diff --git a/README.md b/README.md index f190d97f..0a6b34bb 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ For direct use in a browser script: ```{"language":"html"} - + @@ -149,6 +149,78 @@ webChatApi.postWebchatGuestConversations(createChatBody) .catch(console.error); ``` +## SDK Logging + +Logging of API requests and responses can be controlled by a number of parameters on the `Configuration`'s `Logger` instance. + +`log_level` values: +1. LTrace (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers, Response Headers) +2. LDebug (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers) +3. LError (HTTP Method, URL, Request Body, Response Body, HTTP Status Code, Request Headers, Response Headers) +4. LNone - default + +`log_format` values: +1. JSON +2. TEXT - default + +By default, the request and response bodies are not logged because these can contain PII. Be mindful of this data if choosing to log it. +To log to a file, provide a `log_file_path` value. SDK users are responsible for the rotation of the log file. This feature is not available in browser-based applications. + +Example logging configuration: +```{"language":"javascript"} +client.config.logger.log_level = client.config.logger.logLevelEnum.level.LTrace; +client.config.logger.log_format = client.config.logger.logFormatEnum.formats.JSON; +client.config.logger.log_request_body = true; +client.config.logger.log_response_body = true; +client.config.logger.log_to_console = true; +client.config.logger.log_file_path = "/var/log/javascriptguestsdk.log"; + +client.config.logger.setLogger(); // To apply above changes +``` + +#### Configuration file + +**Note:** This feature is not available in browser-based applications + +A number of configuration parameters can be applied using a configuration file. There are two sources for this file: + +1. The SDK will look for `%USERPROFILE%\.genesyscloudjavascript-guest\config` on Windows if the environment variable USERPROFILE is defined, otherwise uses the path to the profile directory of the current user as home, or `$HOME/.genesyscloudjavascript-guest/config` on Unix. +2. Provide a valid file path to `client.config.setConfigPath()` + +The SDK will constantly check to see if the config file has been updated, regardless of whether a config file was present at start-up. To disable this behaviour, set `client.config.live_reload_config` to false. +INI and JSON formats are supported. See below for examples of configuration values in both formats: + +INI: +```{"language":"ini"} +[logging] +log_level = trace +log_format = text +log_to_console = false +log_file_path = /var/log/javascriptguestsdk.log +log_response_body = false +log_request_body = false +[general] +live_reload_config = true +host = https://api.mypurecloud.com +``` + +JSON: +```{"language":"json"} +{ + "logging": { + "log_level": "trace", + "log_format": "text", + "log_to_console": false, + "log_file_path": "/var/log/javascriptguestsdk.log", + "log_response_body": false, + "log_request_body": false + }, + "general": { + "live_reload_config": true, + "host": "https://api.mypurecloud.com" + } +} +``` ## Environments @@ -281,16 +353,6 @@ Example error response object: ``` -## Debug Logging - -There are hooks to trace requests and responses. To enable debug tracing, provide a log object. Optionally, specify a maximum number of lines. If specified, the response body trace will be truncated. If not specified, the entire response body will be traced out. - -```{"language":"javascript"} -const client = platformClient.ApiClient.instance; -client.setDebugLog(console.log, 25); -``` - - ## Versioning The SDK's version is incremented according to the [Semantic Versioning Specification](https://semver.org/). The decision to increment version numbers is determined by [diffing the Platform API's swagger](https://github.com/purecloudlabs/platform-client-sdk-common/blob/master/modules/swaggerDiff.js) for automated builds, and optionally forcing a version bump when a build is triggered manually (e.g. releasing a bugfix). diff --git a/build/README.md b/build/README.md index f190d97f..0a6b34bb 100644 --- a/build/README.md +++ b/build/README.md @@ -31,7 +31,7 @@ For direct use in a browser script: ```{"language":"html"} - + @@ -149,6 +149,78 @@ webChatApi.postWebchatGuestConversations(createChatBody) .catch(console.error); ``` +## SDK Logging + +Logging of API requests and responses can be controlled by a number of parameters on the `Configuration`'s `Logger` instance. + +`log_level` values: +1. LTrace (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers, Response Headers) +2. LDebug (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers) +3. LError (HTTP Method, URL, Request Body, Response Body, HTTP Status Code, Request Headers, Response Headers) +4. LNone - default + +`log_format` values: +1. JSON +2. TEXT - default + +By default, the request and response bodies are not logged because these can contain PII. Be mindful of this data if choosing to log it. +To log to a file, provide a `log_file_path` value. SDK users are responsible for the rotation of the log file. This feature is not available in browser-based applications. + +Example logging configuration: +```{"language":"javascript"} +client.config.logger.log_level = client.config.logger.logLevelEnum.level.LTrace; +client.config.logger.log_format = client.config.logger.logFormatEnum.formats.JSON; +client.config.logger.log_request_body = true; +client.config.logger.log_response_body = true; +client.config.logger.log_to_console = true; +client.config.logger.log_file_path = "/var/log/javascriptguestsdk.log"; + +client.config.logger.setLogger(); // To apply above changes +``` + +#### Configuration file + +**Note:** This feature is not available in browser-based applications + +A number of configuration parameters can be applied using a configuration file. There are two sources for this file: + +1. The SDK will look for `%USERPROFILE%\.genesyscloudjavascript-guest\config` on Windows if the environment variable USERPROFILE is defined, otherwise uses the path to the profile directory of the current user as home, or `$HOME/.genesyscloudjavascript-guest/config` on Unix. +2. Provide a valid file path to `client.config.setConfigPath()` + +The SDK will constantly check to see if the config file has been updated, regardless of whether a config file was present at start-up. To disable this behaviour, set `client.config.live_reload_config` to false. +INI and JSON formats are supported. See below for examples of configuration values in both formats: + +INI: +```{"language":"ini"} +[logging] +log_level = trace +log_format = text +log_to_console = false +log_file_path = /var/log/javascriptguestsdk.log +log_response_body = false +log_request_body = false +[general] +live_reload_config = true +host = https://api.mypurecloud.com +``` + +JSON: +```{"language":"json"} +{ + "logging": { + "log_level": "trace", + "log_format": "text", + "log_to_console": false, + "log_file_path": "/var/log/javascriptguestsdk.log", + "log_response_body": false, + "log_request_body": false + }, + "general": { + "live_reload_config": true, + "host": "https://api.mypurecloud.com" + } +} +``` ## Environments @@ -281,16 +353,6 @@ Example error response object: ``` -## Debug Logging - -There are hooks to trace requests and responses. To enable debug tracing, provide a log object. Optionally, specify a maximum number of lines. If specified, the response body trace will be truncated. If not specified, the entire response body will be traced out. - -```{"language":"javascript"} -const client = platformClient.ApiClient.instance; -client.setDebugLog(console.log, 25); -``` - - ## Versioning The SDK's version is incremented according to the [Semantic Versioning Specification](https://semver.org/). The decision to increment version numbers is determined by [diffing the Platform API's swagger](https://github.com/purecloudlabs/platform-client-sdk-common/blob/master/modules/swaggerDiff.js) for automated builds, and optionally forcing a version bump when a build is triggered manually (e.g. releasing a bugfix). diff --git a/build/dist/node/purecloud-guest-chat-client.js b/build/dist/node/purecloud-guest-chat-client.js index 7111affb..0b473798 100644 --- a/build/dist/node/purecloud-guest-chat-client.js +++ b/build/dist/node/purecloud-guest-chat-client.js @@ -16,9 +16,358 @@ var PureCloudRegionHosts = { eu_west_2: "euw2.pure.cloud" } +const logLevels = { + levels: { + none: 0, + error: 1, + debug: 2, + trace: 3, + }, +}; + +const logLevelEnum = { + level: { + LNone: 'none', + LError: 'error', + LDebug: 'debug', + LTrace: 'trace', + }, +}; + +const logFormatEnum = { + formats: { + JSON: 'json', + TEXT: 'text', + }, +}; + +class Logger { + get logLevelEnum() { + return logLevelEnum; + } + + get logFormatEnum() { + return logFormatEnum; + } + + constructor() { + this.log_level = logLevelEnum.level.LNone; + this.log_format = logFormatEnum.formats.TEXT; + this.log_to_console = true; + this.log_file_path; + this.log_response_body = false; + this.log_request_body = false; + + this.setLogger(); + } + + setLogger() { + if(typeof window === 'undefined') { + const winston = require('winston'); + this.logger = winston.createLogger({ + levels: logLevels.levels, + level: this.log_level, + }); + if (this.log_file_path && this.log_file_path !== '') { + if (this.log_format === logFormatEnum.formats.JSON) { + this.logger.add(new winston.transports.File({ format: winston.format.json(), filename: this.log_file_path })); + } else { + this.logger.add( + new winston.transports.File({ + format: winston.format.combine( + winston.format((info) => { + info.level = info.level.toUpperCase(); + return info; + })(), + winston.format.simple() + ), + filename: this.log_file_path, + }) + ); + } + } + if (this.log_to_console) { + if (this.log_format === logFormatEnum.formats.JSON) { + this.logger.add(new winston.transports.Console({ format: winston.format.json() })); + } else { + this.logger.add( + new winston.transports.Console({ + format: winston.format.combine( + winston.format((info) => { + info.level = info.level.toUpperCase(); + return info; + })(), + winston.format.simple() + ), + }) + ); + } + } + } + } + + log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody); + if (typeof window !== 'undefined') { + var shouldLog = this.calculateLogLevel(level); + if (shouldLog > 0 && this.log_to_console === true) { + if(this.log_format === this.logFormatEnum.formats.JSON) { + console.log(content); + } else { + console.log(`${level.toUpperCase()}: ${content}`); + } + } + } else { + if (this.logger.transports.length > 0) this.logger.log(level, content); + } + } + + calculateLogLevel(level) { + switch (this.log_level) { + case this.logLevelEnum.level.LError: + if (level !== this.logLevelEnum.level.LError) { + return -1; + } + return 1; + case this.logLevelEnum.level.LDebug: + if (level === this.logLevelEnum.level.LTrace) { + return -1; + } + return 1; + case this.logLevelEnum.level.LTrace: + return 1; + default: + return -1; + } + } + + formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var result; + if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]'; + if (!this.log_request_body) requestBody = undefined; + if (!this.log_response_body) responseBody = undefined; + if (this.log_format && this.log_format === logFormatEnum.formats.JSON) { + result = { + level: level, + date: new Date().toISOString(), + method: method, + url: decodeURIComponent(url), + correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '', + statusCode: statusCode, + }; + if (requestHeaders) result.requestHeaders = requestHeaders; + if (responseHeaders) result.responseHeaders = responseHeaders; + if (requestBody) result.requestBody = requestBody; + if (responseBody) result.responseBody = responseBody; + } else { + result = `${new Date().toISOString()} +=== REQUEST === +${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue( + 'Headers', + this.formatHeaderString(requestHeaders) + )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')} +=== RESPONSE === +${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue( + 'CorrelationId', + responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '' + )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`; + } + + return result; + } + + formatHeaderString(headers) { + var headerString = ''; + if (!headers) return headerString; + for (const [key, value] of Object.entries(headers)) { + headerString += `\n\t${key}: ${value}`; + } + return headerString; + } + + formatValue(key, value) { + if (!value || value === '' || value === '{}') return ''; + return `${key}: ${value}\n`; + } + + getLogLevel(level) { + switch (level) { + case 'error': + return logLevelEnum.level.LError; + case 'debug': + return logLevelEnum.level.LDebug; + case 'trace': + return logLevelEnum.level.LTrace; + default: + return logLevelEnum.level.LNone; + } + } + + getLogFormat(format) { + switch (format) { + case 'json': + return logFormatEnum.formats.JSON; + default: + return logFormatEnum.formats.TEXT; + } + } +} + +class Configuration { + /** + * Singleton getter + */ + get instance() { + return Configuration.instance; + } + + /** + * Singleton setter + */ + set instance(value) { + Configuration.instance = value; + } + + constructor() { + if (!Configuration.instance) { + Configuration.instance = this; + } + + if (typeof window !== 'undefined') { + this.configPath = ''; + } else { + const os = require('os'); + const path = require('path'); + this.configPath = path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config'); + } + + this.live_reload_config = true; + this.host; + this.environment; + this.basePath; + this.authUrl; + this.config; + this.logger = new Logger(); + this.setEnvironment(); + this.liveLoadConfig(); + } + + liveLoadConfig() { + // If in browser, don't read config file, use default values + if (typeof window !== 'undefined') { + this.configPath = ''; + return; + } + + this.updateConfigFromFile(); + + if (this.live_reload_config && this.live_reload_config === true) { + try { + const fs = require('fs'); + fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => { + this.updateConfigFromFile(); + if (!this.live_reload_config) { + fs.unwatchFile(this.configPath); + } + }); + } catch (err) { + // do nothing + } + } + } + + setConfigPath(path) { + if (path && path !== this.configPath) { + this.configPath = path; + this.liveLoadConfig(); + } + } + + updateConfigFromFile() { + const ConfigParser = require('configparser'); + var configparser = new ConfigParser(); + + try { + configparser.read(this.configPath); // If no error catched, indicates it's INI format + this.config = configparser; + } catch (error) { + if (error.name && error.name === 'MissingSectionHeaderError') { + // Not INI format, see if it's JSON format + const fs = require('fs'); + var configData = fs.readFileSync(this.configPath, 'utf8'); + this.config = { + _sections: JSON.parse(configData), // To match INI data format + }; + } + } + + if (this.config) this.updateConfigValues(); + } + + updateConfigValues() { + this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level')); + this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format')); + this.logger.log_to_console = + this.getConfigBoolean('logging', 'log_to_console') !== undefined + ? this.getConfigBoolean('logging', 'log_to_console') + : this.logger.log_to_console; + this.logger.log_file_path = + this.getConfigString('logging', 'log_file_path') !== undefined + ? this.getConfigString('logging', 'log_file_path') + : this.logger.log_file_path; + this.logger.log_response_body = + this.getConfigBoolean('logging', 'log_response_body') !== undefined + ? this.getConfigBoolean('logging', 'log_response_body') + : this.logger.log_response_body; + this.logger.log_request_body = + this.getConfigBoolean('logging', 'log_request_body') !== undefined + ? this.getConfigBoolean('logging', 'log_request_body') + : this.logger.log_request_body; + this.live_reload_config = + this.getConfigBoolean('general', 'live_reload_config') !== undefined + ? this.getConfigBoolean('general', 'live_reload_config') + : this.live_reload_config; + this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host; + + this.setEnvironment(); + + // Update logging configs + this.logger.setLogger(); + } + + setEnvironment(env) { + // Default value + if (env) this.environment = env; + else this.environment = this.host ? this.host : 'mypurecloud.com'; + + // Strip trailing slash + this.environment = this.environment.replace(/\/+$/, ''); + + // Strip protocol and subdomain + if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8); + if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7); + if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4); + + this.basePath = `https://api.${this.environment}`; + this.authUrl = `https://login.${this.environment}`; + } + + getConfigString(section, key) { + if (this.config._sections[section]) return this.config._sections[section][key]; + } + + getConfigBoolean(section, key) { + if (this.config._sections[section] && this.config._sections[section][key] !== undefined) { + if (typeof this.config._sections[section][key] === 'string') { + return this.config._sections[section][key] === 'true'; + } else return this.config._sections[section][key]; + } + } +} + /** * @module purecloud-guest-chat-client/ApiClient - * @version 7.1.0 + * @version 7.2.0 */ class ApiClient { /** @@ -95,6 +444,11 @@ class ApiClient { this.hasLocalStorage = false; } + /** + * Create configuration instance for ApiClient and prepare logger. + */ + this.config = new Configuration(); + /** * The base URL against which to resolve every API call's (relative) path. * @type {String} @@ -134,16 +488,6 @@ class ApiClient { if (typeof(window) !== 'undefined') window.ApiClient = this; } - /** - * @description Sets the debug log to enable debug logging - * @param {log} debugLog - In most cases use `console.log` - * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0. - */ - setDebugLog(debugLog, maxLines) { - this.debugLog = debugLog; - this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined; - } - /** * @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned. * @param {boolean} returnExtended - `true` to return extended responses @@ -160,7 +504,6 @@ class ApiClient { setPersistSettings(doPersist, prefix) { this.persistSettings = doPersist; this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud'; - this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`); } /** @@ -185,7 +528,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.'); return; } @@ -195,7 +537,6 @@ class ApiClient { // Save updated auth data localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData)); - this._debugTrace('Auth data saved to local storage'); } catch (e) { console.error(e); } @@ -210,7 +551,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.'); return; } @@ -230,24 +570,7 @@ class ApiClient { * @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc. */ setEnvironment(environment) { - if (!environment) - environment = 'mypurecloud.com'; - - // Strip trailing slash - environment = environment.replace(/\/+$/, ''); - - // Strip protocol and subdomain - if (environment.startsWith('https://')) - environment = environment.substring(8); - if (environment.startsWith('http://')) - environment = environment.substring(7); - if (environment.startsWith('api.')) - environment = environment.substring(4); - - // Set vars - this.environment = environment; - this.basePath = `https://api.${environment}`; - this.authUrl = `https://login.${environment}`; + this.config.setEnvironment(environment); } /** @@ -304,7 +627,7 @@ class ApiClient { */ _buildAuthUrl(path, query) { if (!query) query = {}; - return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`); + return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`); } /** @@ -333,7 +656,7 @@ class ApiClient { if (!path.match(/^\//)) { path = `/${path}`; } - var url = this.basePath + path; + var url = this.config.basePath + path; url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { @@ -518,23 +841,6 @@ class ApiClient { request.proxy(this.proxy); } - if(this.debugLog){ - var trace = `[REQUEST] ${httpMethod} ${url}`; - if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){ - trace += `\nPath Params: ${JSON.stringify(pathParams)}`; - } - - if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){ - trace += `\nQuery Params: ${JSON.stringify(queryParams)}`; - } - - if(bodyParam){ - trace += `\nnBody: ${JSON.stringify(bodyParam)}`; - } - - this._debugTrace(trace); - } - // apply authentications this.applyAuthToRequest(request, authNames); @@ -543,7 +849,7 @@ class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //request.set({ 'purecloud-sdk': '7.1.0' }); + //request.set({ 'purecloud-sdk': '7.2.0' }); // set request timeout request.timeout(this.timeout); @@ -605,23 +911,22 @@ class ApiClient { } : response.body ? response.body : response.text; // Debug logging - if (this.debugLog) { - var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`; - if (response.headers) - trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`; - if (response.body) - trace += `\nBody: ${JSON.stringify(response.body,null,2)}`; - - // Log trace message - this._debugTrace(trace); - - // Log stack trace - if (error) - this._debugTrace(error); - } + this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined); + this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined); // Resolve promise if (error) { + // Log error + this.config.logger.log( + 'error', + response.statusCode, + httpMethod, + url, + request.header, + response.headers, + bodyParam, + response.body + ); reject(data); } else { resolve(data); @@ -629,46 +934,13 @@ class ApiClient { }); }); } - - /** - * @description Parses an ISO-8601 string representation of a date value. - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - parseDate(str) { - return new Date(str.replace(/T/i, ' ')); - } - - /** - * @description Logs to the debug log - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - _debugTrace(trace) { - if (!this.debugLog) return; - - if (typeof(trace) === 'string') { - // Truncate - var truncTrace = ''; - var lines = trace.split('\n'); - if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) { - for (var i = 0; i < this.debugLogMaxLines; i++) { - truncTrace += `${lines[i]}\n`; - } - truncTrace += '...response truncated...'; - trace = truncTrace; - } - } - - this.debugLog(trace); - } } class WebChatApi { /** * WebChat service. * @module purecloud-guest-chat-client/api/WebChatApi - * @version 7.1.0 + * @version 7.2.0 */ /** @@ -1047,7 +1319,7 @@ class WebChatApi { * *

* @module purecloud-guest-chat-client/index - * @version 7.1.0 + * @version 7.2.0 */ class platformClient { constructor() { diff --git a/build/dist/web-amd/purecloud-guest-chat-client.js b/build/dist/web-amd/purecloud-guest-chat-client.js index 57c34a09..020cc0ae 100644 --- a/build/dist/web-amd/purecloud-guest-chat-client.js +++ b/build/dist/web-amd/purecloud-guest-chat-client.js @@ -14,9 +14,358 @@ define(['superagent'], function (superagent) { 'use strict'; eu_west_2: "euw2.pure.cloud" } + const logLevels = { + levels: { + none: 0, + error: 1, + debug: 2, + trace: 3, + }, + }; + + const logLevelEnum = { + level: { + LNone: 'none', + LError: 'error', + LDebug: 'debug', + LTrace: 'trace', + }, + }; + + const logFormatEnum = { + formats: { + JSON: 'json', + TEXT: 'text', + }, + }; + + class Logger { + get logLevelEnum() { + return logLevelEnum; + } + + get logFormatEnum() { + return logFormatEnum; + } + + constructor() { + this.log_level = logLevelEnum.level.LNone; + this.log_format = logFormatEnum.formats.TEXT; + this.log_to_console = true; + this.log_file_path; + this.log_response_body = false; + this.log_request_body = false; + + this.setLogger(); + } + + setLogger() { + if(typeof window === 'undefined') { + const winston = require('winston'); + this.logger = winston.createLogger({ + levels: logLevels.levels, + level: this.log_level, + }); + if (this.log_file_path && this.log_file_path !== '') { + if (this.log_format === logFormatEnum.formats.JSON) { + this.logger.add(new winston.transports.File({ format: winston.format.json(), filename: this.log_file_path })); + } else { + this.logger.add( + new winston.transports.File({ + format: winston.format.combine( + winston.format((info) => { + info.level = info.level.toUpperCase(); + return info; + })(), + winston.format.simple() + ), + filename: this.log_file_path, + }) + ); + } + } + if (this.log_to_console) { + if (this.log_format === logFormatEnum.formats.JSON) { + this.logger.add(new winston.transports.Console({ format: winston.format.json() })); + } else { + this.logger.add( + new winston.transports.Console({ + format: winston.format.combine( + winston.format((info) => { + info.level = info.level.toUpperCase(); + return info; + })(), + winston.format.simple() + ), + }) + ); + } + } + } + } + + log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody); + if (typeof window !== 'undefined') { + var shouldLog = this.calculateLogLevel(level); + if (shouldLog > 0 && this.log_to_console === true) { + if(this.log_format === this.logFormatEnum.formats.JSON) { + console.log(content); + } else { + console.log(`${level.toUpperCase()}: ${content}`); + } + } + } else { + if (this.logger.transports.length > 0) this.logger.log(level, content); + } + } + + calculateLogLevel(level) { + switch (this.log_level) { + case this.logLevelEnum.level.LError: + if (level !== this.logLevelEnum.level.LError) { + return -1; + } + return 1; + case this.logLevelEnum.level.LDebug: + if (level === this.logLevelEnum.level.LTrace) { + return -1; + } + return 1; + case this.logLevelEnum.level.LTrace: + return 1; + default: + return -1; + } + } + + formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var result; + if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]'; + if (!this.log_request_body) requestBody = undefined; + if (!this.log_response_body) responseBody = undefined; + if (this.log_format && this.log_format === logFormatEnum.formats.JSON) { + result = { + level: level, + date: new Date().toISOString(), + method: method, + url: decodeURIComponent(url), + correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '', + statusCode: statusCode, + }; + if (requestHeaders) result.requestHeaders = requestHeaders; + if (responseHeaders) result.responseHeaders = responseHeaders; + if (requestBody) result.requestBody = requestBody; + if (responseBody) result.responseBody = responseBody; + } else { + result = `${new Date().toISOString()} +=== REQUEST === +${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue( + 'Headers', + this.formatHeaderString(requestHeaders) + )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')} +=== RESPONSE === +${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue( + 'CorrelationId', + responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '' + )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`; + } + + return result; + } + + formatHeaderString(headers) { + var headerString = ''; + if (!headers) return headerString; + for (const [key, value] of Object.entries(headers)) { + headerString += `\n\t${key}: ${value}`; + } + return headerString; + } + + formatValue(key, value) { + if (!value || value === '' || value === '{}') return ''; + return `${key}: ${value}\n`; + } + + getLogLevel(level) { + switch (level) { + case 'error': + return logLevelEnum.level.LError; + case 'debug': + return logLevelEnum.level.LDebug; + case 'trace': + return logLevelEnum.level.LTrace; + default: + return logLevelEnum.level.LNone; + } + } + + getLogFormat(format) { + switch (format) { + case 'json': + return logFormatEnum.formats.JSON; + default: + return logFormatEnum.formats.TEXT; + } + } + } + + class Configuration { + /** + * Singleton getter + */ + get instance() { + return Configuration.instance; + } + + /** + * Singleton setter + */ + set instance(value) { + Configuration.instance = value; + } + + constructor() { + if (!Configuration.instance) { + Configuration.instance = this; + } + + if (typeof window !== 'undefined') { + this.configPath = ''; + } else { + const os = require('os'); + const path = require('path'); + this.configPath = path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config'); + } + + this.live_reload_config = true; + this.host; + this.environment; + this.basePath; + this.authUrl; + this.config; + this.logger = new Logger(); + this.setEnvironment(); + this.liveLoadConfig(); + } + + liveLoadConfig() { + // If in browser, don't read config file, use default values + if (typeof window !== 'undefined') { + this.configPath = ''; + return; + } + + this.updateConfigFromFile(); + + if (this.live_reload_config && this.live_reload_config === true) { + try { + const fs = require('fs'); + fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => { + this.updateConfigFromFile(); + if (!this.live_reload_config) { + fs.unwatchFile(this.configPath); + } + }); + } catch (err) { + // do nothing + } + } + } + + setConfigPath(path) { + if (path && path !== this.configPath) { + this.configPath = path; + this.liveLoadConfig(); + } + } + + updateConfigFromFile() { + const ConfigParser = require('configparser'); + var configparser = new ConfigParser(); + + try { + configparser.read(this.configPath); // If no error catched, indicates it's INI format + this.config = configparser; + } catch (error) { + if (error.name && error.name === 'MissingSectionHeaderError') { + // Not INI format, see if it's JSON format + const fs = require('fs'); + var configData = fs.readFileSync(this.configPath, 'utf8'); + this.config = { + _sections: JSON.parse(configData), // To match INI data format + }; + } + } + + if (this.config) this.updateConfigValues(); + } + + updateConfigValues() { + this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level')); + this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format')); + this.logger.log_to_console = + this.getConfigBoolean('logging', 'log_to_console') !== undefined + ? this.getConfigBoolean('logging', 'log_to_console') + : this.logger.log_to_console; + this.logger.log_file_path = + this.getConfigString('logging', 'log_file_path') !== undefined + ? this.getConfigString('logging', 'log_file_path') + : this.logger.log_file_path; + this.logger.log_response_body = + this.getConfigBoolean('logging', 'log_response_body') !== undefined + ? this.getConfigBoolean('logging', 'log_response_body') + : this.logger.log_response_body; + this.logger.log_request_body = + this.getConfigBoolean('logging', 'log_request_body') !== undefined + ? this.getConfigBoolean('logging', 'log_request_body') + : this.logger.log_request_body; + this.live_reload_config = + this.getConfigBoolean('general', 'live_reload_config') !== undefined + ? this.getConfigBoolean('general', 'live_reload_config') + : this.live_reload_config; + this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host; + + this.setEnvironment(); + + // Update logging configs + this.logger.setLogger(); + } + + setEnvironment(env) { + // Default value + if (env) this.environment = env; + else this.environment = this.host ? this.host : 'mypurecloud.com'; + + // Strip trailing slash + this.environment = this.environment.replace(/\/+$/, ''); + + // Strip protocol and subdomain + if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8); + if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7); + if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4); + + this.basePath = `https://api.${this.environment}`; + this.authUrl = `https://login.${this.environment}`; + } + + getConfigString(section, key) { + if (this.config._sections[section]) return this.config._sections[section][key]; + } + + getConfigBoolean(section, key) { + if (this.config._sections[section] && this.config._sections[section][key] !== undefined) { + if (typeof this.config._sections[section][key] === 'string') { + return this.config._sections[section][key] === 'true'; + } else return this.config._sections[section][key]; + } + } + } + /** * @module purecloud-guest-chat-client/ApiClient - * @version 7.1.0 + * @version 7.2.0 */ class ApiClient { /** @@ -93,6 +442,11 @@ define(['superagent'], function (superagent) { 'use strict'; this.hasLocalStorage = false; } + /** + * Create configuration instance for ApiClient and prepare logger. + */ + this.config = new Configuration(); + /** * The base URL against which to resolve every API call's (relative) path. * @type {String} @@ -132,16 +486,6 @@ define(['superagent'], function (superagent) { 'use strict'; if (typeof(window) !== 'undefined') window.ApiClient = this; } - /** - * @description Sets the debug log to enable debug logging - * @param {log} debugLog - In most cases use `console.log` - * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0. - */ - setDebugLog(debugLog, maxLines) { - this.debugLog = debugLog; - this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined; - } - /** * @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned. * @param {boolean} returnExtended - `true` to return extended responses @@ -158,7 +502,6 @@ define(['superagent'], function (superagent) { 'use strict'; setPersistSettings(doPersist, prefix) { this.persistSettings = doPersist; this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud'; - this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`); } /** @@ -183,7 +526,6 @@ define(['superagent'], function (superagent) { 'use strict'; // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.'); return; } @@ -193,7 +535,6 @@ define(['superagent'], function (superagent) { 'use strict'; // Save updated auth data localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData)); - this._debugTrace('Auth data saved to local storage'); } catch (e) { console.error(e); } @@ -208,7 +549,6 @@ define(['superagent'], function (superagent) { 'use strict'; // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.'); return; } @@ -228,24 +568,7 @@ define(['superagent'], function (superagent) { 'use strict'; * @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc. */ setEnvironment(environment) { - if (!environment) - environment = 'mypurecloud.com'; - - // Strip trailing slash - environment = environment.replace(/\/+$/, ''); - - // Strip protocol and subdomain - if (environment.startsWith('https://')) - environment = environment.substring(8); - if (environment.startsWith('http://')) - environment = environment.substring(7); - if (environment.startsWith('api.')) - environment = environment.substring(4); - - // Set vars - this.environment = environment; - this.basePath = `https://api.${environment}`; - this.authUrl = `https://login.${environment}`; + this.config.setEnvironment(environment); } /** @@ -302,7 +625,7 @@ define(['superagent'], function (superagent) { 'use strict'; */ _buildAuthUrl(path, query) { if (!query) query = {}; - return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`); + return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`); } /** @@ -331,7 +654,7 @@ define(['superagent'], function (superagent) { 'use strict'; if (!path.match(/^\//)) { path = `/${path}`; } - var url = this.basePath + path; + var url = this.config.basePath + path; url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { @@ -516,23 +839,6 @@ define(['superagent'], function (superagent) { 'use strict'; request.proxy(this.proxy); } - if(this.debugLog){ - var trace = `[REQUEST] ${httpMethod} ${url}`; - if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){ - trace += `\nPath Params: ${JSON.stringify(pathParams)}`; - } - - if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){ - trace += `\nQuery Params: ${JSON.stringify(queryParams)}`; - } - - if(bodyParam){ - trace += `\nnBody: ${JSON.stringify(bodyParam)}`; - } - - this._debugTrace(trace); - } - // apply authentications this.applyAuthToRequest(request, authNames); @@ -541,7 +847,7 @@ define(['superagent'], function (superagent) { 'use strict'; // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //request.set({ 'purecloud-sdk': '7.1.0' }); + //request.set({ 'purecloud-sdk': '7.2.0' }); // set request timeout request.timeout(this.timeout); @@ -603,23 +909,22 @@ define(['superagent'], function (superagent) { 'use strict'; } : response.body ? response.body : response.text; // Debug logging - if (this.debugLog) { - var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`; - if (response.headers) - trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`; - if (response.body) - trace += `\nBody: ${JSON.stringify(response.body,null,2)}`; - - // Log trace message - this._debugTrace(trace); - - // Log stack trace - if (error) - this._debugTrace(error); - } + this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined); + this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined); // Resolve promise if (error) { + // Log error + this.config.logger.log( + 'error', + response.statusCode, + httpMethod, + url, + request.header, + response.headers, + bodyParam, + response.body + ); reject(data); } else { resolve(data); @@ -627,46 +932,13 @@ define(['superagent'], function (superagent) { 'use strict'; }); }); } - - /** - * @description Parses an ISO-8601 string representation of a date value. - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - parseDate(str) { - return new Date(str.replace(/T/i, ' ')); - } - - /** - * @description Logs to the debug log - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - _debugTrace(trace) { - if (!this.debugLog) return; - - if (typeof(trace) === 'string') { - // Truncate - var truncTrace = ''; - var lines = trace.split('\n'); - if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) { - for (var i = 0; i < this.debugLogMaxLines; i++) { - truncTrace += `${lines[i]}\n`; - } - truncTrace += '...response truncated...'; - trace = truncTrace; - } - } - - this.debugLog(trace); - } } class WebChatApi { /** * WebChat service. * @module purecloud-guest-chat-client/api/WebChatApi - * @version 7.1.0 + * @version 7.2.0 */ /** @@ -1045,7 +1317,7 @@ define(['superagent'], function (superagent) { 'use strict'; * *

* @module purecloud-guest-chat-client/index - * @version 7.1.0 + * @version 7.2.0 */ class platformClient { constructor() { diff --git a/build/dist/web-amd/purecloud-guest-chat-client.min.js b/build/dist/web-amd/purecloud-guest-chat-client.min.js index e1806a51..d25628f0 100644 --- a/build/dist/web-amd/purecloud-guest-chat-client.min.js +++ b/build/dist/web-amd/purecloud-guest-chat-client.min.js @@ -1 +1 @@ -define(["superagent"],function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var t={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud"};class a{get instance(){return a.instance}set instance(e){a.instance=e}constructor(){a.instance||(a.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(e){this.hasLocalStorage=!1}this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=e,"undefined"!=typeof window&&(window.ApiClient=this)}setDebugLog(e,t){this.debugLog=e,this.debugLogMaxLines=t&&t>0?t:void 0}setReturnExtendedResponses(e){this.returnExtended=e}setPersistSettings(e,t){this.persistSettings=e,this.settingsPrefix=t?t.replace(/\W+/g,"_"):"purecloud",this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`)}_saveSettings(e){try{if(this.authData.apiKey=e.apiKey,this.authentications["Guest Chat JWT"].apiKey=e.apiKey,e.state&&(this.authData.state=e.state),e.tokenExpiryTime&&(this.authData.tokenExpiryTime=e.tokenExpiryTime,this.authData.tokenExpiryTimeString=e.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return void this._debugTrace("Warning: Cannot access local storage. Settings will not be saved.");let t=JSON.parse(JSON.stringify(this.authData));delete t.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(t)),this._debugTrace("Auth data saved to local storage")}catch(e){console.error(e)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return void this._debugTrace("Warning: Cannot access local storage. Settings will not be loaded.");const e=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=e}setEnvironment(e){e||(e="mypurecloud.com"),(e=e.replace(/\/+$/,"")).startsWith("https://")&&(e=e.substring(8)),e.startsWith("http://")&&(e=e.substring(7)),e.startsWith("api.")&&(e=e.substring(4)),this.environment=e,this.basePath=`https://api.${e}`,this.authUrl=`https://login.${e}`}_testTokenAccess(){return new Promise((e,t)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{e()}).catch(e=>{this._saveSettings({apiKey:void 0}),t(e)}):t(new Error("Token is not set"))})}setJwt(e){this._saveSettings({apiKey:e})}setStorageKey(e){this.storageKey=e,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(e,t){return t||(t={}),Object.keys(t).reduce((e,a)=>t[a]?`${e}&${a}=${t[a]}`:e,`${this.authUrl}/${e}?`)}paramToString(e){return e?e instanceof Date?e.toJSON():e.toString():""}buildUrl(e,t){e.match(/^\//)||(e=`/${e}`);var a=this.basePath+e;return a=a.replace(/\{([\w-]+)\}/g,(e,a)=>{var i;return i=t.hasOwnProperty(a)?this.paramToString(t[a]):e,encodeURIComponent(i)})}isJsonMime(e){return Boolean(e&&e.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(e){for(var t=0;t{var a=this.authentications[t];switch(a.type){case"basic":(a.username||a.password)&&e.auth(a.username||"",a.password||"");break;case"apiKey":if(a.apiKey){var i={};a.apiKeyPrefix?i[a.name]=`${a.apiKeyPrefix} ${a.apiKey}`:i[a.name]=a.apiKey,"header"===a.in?e.set(i):e.query(i)}break;case"oauth2":a.accessToken&&e.set({Authorization:`Bearer ${a.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${a.type}`)}})}callApi(t,a,i,s,n,r,o,u,h,l){var c=this.buildUrl(t,i),p=e(a,c);if(this.proxy&&p.proxy&&p.proxy(this.proxy),this.debugLog){var d=`[REQUEST] ${a} ${c}`;i&&Object.keys(i).count>0&&i[Object.keys(i)[0]]&&(d+=`\nPath Params: ${JSON.stringify(i)}`),s&&Object.keys(s).count>0&&s[Object.keys(s)[0]]&&(d+=`\nQuery Params: ${JSON.stringify(s)}`),o&&(d+=`\nnBody: ${JSON.stringify(o)}`),this._debugTrace(d)}this.applyAuthToRequest(p,u),p.query(this.normalizeParams(s)),p.set(this.defaultHeaders).set(this.normalizeParams(n)),p.timeout(this.timeout);var g=this.jsonPreferredMime(h);if(g?p.type(g):p.header["Content-Type"]||p.type("application/json"),"application/x-www-form-urlencoded"===g)p.send(this.normalizeParams(r));else if("multipart/form-data"==g){var m=this.normalizeParams(r);for(var v in m)m.hasOwnProperty(v)&&(this.isFileParam(m[v])?p.attach(v,m[v]):p.field(v,m[v]))}else o&&p.send(o);var b=this.jsonPreferredMime(l);return b&&p.accept(b),new Promise((e,t)=>{p.end((i,s)=>{if(!i||s){var n=!0===this.returnExtended||i?{status:s.status,statusText:s.statusText,headers:s.headers,body:s.body,text:s.text,error:i}:s.body?s.body:s.text;if(this.debugLog){var r=`[RESPONSE] ${s.status}: ${a} ${c}`;s.headers&&(r+=`\ninin-correlation-id: ${s.headers["inin-correlation-id"]}`),s.body&&(r+=`\nBody: ${JSON.stringify(s.body,null,2)}`),this._debugTrace(r),i&&this._debugTrace(i)}i?t(n):e(n)}else t({status:0,statusText:"error",headers:[],body:{},text:"error",error:i})})})}parseDate(e){return new Date(e.replace(/T/i," "))}_debugTrace(e){if(this.debugLog){if("string"==typeof e){var t="",a=e.split("\n");if(this.debugLogMaxLines&&a.length>this.debugLogMaxLines){for(var i=0;i(e.level=e.level.toUpperCase(),e))(),e.format.simple()),filename:this.log_file_path}))),this.log_to_console&&(this.log_format===o.formats.JSON?this.logger.add(new e.transports.Console({format:e.format.json()})):this.logger.add(new e.transports.Console({format:e.format.combine(e.format(e=>(e.level=e.level.toUpperCase(),e))(),e.format.simple())})))}}log(e,t,i,s,o,n,a,r){var l=this.formatLog(e,t,i,s,o,n,a,r);"undefined"!=typeof window?this.calculateLogLevel(e)>0&&!0===this.log_to_console&&(this.log_format===this.logFormatEnum.formats.JSON?console.log(l):console.log(`${e.toUpperCase()}: ${l}`)):this.logger.transports.length>0&&this.logger.log(e,l)}calculateLogLevel(e){switch(this.log_level){case this.logLevelEnum.level.LError:return e!==this.logLevelEnum.level.LError?-1:1;case this.logLevelEnum.level.LDebug:return e===this.logLevelEnum.level.LTrace?-1:1;case this.logLevelEnum.level.LTrace:return 1;default:return-1}}formatLog(e,t,i,s,n,a,r,l){var h;return n&&(n.Authorization="[REDACTED]"),this.log_request_body||(r=void 0),this.log_response_body||(l=void 0),this.log_format&&this.log_format===o.formats.JSON?(h={level:e,date:(new Date).toISOString(),method:i,url:decodeURIComponent(s),correlationId:a&&a["inin-correlation-id"]?a["inin-correlation-id"]:"",statusCode:t},n&&(h.requestHeaders=n),a&&(h.responseHeaders=a),r&&(h.requestBody=r),l&&(h.responseBody=l)):h=`${(new Date).toISOString()}\n=== REQUEST === \n${this.formatValue("URL",decodeURIComponent(s))}${this.formatValue("Method",i)}${this.formatValue("Headers",this.formatHeaderString(n))}${this.formatValue("Body",r?JSON.stringify(r,null,2):"")}\n=== RESPONSE ===\n${this.formatValue("Status",t)}${this.formatValue("Headers",this.formatHeaderString(a))}${this.formatValue("CorrelationId",a&&a["inin-correlation-id"]?a["inin-correlation-id"]:"")}${this.formatValue("Body",l?JSON.stringify(l,null,2):"")}`,h}formatHeaderString(e){var t="";if(!e)return t;for(const[i,s]of Object.entries(e))t+=`\n\t${i}: ${s}`;return t}formatValue(e,t){return t&&""!==t&&"{}"!==t?`${e}: ${t}\n`:""}getLogLevel(e){switch(e){case"error":return s.level.LError;case"debug":return s.level.LDebug;case"trace":return s.level.LTrace;default:return s.level.LNone}}getLogFormat(e){switch(e){case"json":return o.formats.JSON;default:return o.formats.TEXT}}}class a{get instance(){return a.instance}set instance(e){a.instance=e}constructor(){if(a.instance||(a.instance=this),"undefined"!=typeof window)this.configPath="";else{const e=require("os"),t=require("path");this.configPath=t.join(e.homedir(),".genesyscloudjavascript-guest","config")}this.live_reload_config=!0,this.host,this.environment,this.basePath,this.authUrl,this.config,this.logger=new n,this.setEnvironment(),this.liveLoadConfig()}liveLoadConfig(){if("undefined"==typeof window){if(this.updateConfigFromFile(),this.live_reload_config&&!0===this.live_reload_config)try{const e=require("fs");e.watchFile(this.configPath,{persistent:!1},(t,i)=>{this.updateConfigFromFile(),this.live_reload_config||e.unwatchFile(this.configPath)})}catch(e){}}else this.configPath=""}setConfigPath(e){e&&e!==this.configPath&&(this.configPath=e,this.liveLoadConfig())}updateConfigFromFile(){var e=new(require("configparser"));try{e.read(this.configPath),this.config=e}catch(e){if(e.name&&"MissingSectionHeaderError"===e.name){var t=require("fs").readFileSync(this.configPath,"utf8");this.config={_sections:JSON.parse(t)}}}this.config&&this.updateConfigValues()}updateConfigValues(){this.logger.log_level=this.logger.getLogLevel(this.getConfigString("logging","log_level")),this.logger.log_format=this.logger.getLogFormat(this.getConfigString("logging","log_format")),this.logger.log_to_console=void 0!==this.getConfigBoolean("logging","log_to_console")?this.getConfigBoolean("logging","log_to_console"):this.logger.log_to_console,this.logger.log_file_path=void 0!==this.getConfigString("logging","log_file_path")?this.getConfigString("logging","log_file_path"):this.logger.log_file_path,this.logger.log_response_body=void 0!==this.getConfigBoolean("logging","log_response_body")?this.getConfigBoolean("logging","log_response_body"):this.logger.log_response_body,this.logger.log_request_body=void 0!==this.getConfigBoolean("logging","log_request_body")?this.getConfigBoolean("logging","log_request_body"):this.logger.log_request_body,this.live_reload_config=void 0!==this.getConfigBoolean("general","live_reload_config")?this.getConfigBoolean("general","live_reload_config"):this.live_reload_config,this.host=void 0!==this.getConfigString("general","host")?this.getConfigString("general","host"):this.host,this.setEnvironment(),this.logger.setLogger()}setEnvironment(e){this.environment=e||(this.host?this.host:"mypurecloud.com"),this.environment=this.environment.replace(/\/+$/,""),this.environment.startsWith("https://")&&(this.environment=this.environment.substring(8)),this.environment.startsWith("http://")&&(this.environment=this.environment.substring(7)),this.environment.startsWith("api.")&&(this.environment=this.environment.substring(4)),this.basePath=`https://api.${this.environment}`,this.authUrl=`https://login.${this.environment}`}getConfigString(e,t){if(this.config._sections[e])return this.config._sections[e][t]}getConfigBoolean(e,t){if(this.config._sections[e]&&void 0!==this.config._sections[e][t])return"string"==typeof this.config._sections[e][t]?"true"===this.config._sections[e][t]:this.config._sections[e][t]}}class r{get instance(){return r.instance}set instance(e){r.instance=e}constructor(){r.instance||(r.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(e){this.hasLocalStorage=!1}this.config=new a,this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=e,"undefined"!=typeof window&&(window.ApiClient=this)}setReturnExtendedResponses(e){this.returnExtended=e}setPersistSettings(e,t){this.persistSettings=e,this.settingsPrefix=t?t.replace(/\W+/g,"_"):"purecloud"}_saveSettings(e){try{if(this.authData.apiKey=e.apiKey,this.authentications["Guest Chat JWT"].apiKey=e.apiKey,e.state&&(this.authData.state=e.state),e.tokenExpiryTime&&(this.authData.tokenExpiryTime=e.tokenExpiryTime,this.authData.tokenExpiryTimeString=e.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;let t=JSON.parse(JSON.stringify(this.authData));delete t.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(t))}catch(e){console.error(e)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;const e=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=e}setEnvironment(e){this.config.setEnvironment(e)}_testTokenAccess(){return new Promise((e,t)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{e()}).catch(e=>{this._saveSettings({apiKey:void 0}),t(e)}):t(new Error("Token is not set"))})}setJwt(e){this._saveSettings({apiKey:e})}setStorageKey(e){this.storageKey=e,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(e,t){return t||(t={}),Object.keys(t).reduce((e,i)=>t[i]?`${e}&${i}=${t[i]}`:e,`${this.config.authUrl}/${e}?`)}paramToString(e){return e?e instanceof Date?e.toJSON():e.toString():""}buildUrl(e,t){e.match(/^\//)||(e=`/${e}`);var i=this.config.basePath+e;return i=i.replace(/\{([\w-]+)\}/g,(e,i)=>{var s;return s=t.hasOwnProperty(i)?this.paramToString(t[i]):e,encodeURIComponent(s)})}isJsonMime(e){return Boolean(e&&e.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(e){for(var t=0;t{var i=this.authentications[t];switch(i.type){case"basic":(i.username||i.password)&&e.auth(i.username||"",i.password||"");break;case"apiKey":if(i.apiKey){var s={};i.apiKeyPrefix?s[i.name]=`${i.apiKeyPrefix} ${i.apiKey}`:s[i.name]=i.apiKey,"header"===i.in?e.set(s):e.query(s)}break;case"oauth2":i.accessToken&&e.set({Authorization:`Bearer ${i.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${i.type}`)}})}callApi(t,i,s,o,n,a,r,l,h,g){var u=this.buildUrl(t,s),c=e(i,u);this.proxy&&c.proxy&&c.proxy(this.proxy),this.applyAuthToRequest(c,l),c.query(this.normalizeParams(o)),c.set(this.defaultHeaders).set(this.normalizeParams(n)),c.timeout(this.timeout);var d=this.jsonPreferredMime(h);if(d?c.type(d):c.header["Content-Type"]||c.type("application/json"),"application/x-www-form-urlencoded"===d)c.send(this.normalizeParams(a));else if("multipart/form-data"==d){var p=this.normalizeParams(a);for(var m in p)p.hasOwnProperty(m)&&(this.isFileParam(p[m])?c.attach(m,p[m]):c.field(m,p[m]))}else r&&c.send(r);var f=this.jsonPreferredMime(g);return f&&c.accept(f),new Promise((e,t)=>{c.end((s,o)=>{if(!s||o){var n=!0===this.returnExtended||s?{status:o.status,statusText:o.statusText,headers:o.headers,body:o.body,text:o.text,error:s}:o.body?o.body:o.text;this.config.logger.log("trace",o.statusCode,i,u,c.header,o.headers,r,void 0),this.config.logger.log("debug",o.statusCode,i,u,c.header,void 0,r,void 0),s?(this.config.logger.log("error",o.statusCode,i,u,c.header,o.headers,r,o.body),t(n)):e(n)}else t({status:0,statusText:"error",headers:[],body:{},text:"error",error:s})})})}}class l{constructor(e){this.apiClient=e||r.instance}deleteWebchatGuestConversationMember(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling deleteWebchatGuestConversationMember';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling deleteWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","DELETE",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequest(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequest';if(void 0===t||null===t)throw'Missing the required parameter "mediaRequestId" when calling getWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","GET",{conversationId:e,mediaRequestId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequests(e){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequests';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests","GET",{conversationId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMember(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMember';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling getWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","GET",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMembers(e,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMembers';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members","GET",{conversationId:e},{pageSize:t.pageSize,pageNumber:t.pageNumber,excludeDisconnectedMembers:t.excludeDisconnectedMembers},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessage(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessage';if(void 0===t||null===t)throw'Missing the required parameter "messageId" when calling getWebchatGuestConversationMessage';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages/{messageId}","GET",{conversationId:e,messageId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessages(e,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages","GET",{conversationId:e},{after:t.after,before:t.before,sortOrder:t.sortOrder,maxResults:t.maxResults},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}patchWebchatGuestConversationMediarequest(e,t,i){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling patchWebchatGuestConversationMediarequest';if(void 0===t||null===t)throw'Missing the required parameter "mediaRequestId" when calling patchWebchatGuestConversationMediarequest';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling patchWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","PATCH",{conversationId:e,mediaRequestId:t},{},{},{},i,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberMessages(e,t,i){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberMessages';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberMessages';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling postWebchatGuestConversationMemberMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/messages","POST",{conversationId:e,memberId:t},{},{},{},i,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberTyping(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberTyping';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberTyping';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/typing","POST",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversations(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling postWebchatGuestConversations';return this.apiClient.callApi("/api/v2/webchat/guest/conversations","POST",{},{},{},{},e,[],["application/json"],["application/json"])}}return new class{constructor(){this.ApiClient=new r,this.WebChatApi=l,this.PureCloudRegionHosts=t}}}); \ No newline at end of file diff --git a/build/dist/web-cjs/bundle.js b/build/dist/web-cjs/bundle.js index bbb38954..5e41565e 100644 --- a/build/dist/web-cjs/bundle.js +++ b/build/dist/web-cjs/bundle.js @@ -1981,9 +1981,307 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } +const logLevelEnum = { + level: { + LNone: 'none', + LError: 'error', + LDebug: 'debug', + LTrace: 'trace', + }, +}; + +const logFormatEnum = { + formats: { + JSON: 'json', + TEXT: 'text', + }, +}; + +class Logger { + get logLevelEnum() { + return logLevelEnum; + } + + get logFormatEnum() { + return logFormatEnum; + } + + constructor() { + this.log_level = logLevelEnum.level.LNone; + this.log_format = logFormatEnum.formats.TEXT; + this.log_to_console = true; + this.log_file_path; + this.log_response_body = false; + this.log_request_body = false; + + this.setLogger(); + } + + setLogger() { + } + + log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody); + if (typeof window !== 'undefined') { + var shouldLog = this.calculateLogLevel(level); + if (shouldLog > 0 && this.log_to_console === true) { + if(this.log_format === this.logFormatEnum.formats.JSON) { + console.log(content); + } else { + console.log(`${level.toUpperCase()}: ${content}`); + } + } + } else { + if (this.logger.transports.length > 0) this.logger.log(level, content); + } + } + + calculateLogLevel(level) { + switch (this.log_level) { + case this.logLevelEnum.level.LError: + if (level !== this.logLevelEnum.level.LError) { + return -1; + } + return 1; + case this.logLevelEnum.level.LDebug: + if (level === this.logLevelEnum.level.LTrace) { + return -1; + } + return 1; + case this.logLevelEnum.level.LTrace: + return 1; + default: + return -1; + } + } + + formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var result; + if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]'; + if (!this.log_request_body) requestBody = undefined; + if (!this.log_response_body) responseBody = undefined; + if (this.log_format && this.log_format === logFormatEnum.formats.JSON) { + result = { + level: level, + date: new Date().toISOString(), + method: method, + url: decodeURIComponent(url), + correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '', + statusCode: statusCode, + }; + if (requestHeaders) result.requestHeaders = requestHeaders; + if (responseHeaders) result.responseHeaders = responseHeaders; + if (requestBody) result.requestBody = requestBody; + if (responseBody) result.responseBody = responseBody; + } else { + result = `${new Date().toISOString()} +=== REQUEST === +${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue( + 'Headers', + this.formatHeaderString(requestHeaders) + )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')} +=== RESPONSE === +${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue( + 'CorrelationId', + responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '' + )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`; + } + + return result; + } + + formatHeaderString(headers) { + var headerString = ''; + if (!headers) return headerString; + for (const [key, value] of Object.entries(headers)) { + headerString += `\n\t${key}: ${value}`; + } + return headerString; + } + + formatValue(key, value) { + if (!value || value === '' || value === '{}') return ''; + return `${key}: ${value}\n`; + } + + getLogLevel(level) { + switch (level) { + case 'error': + return logLevelEnum.level.LError; + case 'debug': + return logLevelEnum.level.LDebug; + case 'trace': + return logLevelEnum.level.LTrace; + default: + return logLevelEnum.level.LNone; + } + } + + getLogFormat(format) { + switch (format) { + case 'json': + return logFormatEnum.formats.JSON; + default: + return logFormatEnum.formats.TEXT; + } + } +} + +class Configuration { + /** + * Singleton getter + */ + get instance() { + return Configuration.instance; + } + + /** + * Singleton setter + */ + set instance(value) { + Configuration.instance = value; + } + + constructor() { + if (!Configuration.instance) { + Configuration.instance = this; + } + + if (typeof window !== 'undefined') { + this.configPath = ''; + } else { + const os = require('os'); + const path = require('path'); + this.configPath = path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config'); + } + + this.live_reload_config = true; + this.host; + this.environment; + this.basePath; + this.authUrl; + this.config; + this.logger = new Logger(); + this.setEnvironment(); + this.liveLoadConfig(); + } + + liveLoadConfig() { + // If in browser, don't read config file, use default values + if (typeof window !== 'undefined') { + this.configPath = ''; + return; + } + + this.updateConfigFromFile(); + + if (this.live_reload_config && this.live_reload_config === true) { + try { + const fs = require('fs'); + fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => { + this.updateConfigFromFile(); + if (!this.live_reload_config) { + fs.unwatchFile(this.configPath); + } + }); + } catch (err) { + // do nothing + } + } + } + + setConfigPath(path) { + if (path && path !== this.configPath) { + this.configPath = path; + this.liveLoadConfig(); + } + } + + updateConfigFromFile() { + const ConfigParser = require('configparser'); + var configparser = new ConfigParser(); + + try { + configparser.read(this.configPath); // If no error catched, indicates it's INI format + this.config = configparser; + } catch (error) { + if (error.name && error.name === 'MissingSectionHeaderError') { + // Not INI format, see if it's JSON format + const fs = require('fs'); + var configData = fs.readFileSync(this.configPath, 'utf8'); + this.config = { + _sections: JSON.parse(configData), // To match INI data format + }; + } + } + + if (this.config) this.updateConfigValues(); + } + + updateConfigValues() { + this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level')); + this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format')); + this.logger.log_to_console = + this.getConfigBoolean('logging', 'log_to_console') !== undefined + ? this.getConfigBoolean('logging', 'log_to_console') + : this.logger.log_to_console; + this.logger.log_file_path = + this.getConfigString('logging', 'log_file_path') !== undefined + ? this.getConfigString('logging', 'log_file_path') + : this.logger.log_file_path; + this.logger.log_response_body = + this.getConfigBoolean('logging', 'log_response_body') !== undefined + ? this.getConfigBoolean('logging', 'log_response_body') + : this.logger.log_response_body; + this.logger.log_request_body = + this.getConfigBoolean('logging', 'log_request_body') !== undefined + ? this.getConfigBoolean('logging', 'log_request_body') + : this.logger.log_request_body; + this.live_reload_config = + this.getConfigBoolean('general', 'live_reload_config') !== undefined + ? this.getConfigBoolean('general', 'live_reload_config') + : this.live_reload_config; + this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host; + + this.setEnvironment(); + + // Update logging configs + this.logger.setLogger(); + } + + setEnvironment(env) { + // Default value + if (env) this.environment = env; + else this.environment = this.host ? this.host : 'mypurecloud.com'; + + // Strip trailing slash + this.environment = this.environment.replace(/\/+$/, ''); + + // Strip protocol and subdomain + if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8); + if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7); + if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4); + + this.basePath = `https://api.${this.environment}`; + this.authUrl = `https://login.${this.environment}`; + } + + getConfigString(section, key) { + if (this.config._sections[section]) return this.config._sections[section][key]; + } + + getConfigBoolean(section, key) { + if (this.config._sections[section] && this.config._sections[section][key] !== undefined) { + if (typeof this.config._sections[section][key] === 'string') { + return this.config._sections[section][key] === 'true'; + } else return this.config._sections[section][key]; + } + } +} + /** * @module purecloud-guest-chat-client/ApiClient - * @version 7.1.0 + * @version 7.2.0 */ class ApiClient { /** @@ -2060,6 +2358,11 @@ class ApiClient { this.hasLocalStorage = false; } + /** + * Create configuration instance for ApiClient and prepare logger. + */ + this.config = new Configuration(); + /** * The base URL against which to resolve every API call's (relative) path. * @type {String} @@ -2099,16 +2402,6 @@ class ApiClient { if (typeof(window) !== 'undefined') window.ApiClient = this; } - /** - * @description Sets the debug log to enable debug logging - * @param {log} debugLog - In most cases use `console.log` - * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0. - */ - setDebugLog(debugLog, maxLines) { - this.debugLog = debugLog; - this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined; - } - /** * @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned. * @param {boolean} returnExtended - `true` to return extended responses @@ -2125,7 +2418,6 @@ class ApiClient { setPersistSettings(doPersist, prefix) { this.persistSettings = doPersist; this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud'; - this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`); } /** @@ -2150,7 +2442,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.'); return; } @@ -2160,7 +2451,6 @@ class ApiClient { // Save updated auth data localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData)); - this._debugTrace('Auth data saved to local storage'); } catch (e) { console.error(e); } @@ -2175,7 +2465,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.'); return; } @@ -2195,24 +2484,7 @@ class ApiClient { * @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc. */ setEnvironment(environment) { - if (!environment) - environment = 'mypurecloud.com'; - - // Strip trailing slash - environment = environment.replace(/\/+$/, ''); - - // Strip protocol and subdomain - if (environment.startsWith('https://')) - environment = environment.substring(8); - if (environment.startsWith('http://')) - environment = environment.substring(7); - if (environment.startsWith('api.')) - environment = environment.substring(4); - - // Set vars - this.environment = environment; - this.basePath = `https://api.${environment}`; - this.authUrl = `https://login.${environment}`; + this.config.setEnvironment(environment); } /** @@ -2269,7 +2541,7 @@ class ApiClient { */ _buildAuthUrl(path, query) { if (!query) query = {}; - return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`); + return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`); } /** @@ -2298,7 +2570,7 @@ class ApiClient { if (!path.match(/^\//)) { path = `/${path}`; } - var url = this.basePath + path; + var url = this.config.basePath + path; url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { @@ -2476,23 +2748,6 @@ class ApiClient { request.proxy(this.proxy); } - if(this.debugLog){ - var trace = `[REQUEST] ${httpMethod} ${url}`; - if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){ - trace += `\nPath Params: ${JSON.stringify(pathParams)}`; - } - - if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){ - trace += `\nQuery Params: ${JSON.stringify(queryParams)}`; - } - - if(bodyParam){ - trace += `\nnBody: ${JSON.stringify(bodyParam)}`; - } - - this._debugTrace(trace); - } - // apply authentications this.applyAuthToRequest(request, authNames); @@ -2501,7 +2756,7 @@ class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //request.set({ 'purecloud-sdk': '7.1.0' }); + //request.set({ 'purecloud-sdk': '7.2.0' }); // set request timeout request.timeout(this.timeout); @@ -2563,23 +2818,22 @@ class ApiClient { } : response.body ? response.body : response.text; // Debug logging - if (this.debugLog) { - var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`; - if (response.headers) - trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`; - if (response.body) - trace += `\nBody: ${JSON.stringify(response.body,null,2)}`; - - // Log trace message - this._debugTrace(trace); - - // Log stack trace - if (error) - this._debugTrace(error); - } + this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined); + this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined); // Resolve promise if (error) { + // Log error + this.config.logger.log( + 'error', + response.statusCode, + httpMethod, + url, + request.header, + response.headers, + bodyParam, + response.body + ); reject(data); } else { resolve(data); @@ -2587,46 +2841,13 @@ class ApiClient { }); }); } - - /** - * @description Parses an ISO-8601 string representation of a date value. - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - parseDate(str) { - return new Date(str.replace(/T/i, ' ')); - } - - /** - * @description Logs to the debug log - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - _debugTrace(trace) { - if (!this.debugLog) return; - - if (typeof(trace) === 'string') { - // Truncate - var truncTrace = ''; - var lines = trace.split('\n'); - if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) { - for (var i = 0; i < this.debugLogMaxLines; i++) { - truncTrace += `${lines[i]}\n`; - } - truncTrace += '...response truncated...'; - trace = truncTrace; - } - } - - this.debugLog(trace); - } } class WebChatApi { /** * WebChat service. * @module purecloud-guest-chat-client/api/WebChatApi - * @version 7.1.0 + * @version 7.2.0 */ /** @@ -3005,7 +3226,7 @@ class WebChatApi { * *

* @module purecloud-guest-chat-client/index - * @version 7.1.0 + * @version 7.2.0 */ class platformClient { constructor() { diff --git a/build/dist/web-cjs/purecloud-guest-chat-client.js b/build/dist/web-cjs/purecloud-guest-chat-client.js index bae3fffd..13934322 100644 --- a/build/dist/web-cjs/purecloud-guest-chat-client.js +++ b/build/dist/web-cjs/purecloud-guest-chat-client.js @@ -1,4 +1,6 @@ require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m @@ -2018,184 +2020,1875 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],4:[function(require,module,exports){ - -/** - * Expose `Emitter`. - */ - -if (typeof module !== 'undefined') { - 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 +},{}],5:[function(require,module,exports){ +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +exports.homedir = function () { + return '/' +}; + +},{}],6:[function(require,module,exports){ +(function (process){(function (){ +// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, +// backported and transplited with Babel, with backwards-compat fixes + +// 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; +} + +// 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) { + if (typeof path !== 'string') path = path + ''; + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) { + // return '//'; + // Backwards-compat fix: + return '/'; + } + return path.slice(0, end); +}; + +function basename(path) { + if (typeof path !== 'string') path = path + ''; + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); +} + +// Uses a mixed approach for backwards-compatibility, as ext behavior changed +// in new Node.js versions, so only basename() above is backported here +exports.basename = function (path, ext) { + var f = basename(path); + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + +exports.extname = function (path) { + if (typeof path !== 'string') path = path + ''; + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); +}; + +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); + } +; + +}).call(this)}).call(this,require('_process')) +},{"_process":7}],7:[function(require,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(require,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 + } +} + +},{}],9:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],10:[function(require,module,exports){ +(function (process,global){(function (){ +// 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 = process.env.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 = require('./support/isBuffer'); + +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 = require('inherits'); + +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); +} + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":9,"_process":7,"inherits":8}],11:[function(require,module,exports){ + +/** + * Expose `Emitter`. + */ + +if (typeof module !== 'undefined') { + 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; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + 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 = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + 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; +}; + +},{}],12:[function(require,module,exports){ +const util = require('util'); +const fs = require('fs'); +const path = require('path'); +const mkdirp = require('mkdirp'); +const errors = require('./errors'); +const interpolation = require('./interpolation'); + +/** + * Regular Expression to match section headers. + * @type {RegExp} + * @private + */ +const SECTION = new RegExp(/\s*\[([^\]]+)]/); + +/** + * Regular expression to match key, value pairs. + * @type {RegExp} + * @private + */ +const KEY = new RegExp(/\s*(.*?)\s*[=:]\s*(.*)/); + +/** + * Regular expression to match comments. Either starting with a + * semi-colon or a hash. + * @type {RegExp} + * @private + */ +const COMMENT = new RegExp(/^\s*[;#]/); + +// RL1.6 Line Boundaries (for unicode) +// ... it shall recognize not only CRLF, LF, CR, +// but also NEL, PS and LS. +const LINE_BOUNDARY = new RegExp(/\r\n|[\n\r\u0085\u2028\u2029]/g); + +const readFileAsync = util.promisify(fs.readFile); +const writeFileAsync = util.promisify(fs.writeFile); +const statAsync = util.promisify(fs.stat); +const mkdirAsync = util.promisify(mkdirp); + +/** + * @constructor + */ +function ConfigParser() { + this._sections = {}; +} + +/** + * Returns an array of the sections. + * @returns {Array} + */ +ConfigParser.prototype.sections = function() { + return Object.keys(this._sections); +}; + +/** + * Adds a section named section to the instance. If the section already + * exists, a DuplicateSectionError is thrown. + * @param {string} section - Section Name + */ +ConfigParser.prototype.addSection = function(section) { + if(this._sections.hasOwnProperty(section)){ + throw new errors.DuplicateSectionError(section) + } + this._sections[section] = {}; +}; + +/** + * Indicates whether the section is present in the configuration + * file. + * @param {string} section - Section Name + * @returns {boolean} + */ +ConfigParser.prototype.hasSection = function(section) { + return this._sections.hasOwnProperty(section); +}; + +/** + * Returns an array of all keys in the specified section. + * @param {string} section - Section Name + * @returns {Array} + */ +ConfigParser.prototype.keys = function(section) { + try { + return Object.keys(this._sections[section]); + } catch(err){ + throw new errors.NoSectionError(section); + } +}; + +/** + * Indicates whether the specified key is in the section. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @returns {boolean} + */ +ConfigParser.prototype.hasKey = function (section, key) { + return this._sections.hasOwnProperty(section) && + this._sections[section].hasOwnProperty(key); +}; + +/** + * Reads a file and parses the configuration data. + * @param {string|Buffer|int} file - Filename or File Descriptor + */ +ConfigParser.prototype.read = function(file) { + const lines = fs.readFileSync(file) + .toString('utf8') + .split(LINE_BOUNDARY); + parseLines.call(this, file, lines); +}; + +/** + * Reads a file asynchronously and parses the configuration data. + * @param {string|Buffer|int} file - Filename or File Descriptor + */ +ConfigParser.prototype.readAsync = async function(file) { + const lines = (await readFileAsync(file)) + .toString('utf8') + .split(LINE_BOUNDARY); + parseLines.call(this, file, lines); +} + +/** + * Gets the value for the key in the named section. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {boolean} [raw=false] - Whether or not to replace placeholders + * @returns {string|undefined} + */ +ConfigParser.prototype.get = function(section, key, raw) { + if(this._sections.hasOwnProperty(section)){ + if(raw){ + return this._sections[section][key]; + } else { + return interpolation.interpolate(this, section, key); + } + } + return undefined; +}; + +/** + * Coerces value to an integer of the specified radix. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {int} [radix=10] - An integer between 2 and 36 that represents the base of the string. + * @returns {number|undefined|NaN} + */ +ConfigParser.prototype.getInt = function(section, key, radix) { + if(this._sections.hasOwnProperty(section)){ + if(!radix) radix = 10; + return parseInt(this._sections[section][key], radix); + } + return undefined; +}; + +/** + * Coerces value to a float. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @returns {number|undefined|NaN} + */ +ConfigParser.prototype.getFloat = function(section, key) { + if(this._sections.hasOwnProperty(section)){ + return parseFloat(this._sections[section][key]); + } + return undefined; +}; + +/** + * Returns an object with every key, value pair for the named section. + * @param {string} section - Section Name + * @returns {Object} + */ +ConfigParser.prototype.items = function(section) { + return this._sections[section]; +}; + +/** + * Sets the given key to the specified value. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {*} value - New Key Value + */ +ConfigParser.prototype.set = function(section, key, value) { + if(this._sections.hasOwnProperty(section)){ + this._sections[section][key] = value; + } +}; + +/** + * Removes the property specified by key in the named section. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @returns {boolean} + */ +ConfigParser.prototype.removeKey = function(section, key) { + // delete operator returns true if the property doesn't not exist + if(this._sections.hasOwnProperty(section) && + this._sections[section].hasOwnProperty(key)){ + return delete this._sections[section][key]; + } + return false; +}; + +/** + * Removes the named section (and associated key, value pairs). + * @param {string} section - Section Name + * @returns {boolean} + */ +ConfigParser.prototype.removeSection = function(section) { + if(this._sections.hasOwnProperty(section)){ + return delete this._sections[section]; + } + return false; +}; + +/** + * Writes the representation of the config file to the + * specified file. Comments are not preserved. + * @param {string|Buffer|int} file - Filename or File Descriptor + * @param {bool} [createMissingDirs=false] - Whether to create the directories in the path if they don't exist */ +ConfigParser.prototype.write = function(file, createMissingDirs = false) { + if (createMissingDirs) { + const dir = path.dirname(file); + mkdirp.sync(dir); + } -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; + fs.writeFileSync(file, getSectionsAsString.call(this)); +}; - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } +/** + * Writes the representation of the config file to the + * specified file asynchronously. Comments are not preserved. + * @param {string|Buffer|int} file - Filename or File Descriptor + * @param {bool} [createMissingDirs=false] - Whether to create the directories in the path if they don't exist + * @returns {Promise} + */ +ConfigParser.prototype.writeAsync = async function(file, createMissingDirs = false) { + if (createMissingDirs) { + const dir = path.dirname(file); + await mkdirAsync(dir); + } - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; + await writeFileAsync(file, getSectionsAsString.call(this)); +} - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } +function parseLines(file, lines) { + let curSec = null; + lines.forEach((line, lineNumber) => { + if(!line || line.match(COMMENT)) return; + let res = SECTION.exec(line); + if(res){ + const header = res[1]; + curSec = {}; + this._sections[header] = curSec; + } else if(!curSec) { + throw new errors.MissingSectionHeaderError(file, lineNumber, line); + } else { + res = KEY.exec(line); + if(res){ + const key = res[1]; + curSec[key] = res[2]; + } else { + throw new errors.ParseError(file, lineNumber, line); + } + } + }); +} - // 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; +function getSectionsAsString() { + let out = ''; + let section; + for(section in this._sections){ + if(!this._sections.hasOwnProperty(section)) continue; + out += ('[' + section + ']\n'); + const keys = this._sections[section]; + let key; + for(key in keys){ + if(!keys.hasOwnProperty(key)) continue; + let value = keys[key]; + out += (key + '=' + value + '\n'); + } + out += '\n'; } - } - - // Remove event specific arrays for event types that no - // one is subscribed for to avoid memory leak. - if (callbacks.length === 0) { - delete this._callbacks['$' + event]; - } + return out; +} - return this; -}; +module.exports = ConfigParser; + +},{"./errors":13,"./interpolation":14,"fs":1,"mkdirp":15,"path":6,"util":10}],13:[function(require,module,exports){ +/** + * Error thrown when addSection is called with a section + * that already exists. + * @param {string} section - Section Name + * @constructor + */ +function DuplicateSectionError(section) { + this.name = 'DuplicateSectionError'; + this.message = section + ' already exists'; + Error.captureStackTrace(this, this.constructor); +} /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} + * Error thrown when the section being accessed, does + * not exist. + * @param {string} section - Section Name + * @constructor */ +function NoSectionError(section) { + this.name = this.constructor.name; + this.message = 'Section ' + section + ' does not exist.'; + Error.captureStackTrace(this, this.constructor); +} -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; +/** + * Error thrown when a file is being parsed. + * @param {string} filename - File name + * @param {int} lineNumber - Line Number + * @param {string} line - Contents of the line + * @constructor + */ +function ParseError(filename, lineNumber, line) { + this.name = this.constructor.name; + this.message = 'Source contains parsing errors.\nfile: ' + filename + + ' line: ' + lineNumber + '\n' + line; + Error.captureStackTrace(this, this.constructor); +} - var args = new Array(arguments.length - 1) - , callbacks = this._callbacks['$' + event]; +/** + * Error thrown when there are no section headers present + * in a file. + * @param {string} filename - File name + * @param {int} lineNumber - Line Number + * @param {string} line - Contents of the line + * @constructor + */ +function MissingSectionHeaderError(filename, lineNumber, line) { + this.name = this.constructor.name; + this.message = 'File contains no section headers.\nfile: ' + filename + + ' line: ' + lineNumber + '\n' + line; + Error.captureStackTrace(this, this.constructor); +} - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } +/** + * Error thrown when the interpolate function exceeds the maximum recursion + * depth. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {string} value - Key Value + * @param {int} maxDepth - Maximum recursion depth + * @constructor + */ +function MaximumInterpolationDepthError(section, key, value, maxDepth) { + this.name = this.constructor.name; + this.message = 'Exceeded Maximum Recursion Depth (' + maxDepth + + ') for key ' + key + ' in section ' + section + '\nvalue: ' + value; + Error.captureStackTrace(this, this.constructor); +} - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } +module.exports = { + DuplicateSectionError, + NoSectionError, + ParseError, + MissingSectionHeaderError, + MaximumInterpolationDepthError +}; +},{}],14:[function(require,module,exports){ +const errors = require('./errors'); - return this; -}; +/** + * Regular Expression to match placeholders. + * @type {RegExp} + * @private + */ +const PLACEHOLDER = new RegExp(/%\(([\w-]+)\)s/); /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public + * Maximum recursion depth for parseValue + * @type {number} */ +const MAXIMUM_INTERPOLATION_DEPTH = 50; -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; +/** + * Recursively parses a string and replaces the placeholder ( %(key)s ) + * with the value the key points to. + * @param {ParserConfig} parser - Parser Config Object + * @param {string} section - Section Name + * @param {string} key - Key Name + */ +function interpolate(parser, section, key) { + return interpolateRecurse(parser, section, key, 1); +} /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public + * Interpolate Recurse + * @param parser + * @param section + * @param key + * @param depth + * @private */ +function interpolateRecurse(parser, section, key, depth) { + let value = parser.get(section, key, true); + if(depth > MAXIMUM_INTERPOLATION_DEPTH){ + throw new errors.MaximumInterpolationDepthError(section, key, value, MAXIMUM_INTERPOLATION_DEPTH); + } + let res = PLACEHOLDER.exec(value); + while(res !== null){ + const placeholder = res[1]; + const rep = interpolateRecurse(parser, section, placeholder, depth + 1); + // replace %(key)s with the returned value next + value = value.substr(0, res.index) + rep + + value.substr(res.index + res[0].length); + // get next placeholder + res = PLACEHOLDER.exec(value); + } + return value; +} -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; +module.exports = { + interpolate, + MAXIMUM_INTERPOLATION_DEPTH +}; +},{"./errors":13}],15:[function(require,module,exports){ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); -},{}],5:[function(require,module,exports){ +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + +},{"fs":1,"path":6}],16:[function(require,module,exports){ function Agent() { this._defaults = []; } @@ -2217,7 +3910,7 @@ Agent.prototype._setDefaults = function(req) { module.exports = Agent; -},{}],6:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ /** * Root reference for iframes. */ @@ -3139,7 +4832,7 @@ request.put = function(url, data, fn) { return req; }; -},{"./agent-base":5,"./is-object":7,"./request-base":8,"./response-base":9,"component-emitter":4}],7:[function(require,module,exports){ +},{"./agent-base":16,"./is-object":18,"./request-base":19,"./response-base":20,"component-emitter":11}],18:[function(require,module,exports){ 'use strict'; /** @@ -3156,7 +4849,7 @@ function isObject(obj) { module.exports = isObject; -},{}],8:[function(require,module,exports){ +},{}],19:[function(require,module,exports){ 'use strict'; /** @@ -3852,7 +5545,7 @@ RequestBase.prototype._setTimeouts = function() { } }; -},{"./is-object":7}],9:[function(require,module,exports){ +},{"./is-object":18}],20:[function(require,module,exports){ 'use strict'; /** @@ -3990,7 +5683,7 @@ ResponseBase.prototype._setStatusProperties = function(status){ this.unprocessableEntity = 422 == status; }; -},{"./utils":10}],10:[function(require,module,exports){ +},{"./utils":21}],21:[function(require,module,exports){ 'use strict'; /** @@ -6048,9 +7741,307 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } +const logLevelEnum = { + level: { + LNone: 'none', + LError: 'error', + LDebug: 'debug', + LTrace: 'trace', + }, +}; + +const logFormatEnum = { + formats: { + JSON: 'json', + TEXT: 'text', + }, +}; + +class Logger { + get logLevelEnum() { + return logLevelEnum; + } + + get logFormatEnum() { + return logFormatEnum; + } + + constructor() { + this.log_level = logLevelEnum.level.LNone; + this.log_format = logFormatEnum.formats.TEXT; + this.log_to_console = true; + this.log_file_path; + this.log_response_body = false; + this.log_request_body = false; + + this.setLogger(); + } + + setLogger() { + } + + log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody); + if (typeof window !== 'undefined') { + var shouldLog = this.calculateLogLevel(level); + if (shouldLog > 0 && this.log_to_console === true) { + if(this.log_format === this.logFormatEnum.formats.JSON) { + console.log(content); + } else { + console.log(`${level.toUpperCase()}: ${content}`); + } + } + } else { + if (this.logger.transports.length > 0) this.logger.log(level, content); + } + } + + calculateLogLevel(level) { + switch (this.log_level) { + case this.logLevelEnum.level.LError: + if (level !== this.logLevelEnum.level.LError) { + return -1; + } + return 1; + case this.logLevelEnum.level.LDebug: + if (level === this.logLevelEnum.level.LTrace) { + return -1; + } + return 1; + case this.logLevelEnum.level.LTrace: + return 1; + default: + return -1; + } + } + + formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var result; + if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]'; + if (!this.log_request_body) requestBody = undefined; + if (!this.log_response_body) responseBody = undefined; + if (this.log_format && this.log_format === logFormatEnum.formats.JSON) { + result = { + level: level, + date: new Date().toISOString(), + method: method, + url: decodeURIComponent(url), + correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '', + statusCode: statusCode, + }; + if (requestHeaders) result.requestHeaders = requestHeaders; + if (responseHeaders) result.responseHeaders = responseHeaders; + if (requestBody) result.requestBody = requestBody; + if (responseBody) result.responseBody = responseBody; + } else { + result = `${new Date().toISOString()} +=== REQUEST === +${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue( + 'Headers', + this.formatHeaderString(requestHeaders) + )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')} +=== RESPONSE === +${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue( + 'CorrelationId', + responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '' + )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`; + } + + return result; + } + + formatHeaderString(headers) { + var headerString = ''; + if (!headers) return headerString; + for (const [key, value] of Object.entries(headers)) { + headerString += `\n\t${key}: ${value}`; + } + return headerString; + } + + formatValue(key, value) { + if (!value || value === '' || value === '{}') return ''; + return `${key}: ${value}\n`; + } + + getLogLevel(level) { + switch (level) { + case 'error': + return logLevelEnum.level.LError; + case 'debug': + return logLevelEnum.level.LDebug; + case 'trace': + return logLevelEnum.level.LTrace; + default: + return logLevelEnum.level.LNone; + } + } + + getLogFormat(format) { + switch (format) { + case 'json': + return logFormatEnum.formats.JSON; + default: + return logFormatEnum.formats.TEXT; + } + } +} + +class Configuration { + /** + * Singleton getter + */ + get instance() { + return Configuration.instance; + } + + /** + * Singleton setter + */ + set instance(value) { + Configuration.instance = value; + } + + constructor() { + if (!Configuration.instance) { + Configuration.instance = this; + } + + if (typeof window !== 'undefined') { + this.configPath = ''; + } else { + const os = require('os'); + const path = require('path'); + this.configPath = path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config'); + } + + this.live_reload_config = true; + this.host; + this.environment; + this.basePath; + this.authUrl; + this.config; + this.logger = new Logger(); + this.setEnvironment(); + this.liveLoadConfig(); + } + + liveLoadConfig() { + // If in browser, don't read config file, use default values + if (typeof window !== 'undefined') { + this.configPath = ''; + return; + } + + this.updateConfigFromFile(); + + if (this.live_reload_config && this.live_reload_config === true) { + try { + const fs = require('fs'); + fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => { + this.updateConfigFromFile(); + if (!this.live_reload_config) { + fs.unwatchFile(this.configPath); + } + }); + } catch (err) { + // do nothing + } + } + } + + setConfigPath(path) { + if (path && path !== this.configPath) { + this.configPath = path; + this.liveLoadConfig(); + } + } + + updateConfigFromFile() { + const ConfigParser = require('configparser'); + var configparser = new ConfigParser(); + + try { + configparser.read(this.configPath); // If no error catched, indicates it's INI format + this.config = configparser; + } catch (error) { + if (error.name && error.name === 'MissingSectionHeaderError') { + // Not INI format, see if it's JSON format + const fs = require('fs'); + var configData = fs.readFileSync(this.configPath, 'utf8'); + this.config = { + _sections: JSON.parse(configData), // To match INI data format + }; + } + } + + if (this.config) this.updateConfigValues(); + } + + updateConfigValues() { + this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level')); + this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format')); + this.logger.log_to_console = + this.getConfigBoolean('logging', 'log_to_console') !== undefined + ? this.getConfigBoolean('logging', 'log_to_console') + : this.logger.log_to_console; + this.logger.log_file_path = + this.getConfigString('logging', 'log_file_path') !== undefined + ? this.getConfigString('logging', 'log_file_path') + : this.logger.log_file_path; + this.logger.log_response_body = + this.getConfigBoolean('logging', 'log_response_body') !== undefined + ? this.getConfigBoolean('logging', 'log_response_body') + : this.logger.log_response_body; + this.logger.log_request_body = + this.getConfigBoolean('logging', 'log_request_body') !== undefined + ? this.getConfigBoolean('logging', 'log_request_body') + : this.logger.log_request_body; + this.live_reload_config = + this.getConfigBoolean('general', 'live_reload_config') !== undefined + ? this.getConfigBoolean('general', 'live_reload_config') + : this.live_reload_config; + this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host; + + this.setEnvironment(); + + // Update logging configs + this.logger.setLogger(); + } + + setEnvironment(env) { + // Default value + if (env) this.environment = env; + else this.environment = this.host ? this.host : 'mypurecloud.com'; + + // Strip trailing slash + this.environment = this.environment.replace(/\/+$/, ''); + + // Strip protocol and subdomain + if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8); + if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7); + if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4); + + this.basePath = `https://api.${this.environment}`; + this.authUrl = `https://login.${this.environment}`; + } + + getConfigString(section, key) { + if (this.config._sections[section]) return this.config._sections[section][key]; + } + + getConfigBoolean(section, key) { + if (this.config._sections[section] && this.config._sections[section][key] !== undefined) { + if (typeof this.config._sections[section][key] === 'string') { + return this.config._sections[section][key] === 'true'; + } else return this.config._sections[section][key]; + } + } +} + /** * @module purecloud-guest-chat-client/ApiClient - * @version 7.1.0 + * @version 7.2.0 */ class ApiClient { /** @@ -6127,6 +8118,11 @@ class ApiClient { this.hasLocalStorage = false; } + /** + * Create configuration instance for ApiClient and prepare logger. + */ + this.config = new Configuration(); + /** * The base URL against which to resolve every API call's (relative) path. * @type {String} @@ -6166,16 +8162,6 @@ class ApiClient { if (typeof(window) !== 'undefined') window.ApiClient = this; } - /** - * @description Sets the debug log to enable debug logging - * @param {log} debugLog - In most cases use `console.log` - * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0. - */ - setDebugLog(debugLog, maxLines) { - this.debugLog = debugLog; - this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined; - } - /** * @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned. * @param {boolean} returnExtended - `true` to return extended responses @@ -6192,7 +8178,6 @@ class ApiClient { setPersistSettings(doPersist, prefix) { this.persistSettings = doPersist; this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud'; - this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`); } /** @@ -6217,7 +8202,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.'); return; } @@ -6227,7 +8211,6 @@ class ApiClient { // Save updated auth data localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData)); - this._debugTrace('Auth data saved to local storage'); } catch (e) { console.error(e); } @@ -6242,7 +8225,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.'); return; } @@ -6262,24 +8244,7 @@ class ApiClient { * @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc. */ setEnvironment(environment) { - if (!environment) - environment = 'mypurecloud.com'; - - // Strip trailing slash - environment = environment.replace(/\/+$/, ''); - - // Strip protocol and subdomain - if (environment.startsWith('https://')) - environment = environment.substring(8); - if (environment.startsWith('http://')) - environment = environment.substring(7); - if (environment.startsWith('api.')) - environment = environment.substring(4); - - // Set vars - this.environment = environment; - this.basePath = `https://api.${environment}`; - this.authUrl = `https://login.${environment}`; + this.config.setEnvironment(environment); } /** @@ -6336,7 +8301,7 @@ class ApiClient { */ _buildAuthUrl(path, query) { if (!query) query = {}; - return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`); + return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`); } /** @@ -6365,7 +8330,7 @@ class ApiClient { if (!path.match(/^\//)) { path = `/${path}`; } - var url = this.basePath + path; + var url = this.config.basePath + path; url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { @@ -6543,23 +8508,6 @@ class ApiClient { request.proxy(this.proxy); } - if(this.debugLog){ - var trace = `[REQUEST] ${httpMethod} ${url}`; - if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){ - trace += `\nPath Params: ${JSON.stringify(pathParams)}`; - } - - if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){ - trace += `\nQuery Params: ${JSON.stringify(queryParams)}`; - } - - if(bodyParam){ - trace += `\nnBody: ${JSON.stringify(bodyParam)}`; - } - - this._debugTrace(trace); - } - // apply authentications this.applyAuthToRequest(request, authNames); @@ -6568,7 +8516,7 @@ class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //request.set({ 'purecloud-sdk': '7.1.0' }); + //request.set({ 'purecloud-sdk': '7.2.0' }); // set request timeout request.timeout(this.timeout); @@ -6630,23 +8578,22 @@ class ApiClient { } : response.body ? response.body : response.text; // Debug logging - if (this.debugLog) { - var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`; - if (response.headers) - trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`; - if (response.body) - trace += `\nBody: ${JSON.stringify(response.body,null,2)}`; - - // Log trace message - this._debugTrace(trace); - - // Log stack trace - if (error) - this._debugTrace(error); - } + this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined); + this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined); // Resolve promise if (error) { + // Log error + this.config.logger.log( + 'error', + response.statusCode, + httpMethod, + url, + request.header, + response.headers, + bodyParam, + response.body + ); reject(data); } else { resolve(data); @@ -6654,46 +8601,13 @@ class ApiClient { }); }); } - - /** - * @description Parses an ISO-8601 string representation of a date value. - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - parseDate(str) { - return new Date(str.replace(/T/i, ' ')); - } - - /** - * @description Logs to the debug log - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - _debugTrace(trace) { - if (!this.debugLog) return; - - if (typeof(trace) === 'string') { - // Truncate - var truncTrace = ''; - var lines = trace.split('\n'); - if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) { - for (var i = 0; i < this.debugLogMaxLines; i++) { - truncTrace += `${lines[i]}\n`; - } - truncTrace += '...response truncated...'; - trace = truncTrace; - } - } - - this.debugLog(trace); - } } class WebChatApi { /** * WebChat service. * @module purecloud-guest-chat-client/api/WebChatApi - * @version 7.1.0 + * @version 7.2.0 */ /** @@ -7072,7 +8986,7 @@ class WebChatApi { * *

* @module purecloud-guest-chat-client/index - * @version 7.1.0 + * @version 7.2.0 */ class platformClient { constructor() { @@ -7100,4 +9014,4 @@ var index = new platformClient(); module.exports = index; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"buffer":2,"superagent":6}]},{},[]); +},{"buffer":3,"configparser":12,"fs":1,"os":5,"path":6,"superagent":17}]},{},[]); diff --git a/build/dist/web-cjs/purecloud-guest-chat-client.min.js b/build/dist/web-cjs/purecloud-guest-chat-client.min.js index 819a92e6..59a2e0db 100644 --- a/build/dist/web-cjs/purecloud-guest-chat-client.min.js +++ b/build/dist/web-cjs/purecloud-guest-chat-client.min.js @@ -1 +1 @@ -require=function(){return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var f=r[s]={exports:{}};e[s][0].call(f.exports,function(t){return i(e[s][1][t]||t)},f,f.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0?s-4:s;for(r=0;r>16&255,u[f++]=e>>8&255,u[f++]=255&e;2===a&&(e=i[t.charCodeAt(r)]<<2|i[t.charCodeAt(r+1)]>>4,u[f++]=255&e);1===a&&(e=i[t.charCodeAt(r)]<<10|i[t.charCodeAt(r+1)]<<4|i[t.charCodeAt(r+2)]>>2,u[f++]=e>>8&255,u[f++]=255&e);return u},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,o=[],s=0,a=r-i;sa?a:s+16383));1===i?(e=t[r-1],o.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],o.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,r){for(var i,o,s=[],a=e;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],2:[function(t,e,r){(function(e){(function(){"use strict";var e=t("base64-js"),n=t("ieee754");r.Buffer=s,r.SlowBuffer=function(t){+t!=t&&(t=0);return s.alloc(+t)},r.INSPECT_MAX_BYTES=50;var i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=0|l(t,e),n=o(r),i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return f(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(j(t,ArrayBuffer)||t&&j(t.buffer,ArrayBuffer))return function(t,e,r){if(e<0||t.byteLength=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function l(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||j(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return k(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(t).length;default:if(i)return n?-1:k(t).length;e=(""+e).toLowerCase(),i=!0}}function p(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),G(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:g(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):g(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function g(t,e,r,n,i){var o,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function E(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function T(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&h)<<6|63&o)>127&&(f=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&h)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=A)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,e,r);case"utf8":case"utf-8":return T(this,e,r);case"ascii":return C(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},s.prototype.compare=function(t,e,r,n,i){if(j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,a=r-e,u=Math.min(o,a),h=this.slice(n,i),f=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return y(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":return m(this,t,e,r);case"latin1":case"binary":return v(this,t,e,r);case"base64":return b(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function P(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(t,e,r,i,o){return e=+e,r>>>=0,o||M(t,0,r,4),n.write(t,e,r,i,23,4),r+4}function U(t,e,r,i,o){return e=+e,r>>>=0,o||M(t,0,r,8),n.write(t,e,r,i,52,8),r+8}s.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t],i=1,o=0;++o>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||x(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||x(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||x(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||x(t,4,this.length),n.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||x(t,4,this.length),n.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||x(t,8,this.length),n.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||x(t,8,this.length),n.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||P(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,n)||P(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,r){return B(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return B(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return U(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return U(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function q(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(O,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function D(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function j(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function G(t){return t!=t}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":1,buffer:2,ieee754:3}],3:[function(t,e,r){r.read=function(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)},r.write=function(t,e,r,n,i,o){var s,a,u,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+c>=1?l/u:l*Math.pow(2,1-c))*u>=2&&(s++,u/=2),s+c>=f?(a=0,s=f):s+c>=1?(a=(e*u-1)*Math.pow(2,i),s+=c):(a=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}},{}],4:[function(t,e,r){function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}void 0!==e&&(e.exports=n),n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i=2&&t._responseTimeoutTimer&&clearTimeout(t._responseTimeoutTimer),4==r){var n;try{n=e.status}catch(t){n=0}if(!n){if(t.timedout||t._aborted)return;return t.crossDomainError()}t.emit("end")}};var n=function(e,r){r.total>0&&(r.percent=r.loaded/r.total*100),r.direction=e,t.emit("progress",r)};if(this.hasListeners("progress"))try{e.onprogress=n.bind(null,"download"),e.upload&&(e.upload.onprogress=n.bind(null,"upload"))}catch(t){}try{this.username&&this.password?e.open(this.method,this.url,!0,this.username,this.password):e.open(this.method,this.url,!0)}catch(t){return this.callback(t)}if(this._withCredentials&&(e.withCredentials=!0),!this._formData&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof r&&!this._isHost(r)){var i=this._header["content-type"],o=this._serializer||f.serialize[i?i.split(";")[0]:""];!o&&g(i)&&(o=f.serialize["application/json"]),o&&(r=o(r))}for(var s in this.header)null!=this.header[s]&&this.header.hasOwnProperty(s)&&e.setRequestHeader(s,this.header[s]);return this._responseType&&(e.responseType=this._responseType),this.emit("request",this),e.send(void 0!==r?r:null),this},f.agent=function(){return new u},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach(function(t){u.prototype[t.toLowerCase()]=function(e,r){var n=new f.Request(t,e);return this._setDefaults(n),r&&n.end(r),n}}),u.prototype.del=u.prototype.delete,f.get=function(t,e,r){var n=f("GET",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},f.head=function(t,e,r){var n=f("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},f.options=function(t,e,r){var n=f("OPTIONS",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},f.del=m,f.delete=m,f.patch=function(t,e,r){var n=f("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},f.post=function(t,e,r){var n=f("POST",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},f.put=function(t,e,r){var n=f("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n}},{"./agent-base":5,"./is-object":7,"./request-base":8,"./response-base":9,"component-emitter":4}],7:[function(t,e,r){"use strict";e.exports=function(t){return null!==t&&"object"==typeof t}},{}],8:[function(t,e,r){"use strict";var n=t("./is-object");function i(t){if(t)return function(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}(t)}e.exports=i,i.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete 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){if(!t||"object"!=typeof t)return this._timeout=t,this._responseTimeout=0,this;for(var e in t)switch(e){case"deadline":this._timeout=t.deadline;break;case"response":this._responseTimeout=t.response;break;default:console.warn("Unknown timeout option",e)}return this},i.prototype.retry=function(t,e){return 0!==arguments.length&&!0!==t||(t=1),t<=0&&(t=0),this._maxRetries=t,this._retries=0,this._retryCallback=e,this};var o=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];i.prototype._shouldRetry=function(t,e){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{var r=this._retryCallback(t,e);if(!0===r)return!0;if(!1===r)return!1}catch(t){console.error(t)}if(e&&e.status&&e.status>=500&&501!=e.status)return!0;if(t){if(t.code&&~o.indexOf(t.code))return!0;if(t.timeout&&"ECONNABORTED"==t.code)return!0;if(t.crossDomain)return!0}return!1},i.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},i.prototype.then=function(t,e){if(!this._fullfilledPromise){var r=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){r.end(function(r,n){r?e(r):t(n)})})}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(n(t)){for(var r in t)this.set(r,t[r]);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(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),n(t)){for(var r in t)this.field(r,t[r]);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._auth=function(t,e,r,n){switch(r.type){case"basic":this.set("Authorization","Basic "+n(t+":"+e));break;case"auto":this.username=t,this.password=e;break;case"bearer":this.set("Authorization","Bearer "+t)}return this},i.prototype.withCredentials=function(t){return void 0==t&&(t=!0),this._withCredentials=t,this},i.prototype.redirects=function(t){return this._maxRedirects=t,this},i.prototype.maxResponseSize=function(t){if("number"!=typeof t)throw TypeError("Invalid argument");return this._maxResponseSize=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=n(t),r=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"),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&&n(this._data))for(var i in t)this._data[i]=t[i];else"string"==typeof t?(r||this.type("form"),r=this._header["content-type"],this._data="application/x-www-form-urlencoded"==r?this._data?this._data+"&"+t:t:(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(r||this.type("json"),this)},i.prototype.sortQuery=function(t){return this._sort=void 0===t||t,this},i.prototype._finalizeQueryString=function(){var t=this._query.join("&");if(t&&(this.url+=(this.url.indexOf("?")>=0?"&":"?")+t),this._query.length=0,this._sort){var e=this.url.indexOf("?");if(e>=0){var r=this.url.substring(e+1).split("&");"function"==typeof this._sort?r.sort(this._sort):r.sort(),this.url=this.url.substring(0,e)+"?"+r.join("&")}}},i.prototype._appendQueryString=function(){console.trace("Unsupported")},i.prototype._timeoutError=function(t,e,r){if(!this._aborted){var n=new Error(t+e+"ms exceeded");n.timeout=e,n.code="ECONNABORTED",n.errno=r,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,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){t._timeoutError("Response timeout of ",t._responseTimeout,"ETIMEDOUT")},this._responseTimeout))}},{"./is-object":7}],9:[function(t,e,r){"use strict";var n=t("./utils");function i(t){if(t)return function(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}(t)}e.exports=i,i.prototype.get=function(t){return this.header[t.toLowerCase()]},i.prototype._setHeaderProperties=function(t){var e=t["content-type"]||"";this.type=n.type(e);var r=n.params(e);for(var i in r)this[i]=r[i];this.links={};try{t.link&&(this.links=n.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.created=201==t,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,this.unprocessableEntity=422==t}},{"./utils":10}],10:[function(t,e,r){"use strict";r.type=function(t){return t.split(/ *; */).shift()},r.params=function(t){return t.split(/ *; */).reduce(function(t,e){var r=e.split(/ *= */),n=r.shift(),i=r.shift();return n&&i&&(t[n]=i),t},{})},r.parseLinks=function(t){return t.split(/ *, */).reduce(function(t,e){var r=e.split(/ *; */),n=r[0].slice(1,-1);return t[r[1].split(/ *= */)[1].slice(1,-1)]=n,t},{})},r.cleanHeader=function(t,e){return delete t["content-type"],delete t["content-length"],delete t["transfer-encoding"],delete t.host,e&&(delete t.authorization,delete t.cookie),t}},{}],platformClient:[function(t,e,r){(function(r,n){(function(){"use strict";var n,i=(n=t("superagent"))&&"object"==typeof n&&"default"in n?n.default:n,o={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud"},s=void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},a=[],u=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,f=!1;function c(){f=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+a[i>>12&63]+a[i>>6&63]+a[63&i]);return o.join("")}function p(t){var e;f||c();for(var r=t.length,n=r%3,i="",o=[],s=0,u=r-n;su?u:s+16383));return 1===n?(e=t[r-1],i+=a[e>>2],i+=a[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=a[e>>10],i+=a[e>>4&63],i+=a[e<<2&63],i+="="),o.push(i),o.join("")}function d(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function g(t,e,r,n,i,o){var s,a,u,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+c>=1?l/u:l*Math.pow(2,1-c))*u>=2&&(s++,u/=2),s+c>=f?(a=0,s=f):s+c>=1?(a=(e*u-1)*Math.pow(2,i),s+=c):(a=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var y={}.toString,w=Array.isArray||function(t){return"[object Array]"==y.call(t)};function m(){return b.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function v(t,e){if(m()=m())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+m().toString(16)+" bytes");return 0|t}function R(t){return!(null==t||!t._isBuffer)}function I(t,e){if(R(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 r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Z(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return tt(t).length;default:if(n)return Z(t).length;e=(""+e).toLowerCase(),n=!0}}function S(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function x(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=b.from(e,n)),R(e))return 0===e.length?-1:P(t,e,r,n,i);if("number"==typeof e)return e&=255,b.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):P(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function P(t,e,r,n,i){var o,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function q(t,e,r){return 0===e&&r===t.length?p(t):p(t.slice(e,r))}function D(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&h)<<6|63&o)>127&&(f=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&h)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=j)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return N(this,e,r);case"utf8":case"utf-8":return D(this,e,r);case"ascii":return G(this,e,r);case"latin1":case"binary":return W(this,e,r);case"base64":return q(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},b.prototype.equals=function(t){if(!R(t))throw new TypeError("Argument must be a Buffer");return this===t||0===b.compare(this,t)},b.prototype.inspect=function(){var t="";return this.length>0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},b.prototype.compare=function(t,e,r,n,i){if(!R(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,s=r-e,a=Math.min(o,s),u=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return M(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":return U(this,t,e,r);case"latin1":case"binary":return O(this,t,e,r);case"base64":return L(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var j=4096;function G(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function $(t,e,r,n,i,o){if(!R(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function J(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function H(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function F(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function K(t,e,r,n,i){return i||F(t,0,r,4),g(t,e,r,n,23,4),r+4}function X(t,e,r,n,i){return i||F(t,0,r,8),g(t,e,r,n,52,8),r+8}b.prototype.slice=function(t,e){var r,n=this.length;if(t=~~t,e=void 0===e?n:~~e,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),e<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},b.prototype.readUInt8=function(t,e){return e||z(t,1,this.length),this[t]},b.prototype.readUInt16LE=function(t,e){return e||z(t,2,this.length),this[t]|this[t+1]<<8},b.prototype.readUInt16BE=function(t,e){return e||z(t,2,this.length),this[t]<<8|this[t+1]},b.prototype.readUInt32LE=function(t,e){return e||z(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},b.prototype.readUInt32BE=function(t,e){return e||z(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},b.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||z(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},b.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||z(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},b.prototype.readInt8=function(t,e){return e||z(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},b.prototype.readInt16LE=function(t,e){e||z(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},b.prototype.readInt16BE=function(t,e){e||z(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},b.prototype.readInt32LE=function(t,e){return e||z(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},b.prototype.readInt32BE=function(t,e){return e||z(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},b.prototype.readFloatLE=function(t,e){return e||z(t,4,this.length),d(this,t,!0,23,4)},b.prototype.readFloatBE=function(t,e){return e||z(t,4,this.length),d(this,t,!1,23,4)},b.prototype.readDoubleLE=function(t,e){return e||z(t,8,this.length),d(this,t,!0,52,8)},b.prototype.readDoubleBE=function(t,e){return e||z(t,8,this.length),d(this,t,!1,52,8)},b.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||$(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},b.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,1,255,0),b.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},b.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,2,65535,0),b.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},b.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,2,65535,0),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},b.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,4,4294967295,0),b.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):H(this,t,e,!0),e+4},b.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,4,4294967295,0),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):H(this,t,e,!1),e+4},b.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);$(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},b.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);$(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},b.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,1,127,-128),b.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},b.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,2,32767,-32768),b.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},b.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,2,32767,-32768),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},b.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,4,2147483647,-2147483648),b.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):H(this,t,e,!0),e+4},b.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||$(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):H(this,t,e,!1),e+4},b.prototype.writeFloatLE=function(t,e,r){return K(this,t,e,!0,r)},b.prototype.writeFloatBE=function(t,e,r){return K(this,t,e,!1,r)},b.prototype.writeDoubleLE=function(t,e,r){return X(this,t,e,!0,r)},b.prototype.writeDoubleBE=function(t,e,r){return X(this,t,e,!1,r)},b.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!b.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function tt(t){return function(t){var e,r,n,i,o,s;f||c();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[a-2]?2:"="===t[a-1]?1:0,s=new h(3*a/4-o),n=o>0?a-4:a;var l=0;for(e=0,r=0;e>16&255,s[l++]=i>>8&255,s[l++]=255&i;return 2===o?(i=u[t.charCodeAt(e)]<<2|u[t.charCodeAt(e+1)]>>4,s[l++]=255&i):1===o&&(i=u[t.charCodeAt(e)]<<10|u[t.charCodeAt(e+1)]<<4|u[t.charCodeAt(e+2)]>>2,s[l++]=i>>8&255,s[l++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(Q,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function et(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function rt(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}class nt{get instance(){return nt.instance}set instance(t){nt.instance=t}constructor(){nt.instance||(nt.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(t){this.hasLocalStorage=!1}this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=i,"undefined"!=typeof window&&(window.ApiClient=this)}setDebugLog(t,e){this.debugLog=t,this.debugLogMaxLines=e&&e>0?e:void 0}setReturnExtendedResponses(t){this.returnExtended=t}setPersistSettings(t,e){this.persistSettings=t,this.settingsPrefix=e?e.replace(/\W+/g,"_"):"purecloud",this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`)}_saveSettings(t){try{if(this.authData.apiKey=t.apiKey,this.authentications["Guest Chat JWT"].apiKey=t.apiKey,t.state&&(this.authData.state=t.state),t.tokenExpiryTime&&(this.authData.tokenExpiryTime=t.tokenExpiryTime,this.authData.tokenExpiryTimeString=t.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return void this._debugTrace("Warning: Cannot access local storage. Settings will not be saved.");let e=JSON.parse(JSON.stringify(this.authData));delete e.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(e)),this._debugTrace("Auth data saved to local storage")}catch(t){console.error(t)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return void this._debugTrace("Warning: Cannot access local storage. Settings will not be loaded.");const t=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=t}setEnvironment(t){t||(t="mypurecloud.com"),(t=t.replace(/\/+$/,"")).startsWith("https://")&&(t=t.substring(8)),t.startsWith("http://")&&(t=t.substring(7)),t.startsWith("api.")&&(t=t.substring(4)),this.environment=t,this.basePath=`https://api.${t}`,this.authUrl=`https://login.${t}`}_testTokenAccess(){return new Promise((t,e)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{t()}).catch(t=>{this._saveSettings({apiKey:void 0}),e(t)}):e(new Error("Token is not set"))})}setJwt(t){this._saveSettings({apiKey:t})}setStorageKey(t){this.storageKey=t,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(t,e){return e||(e={}),Object.keys(e).reduce((t,r)=>e[r]?`${t}&${r}=${e[r]}`:t,`${this.authUrl}/${t}?`)}paramToString(t){return t?t instanceof Date?t.toJSON():t.toString():""}buildUrl(t,e){t.match(/^\//)||(t=`/${t}`);var r=this.basePath+t;return r=r.replace(/\{([\w-]+)\}/g,(t,r)=>{var n;return n=e.hasOwnProperty(r)?this.paramToString(e[r]):t,encodeURIComponent(n)})}isJsonMime(t){return Boolean(t&&t.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(t){for(var e=0;e{var r=this.authentications[e];switch(r.type){case"basic":(r.username||r.password)&&t.auth(r.username||"",r.password||"");break;case"apiKey":if(r.apiKey){var n={};r.apiKeyPrefix?n[r.name]=`${r.apiKeyPrefix} ${r.apiKey}`:n[r.name]=r.apiKey,"header"===r.in?t.set(n):t.query(n)}break;case"oauth2":r.accessToken&&t.set({Authorization:`Bearer ${r.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${r.type}`)}})}callApi(t,e,r,n,o,s,a,u,h,f){var c=this.buildUrl(t,r),l=i(e,c);if(this.proxy&&l.proxy&&l.proxy(this.proxy),this.debugLog){var p=`[REQUEST] ${e} ${c}`;r&&Object.keys(r).count>0&&r[Object.keys(r)[0]]&&(p+=`\nPath Params: ${JSON.stringify(r)}`),n&&Object.keys(n).count>0&&n[Object.keys(n)[0]]&&(p+=`\nQuery Params: ${JSON.stringify(n)}`),a&&(p+=`\nnBody: ${JSON.stringify(a)}`),this._debugTrace(p)}this.applyAuthToRequest(l,u),l.query(this.normalizeParams(n)),l.set(this.defaultHeaders).set(this.normalizeParams(o)),l.timeout(this.timeout);var d=this.jsonPreferredMime(h);if(d?l.type(d):l.header["Content-Type"]||l.type("application/json"),"application/x-www-form-urlencoded"===d)l.send(this.normalizeParams(s));else if("multipart/form-data"==d){var g=this.normalizeParams(s);for(var y in g)g.hasOwnProperty(y)&&(this.isFileParam(g[y])?l.attach(y,g[y]):l.field(y,g[y]))}else a&&l.send(a);var w=this.jsonPreferredMime(f);return w&&l.accept(w),new Promise((t,r)=>{l.end((n,i)=>{if(!n||i){var o=!0===this.returnExtended||n?{status:i.status,statusText:i.statusText,headers:i.headers,body:i.body,text:i.text,error:n}:i.body?i.body:i.text;if(this.debugLog){var s=`[RESPONSE] ${i.status}: ${e} ${c}`;i.headers&&(s+=`\ninin-correlation-id: ${i.headers["inin-correlation-id"]}`),i.body&&(s+=`\nBody: ${JSON.stringify(i.body,null,2)}`),this._debugTrace(s),n&&this._debugTrace(n)}n?r(o):t(o)}else r({status:0,statusText:"error",headers:[],body:{},text:"error",error:n})})})}parseDate(t){return new Date(t.replace(/T/i," "))}_debugTrace(t){if(this.debugLog){if("string"==typeof t){var e="",r=t.split("\n");if(this.debugLogMaxLines&&r.length>this.debugLogMaxLines){for(var n=0;n0?s-4:s;for(r=0;r>16&255,u[f++]=e>>8&255,u[f++]=255&e;2===a&&(e=i[t.charCodeAt(r)]<<2|i[t.charCodeAt(r+1)]>>4,u[f++]=255&e);1===a&&(e=i[t.charCodeAt(r)]<<10|i[t.charCodeAt(r+1)]<<4|i[t.charCodeAt(r+2)]>>2,u[f++]=e>>8&255,u[f++]=255&e);return u},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,o=[],s=0,a=r-i;sa?a:s+16383));1===i?(e=t[r-1],o.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],o.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function f(t,e,r){for(var i,o,s=[],a=e;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],3:[function(t,e,r){(function(e){(function(){"use strict";var e=t("base64-js"),n=t("ieee754");r.Buffer=s,r.SlowBuffer=function(t){+t!=t&&(t=0);return s.alloc(+t)},r.INSPECT_MAX_BYTES=50;var i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=0|l(t,e),n=o(r),i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return f(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(q(t,ArrayBuffer)||t&&q(t.buffer,ArrayBuffer))return function(t,e,r){if(e<0||t.byteLength=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function l(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||q(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return k(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return j(t).length;default:if(i)return n?-1:k(t).length;e=(""+e).toLowerCase(),i=!0}}function p(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function g(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),N(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:d(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):d(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function d(t,e,r,n,i){var o,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function E(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function T(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&h)<<6|63&o)>127&&(f=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&h)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=A)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return R(this,e,r);case"utf8":case"utf-8":return T(this,e,r);case"ascii":return C(this,e,r);case"latin1":case"binary":return S(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},s.prototype.compare=function(t,e,r,n,i){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,a=r-e,u=Math.min(o,a),h=this.slice(n,i),f=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return y(this,t,e,r);case"utf8":case"utf-8":return m(this,t,e,r);case"ascii":return v(this,t,e,r);case"latin1":case"binary":return w(this,t,e,r);case"base64":return b(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function I(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function O(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(t,e,r,i,o){return e=+e,r>>>=0,o||O(t,0,r,4),n.write(t,e,r,i,23,4),r+4}function M(t,e,r,i,o){return e=+e,r>>>=0,o||O(t,0,r,8),n.write(t,e,r,i,52,8),r+8}s.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||P(t,e,this.length);for(var n=this[t],i=1,o=0;++o>>=0,e>>>=0,r||P(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUInt8=function(t,e){return t>>>=0,e||P(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||P(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||P(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||P(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||P(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||P(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||P(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||P(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||P(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||P(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||P(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||P(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||P(t,4,this.length),n.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||P(t,4,this.length),n.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||P(t,8,this.length),n.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||P(t,8,this.length),n.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||I(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,n)||I(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);I(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);I(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||I(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,r){return B(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return B(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return M(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return M(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--o)t[o+e]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function j(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(U,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function D(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function q(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function N(t){return t!=t}}).call(this)}).call(this,t("buffer").Buffer)},{"base64-js":2,buffer:3,ieee754:4}],4:[function(t,e,r){r.read=function(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)},r.write=function(t,e,r,n,i,o){var s,a,u,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,g=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+c>=1?l/u:l*Math.pow(2,1-c))*u>=2&&(s++,u/=2),s+c>=f?(a=0,s=f):s+c>=1?(a=(e*u-1)*Math.pow(2,i),s+=c):(a=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=g,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=g,s/=256,h-=8);t[r+p-g]|=128*d}},{}],5:[function(t,e,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n",r.homedir=function(){return"/"}},{}],6:[function(t,e,r){(function(t){(function(){function e(t,e){for(var r=0,n=t.length-1;n>=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var o=r.isAbsolute(t),s="/"===i(t,-1);return(t=e(n(t.split("/"),function(t){return!!t}),!o).join("/"))||o||(t="."),t&&s&&(t+="/"),(o?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u=1;--o)if(47===(e=t.charCodeAt(o))){if(!i){n=o;break}}else i=!1;return-1===n?r?"/":".":r&&1===n?"/":t.slice(0,n)},r.basename=function(t,e){var r=function(t){"string"!=typeof t&&(t+="");var e,r=0,n=-1,i=!0;for(e=t.length-1;e>=0;--e)if(47===t.charCodeAt(e)){if(!i){r=e+1;break}}else-1===n&&(i=!1,n=e+1);return-1===n?"":t.slice(r,n)}(t);return e&&r.substr(-1*e.length)===e&&(r=r.substr(0,r.length-e.length)),r},r.extname=function(t){"string"!=typeof t&&(t+="");for(var e=-1,r=0,n=-1,i=!0,o=0,s=t.length-1;s>=0;--s){var a=t.charCodeAt(s);if(47!==a)-1===n&&(i=!1,n=s+1),46===a?-1===e?e=s:1!==o&&(o=1):-1!==e&&(o=-1);else if(!i){r=s+1;break}}return-1===e||-1===n||0===o||1===o&&e===n-1&&e===r+1?"":t.slice(e,n)};var i="b"==="ab".substr(-1)?function(t,e,r){return t.substr(e,r)}:function(t,e,r){return e<0&&(e=t.length+e),t.substr(e,r)}}).call(this)}).call(this,t("_process"))},{_process:7}],7:[function(t,e,r){var n,i,o=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function u(t){if(n===setTimeout)return setTimeout(t,0);if((n===s||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:s}catch(t){n=s}try{i="function"==typeof clearTimeout?clearTimeout:a}catch(t){i=a}}();var h,f=[],c=!1,l=-1;function p(){c&&h&&(c=!1,h.length?f=h.concat(f):l=-1,f.length&&g())}function g(){if(!c){var t=u(p);c=!0;for(var e=f.length;e;){for(h=f,f=[];++l1)for(var r=1;r=o)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(e)?n.showHidden=e:e&&r._extend(n,e),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),f(n,t,n.depth)}function u(t,e){var r=a.styles[e];return r?"["+a.colors[r][0]+"m"+t+"["+a.colors[r][1]+"m":t}function h(t,e){return t}function f(t,e,n){if(t.customInspect&&e&&T(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(n,t);return m(i)||(i=f(t,i,n)),i}var o=function(t,e){if(v(e))return t.stylize("undefined","undefined");if(m(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(y(e))return t.stylize(""+e,"number");if(g(e))return t.stylize(""+e,"boolean");if(d(e))return t.stylize("null","null")}(t,e);if(o)return o;var s=Object.keys(e),a=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(e)),E(e)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return c(e);if(0===s.length){if(T(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(w(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(_(e))return t.stylize(Date.prototype.toString.call(e),"date");if(E(e))return c(e)}var h,b="",A=!1,C=["{","}"];(p(e)&&(A=!0,C=["[","]"]),T(e))&&(b=" [Function"+(e.name?": "+e.name:"")+"]");return w(e)&&(b=" "+RegExp.prototype.toString.call(e)),_(e)&&(b=" "+Date.prototype.toUTCString.call(e)),E(e)&&(b=" "+c(e)),0!==s.length||A&&0!=e.length?n<0?w(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),h=A?function(t,e,r,n,i){for(var o=[],s=0,a=e.length;s=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(h,b,C)):C[0]+b+C[1]}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function l(t,e,r,n,i,o){var s,a,u;if((u=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?a=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(a=t.stylize("[Setter]","special")),R(n,i)||(s="["+i+"]"),a||(t.seen.indexOf(u.value)<0?(a=d(r)?f(t,u.value,null):f(t,u.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n")):a=t.stylize("[Circular]","special")),v(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function p(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function d(t){return null===t}function y(t){return"number"==typeof t}function m(t){return"string"==typeof t}function v(t){return void 0===t}function w(t){return b(t)&&"[object RegExp]"===A(t)}function b(t){return"object"==typeof t&&null!==t}function _(t){return b(t)&&"[object Date]"===A(t)}function E(t){return b(t)&&("[object Error]"===A(t)||t instanceof Error)}function T(t){return"function"==typeof t}function A(t){return Object.prototype.toString.call(t)}function C(t){return t<10?"0"+t.toString(10):t.toString(10)}r.debuglog=function(t){if(v(o)&&(o=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!s[t])if(new RegExp("\\b"+t+"\\b","i").test(o)){var n=e.pid;s[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else s[t]=function(){};return s[t]},r.inspect=a,a.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]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=p,r.isBoolean=g,r.isNull=d,r.isNullOrUndefined=function(t){return null==t},r.isNumber=y,r.isString=m,r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=v,r.isRegExp=w,r.isObject=b,r.isDate=_,r.isError=E,r.isFunction=T,r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t("./support/isBuffer");var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function R(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[C(t.getHours()),C(t.getMinutes()),C(t.getSeconds())].join(":"),[t.getDate(),S[t.getMonth()],e].join(" ")),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!b(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this)}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":9,_process:7,inherits:8}],11:[function(t,e,r){function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}void 0!==e&&(e.exports=n),n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i{if(!e||e.match(c))return;let i=h.exec(e);if(i){const t=i[1];r={},this._sections[t]=r}else{if(!r)throw new a.MissingSectionHeaderError(t,n,e);if(!(i=f.exec(e)))throw new a.ParseError(t,n,e);{const t=i[1];r[t]=i[2]}}})}function v(){let t,e="";for(t in this._sections){if(!this._sections.hasOwnProperty(t))continue;e+="["+t+"]\n";const r=this._sections[t];let n;for(n in r){if(!r.hasOwnProperty(n))continue;e+=n+"="+r[n]+"\n"}e+="\n"}return e}y.prototype.sections=function(){return Object.keys(this._sections)},y.prototype.addSection=function(t){if(this._sections.hasOwnProperty(t))throw new a.DuplicateSectionError(t);this._sections[t]={}},y.prototype.hasSection=function(t){return this._sections.hasOwnProperty(t)},y.prototype.keys=function(t){try{return Object.keys(this._sections[t])}catch(e){throw new a.NoSectionError(t)}},y.prototype.hasKey=function(t,e){return this._sections.hasOwnProperty(t)&&this._sections[t].hasOwnProperty(e)},y.prototype.read=function(t){const e=i.readFileSync(t).toString("utf8").split(l);m.call(this,t,e)},y.prototype.readAsync=async function(t){const e=(await p(t)).toString("utf8").split(l);m.call(this,t,e)},y.prototype.get=function(t,e,r){if(this._sections.hasOwnProperty(t))return r?this._sections[t][e]:u.interpolate(this,t,e)},y.prototype.getInt=function(t,e,r){if(this._sections.hasOwnProperty(t))return r||(r=10),parseInt(this._sections[t][e],r)},y.prototype.getFloat=function(t,e){if(this._sections.hasOwnProperty(t))return parseFloat(this._sections[t][e])},y.prototype.items=function(t){return this._sections[t]},y.prototype.set=function(t,e,r){this._sections.hasOwnProperty(t)&&(this._sections[t][e]=r)},y.prototype.removeKey=function(t,e){return!(!this._sections.hasOwnProperty(t)||!this._sections[t].hasOwnProperty(e))&&delete this._sections[t][e]},y.prototype.removeSection=function(t){return!!this._sections.hasOwnProperty(t)&&delete this._sections[t]},y.prototype.write=function(t,e=!1){if(e){const e=o.dirname(t);s.sync(e)}i.writeFileSync(t,v.call(this))},y.prototype.writeAsync=async function(t,e=!1){if(e){const e=o.dirname(t);await d(e)}await g(t,v.call(this))},e.exports=y},{"./errors":13,"./interpolation":14,fs:1,mkdirp:15,path:6,util:10}],13:[function(t,e,r){e.exports={DuplicateSectionError:function(t){this.name="DuplicateSectionError",this.message=t+" already exists",Error.captureStackTrace(this,this.constructor)},NoSectionError:function(t){this.name=this.constructor.name,this.message="Section "+t+" does not exist.",Error.captureStackTrace(this,this.constructor)},ParseError:function(t,e,r){this.name=this.constructor.name,this.message="Source contains parsing errors.\nfile: "+t+" line: "+e+"\n"+r,Error.captureStackTrace(this,this.constructor)},MissingSectionHeaderError:function(t,e,r){this.name=this.constructor.name,this.message="File contains no section headers.\nfile: "+t+" line: "+e+"\n"+r,Error.captureStackTrace(this,this.constructor)},MaximumInterpolationDepthError:function(t,e,r,n){this.name=this.constructor.name,this.message="Exceeded Maximum Recursion Depth ("+n+") for key "+e+" in section "+t+"\nvalue: "+r,Error.captureStackTrace(this,this.constructor)}}},{}],14:[function(t,e,r){const n=t("./errors"),i=new RegExp(/%\(([\w-]+)\)s/),o=50;e.exports={interpolate:function(t,e,r){return function t(e,r,s,a){let u=e.get(r,s,!0);if(a>o)throw new n.MaximumInterpolationDepthError(r,s,u,o);let h=i.exec(u);for(;null!==h;){const n=h[1],o=t(e,r,n,a+1);u=u.substr(0,h.index)+o+u.substr(h.index+h[0].length),h=i.exec(u)}return u}(t,e,r,1)},MAXIMUM_INTERPOLATION_DEPTH:o}},{"./errors":13}],15:[function(t,e,r){var n=t("path"),i=t("fs"),o=parseInt("0777",8);function s(t,e,r,a){"function"==typeof e?(r=e,e={}):e&&"object"==typeof e||(e={mode:e});var u=e.mode,h=e.fs||i;void 0===u&&(u=o),a||(a=null);var f=r||function(){};t=n.resolve(t),h.mkdir(t,u,function(r){if(!r)return f(null,a=a||t);switch(r.code){case"ENOENT":if(n.dirname(t)===t)return f(r);s(n.dirname(t),e,function(r,n){r?f(r,n):s(t,e,f,n)});break;default:h.stat(t,function(t,e){t||!e.isDirectory()?f(r,a):f(null,a)})}})}e.exports=s.mkdirp=s.mkdirP=s,s.sync=function t(e,r,s){r&&"object"==typeof r||(r={mode:r});var a=r.mode,u=r.fs||i;void 0===a&&(a=o),s||(s=null),e=n.resolve(e);try{u.mkdirSync(e,a),s=s||e}catch(i){switch(i.code){case"ENOENT":t(e,r,s=t(n.dirname(e),r,s));break;default:var h;try{h=u.statSync(e)}catch(t){throw i}if(!h.isDirectory())throw i}}return s}},{fs:1,path:6}],16:[function(t,e,r){function n(){this._defaults=[]}["use","on","once","set","query","type","accept","auth","withCredentials","sortQuery","retry","ok","redirects","timeout","buffer","serialize","parse","ca","key","pfx","cert"].forEach(function(t){n.prototype[t]=function(){return this._defaults.push({fn:t,arguments:arguments}),this}}),n.prototype._setDefaults=function(t){this._defaults.forEach(function(e){t[e.fn].apply(t,e.arguments)})},e.exports=n},{}],17:[function(t,e,r){var n;"undefined"!=typeof window?n=window:"undefined"!=typeof self?n=self:(console.warn("Using browser-only version of superagent in non-browser environment"),n=this);var i=t("component-emitter"),o=t("./request-base"),s=t("./is-object"),a=t("./response-base"),u=t("./agent-base");function h(){}var f=r=e.exports=function(t,e){return"function"==typeof e?new r.Request("GET",t).end(e):1==arguments.length?new r.Request("GET",t):new r.Request(t,e)};r.Request=m,f.getXHR=function(){if(!(!n.XMLHttpRequest||n.location&&"file:"==n.location.protocol&&n.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}throw Error("Browser-only version of superagent could not find XHR")};var c="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};function l(t){if(!s(t))return t;var e=[];for(var r in t)p(e,r,t[r]);return e.join("&")}function p(t,e,r){if(null!=r)if(Array.isArray(r))r.forEach(function(r){p(t,e,r)});else if(s(r))for(var n in r)p(t,e+"["+n+"]",r[n]);else t.push(encodeURIComponent(e)+"="+encodeURIComponent(r));else null===r&&t.push(encodeURIComponent(e))}function g(t){for(var e,r,n={},i=t.split("&"),o=0,s=i.length;o=2&&t._responseTimeoutTimer&&clearTimeout(t._responseTimeoutTimer),4==r){var n;try{n=e.status}catch(t){n=0}if(!n){if(t.timedout||t._aborted)return;return t.crossDomainError()}t.emit("end")}};var n=function(e,r){r.total>0&&(r.percent=r.loaded/r.total*100),r.direction=e,t.emit("progress",r)};if(this.hasListeners("progress"))try{e.onprogress=n.bind(null,"download"),e.upload&&(e.upload.onprogress=n.bind(null,"upload"))}catch(t){}try{this.username&&this.password?e.open(this.method,this.url,!0,this.username,this.password):e.open(this.method,this.url,!0)}catch(t){return this.callback(t)}if(this._withCredentials&&(e.withCredentials=!0),!this._formData&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof r&&!this._isHost(r)){var i=this._header["content-type"],o=this._serializer||f.serialize[i?i.split(";")[0]:""];!o&&d(i)&&(o=f.serialize["application/json"]),o&&(r=o(r))}for(var s in this.header)null!=this.header[s]&&this.header.hasOwnProperty(s)&&e.setRequestHeader(s,this.header[s]);return this._responseType&&(e.responseType=this._responseType),this.emit("request",this),e.send(void 0!==r?r:null),this},f.agent=function(){return new u},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach(function(t){u.prototype[t.toLowerCase()]=function(e,r){var n=new f.Request(t,e);return this._setDefaults(n),r&&n.end(r),n}}),u.prototype.del=u.prototype.delete,f.get=function(t,e,r){var n=f("GET",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},f.head=function(t,e,r){var n=f("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},f.options=function(t,e,r){var n=f("OPTIONS",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},f.del=v,f.delete=v,f.patch=function(t,e,r){var n=f("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},f.post=function(t,e,r){var n=f("POST",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},f.put=function(t,e,r){var n=f("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n}},{"./agent-base":16,"./is-object":18,"./request-base":19,"./response-base":20,"component-emitter":11}],18:[function(t,e,r){"use strict";e.exports=function(t){return null!==t&&"object"==typeof t}},{}],19:[function(t,e,r){"use strict";var n=t("./is-object");function i(t){if(t)return function(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}(t)}e.exports=i,i.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete 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){if(!t||"object"!=typeof t)return this._timeout=t,this._responseTimeout=0,this;for(var e in t)switch(e){case"deadline":this._timeout=t.deadline;break;case"response":this._responseTimeout=t.response;break;default:console.warn("Unknown timeout option",e)}return this},i.prototype.retry=function(t,e){return 0!==arguments.length&&!0!==t||(t=1),t<=0&&(t=0),this._maxRetries=t,this._retries=0,this._retryCallback=e,this};var o=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];i.prototype._shouldRetry=function(t,e){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{var r=this._retryCallback(t,e);if(!0===r)return!0;if(!1===r)return!1}catch(t){console.error(t)}if(e&&e.status&&e.status>=500&&501!=e.status)return!0;if(t){if(t.code&&~o.indexOf(t.code))return!0;if(t.timeout&&"ECONNABORTED"==t.code)return!0;if(t.crossDomain)return!0}return!1},i.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},i.prototype.then=function(t,e){if(!this._fullfilledPromise){var r=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){r.end(function(r,n){r?e(r):t(n)})})}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(n(t)){for(var r in t)this.set(r,t[r]);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(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),n(t)){for(var r in t)this.field(r,t[r]);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._auth=function(t,e,r,n){switch(r.type){case"basic":this.set("Authorization","Basic "+n(t+":"+e));break;case"auto":this.username=t,this.password=e;break;case"bearer":this.set("Authorization","Bearer "+t)}return this},i.prototype.withCredentials=function(t){return void 0==t&&(t=!0),this._withCredentials=t,this},i.prototype.redirects=function(t){return this._maxRedirects=t,this},i.prototype.maxResponseSize=function(t){if("number"!=typeof t)throw TypeError("Invalid argument");return this._maxResponseSize=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=n(t),r=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"),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&&n(this._data))for(var i in t)this._data[i]=t[i];else"string"==typeof t?(r||this.type("form"),r=this._header["content-type"],this._data="application/x-www-form-urlencoded"==r?this._data?this._data+"&"+t:t:(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(r||this.type("json"),this)},i.prototype.sortQuery=function(t){return this._sort=void 0===t||t,this},i.prototype._finalizeQueryString=function(){var t=this._query.join("&");if(t&&(this.url+=(this.url.indexOf("?")>=0?"&":"?")+t),this._query.length=0,this._sort){var e=this.url.indexOf("?");if(e>=0){var r=this.url.substring(e+1).split("&");"function"==typeof this._sort?r.sort(this._sort):r.sort(),this.url=this.url.substring(0,e)+"?"+r.join("&")}}},i.prototype._appendQueryString=function(){console.trace("Unsupported")},i.prototype._timeoutError=function(t,e,r){if(!this._aborted){var n=new Error(t+e+"ms exceeded");n.timeout=e,n.code="ECONNABORTED",n.errno=r,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,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){t._timeoutError("Response timeout of ",t._responseTimeout,"ETIMEDOUT")},this._responseTimeout))}},{"./is-object":18}],20:[function(t,e,r){"use strict";var n=t("./utils");function i(t){if(t)return function(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}(t)}e.exports=i,i.prototype.get=function(t){return this.header[t.toLowerCase()]},i.prototype._setHeaderProperties=function(t){var e=t["content-type"]||"";this.type=n.type(e);var r=n.params(e);for(var i in r)this[i]=r[i];this.links={};try{t.link&&(this.links=n.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.created=201==t,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,this.unprocessableEntity=422==t}},{"./utils":21}],21:[function(t,e,r){"use strict";r.type=function(t){return t.split(/ *; */).shift()},r.params=function(t){return t.split(/ *; */).reduce(function(t,e){var r=e.split(/ *= */),n=r.shift(),i=r.shift();return n&&i&&(t[n]=i),t},{})},r.parseLinks=function(t){return t.split(/ *, */).reduce(function(t,e){var r=e.split(/ *; */),n=r[0].slice(1,-1);return t[r[1].split(/ *= */)[1].slice(1,-1)]=n,t},{})},r.cleanHeader=function(t,e){return delete t["content-type"],delete t["content-length"],delete t["transfer-encoding"],delete t.host,e&&(delete t.authorization,delete t.cookie),t}},{}],platformClient:[function(t,e,r){(function(r,n){(function(){"use strict";var n,i=(n=t("superagent"))&&"object"==typeof n&&"default"in n?n.default:n,o={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud"},s=void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},a=[],u=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,f=!1;function c(){f=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+a[i>>12&63]+a[i>>6&63]+a[63&i]);return o.join("")}function p(t){var e;f||c();for(var r=t.length,n=r%3,i="",o=[],s=0,u=r-n;su?u:s+16383));return 1===n?(e=t[r-1],i+=a[e>>2],i+=a[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=a[e>>10],i+=a[e>>4&63],i+=a[e<<2&63],i+="="),o.push(i),o.join("")}function g(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function d(t,e,r,n,i,o){var s,a,u,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,g=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+c>=1?l/u:l*Math.pow(2,1-c))*u>=2&&(s++,u/=2),s+c>=f?(a=0,s=f):s+c>=1?(a=(e*u-1)*Math.pow(2,i),s+=c):(a=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=g,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=g,s/=256,h-=8);t[r+p-g]|=128*d}var y={}.toString,m=Array.isArray||function(t){return"[object Array]"==y.call(t)};function v(){return b.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function w(t,e){if(v()=v())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+v().toString(16)+" bytes");return 0|t}function S(t){return!(null==t||!t._isBuffer)}function R(t,e){if(S(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 r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Z(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return tt(t).length;default:if(n)return Z(t).length;e=(""+e).toLowerCase(),n=!0}}function x(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function P(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=b.from(e,n)),S(e))return 0===e.length?-1:I(t,e,r,n,i);if("number"==typeof e)return e&=255,b.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):I(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function I(t,e,r,n,i){var o,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function j(t,e,r){return 0===e&&r===t.length?p(t):p(t.slice(e,r))}function D(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&h)<<6|63&o)>127&&(f=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&h)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=q)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return G(this,e,r);case"utf8":case"utf-8":return D(this,e,r);case"ascii":return N(this,e,r);case"latin1":case"binary":return z(this,e,r);case"base64":return j(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},b.prototype.equals=function(t){if(!S(t))throw new TypeError("Argument must be a Buffer");return this===t||0===b.compare(this,t)},b.prototype.inspect=function(){var t="";return this.length>0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},b.prototype.compare=function(t,e,r,n,i){if(!S(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,s=r-e,a=Math.min(o,s),u=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return O(this,t,e,r);case"utf8":case"utf-8":return B(this,t,e,r);case"ascii":return M(this,t,e,r);case"latin1":case"binary":return U(this,t,e,r);case"base64":return L(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var q=4096;function N(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function Y(t,e,r,n,i,o){if(!S(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function H(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function $(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function J(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function K(t,e,r,n,i){return i||J(t,0,r,4),d(t,e,r,n,23,4),r+4}function X(t,e,r,n,i){return i||J(t,0,r,8),d(t,e,r,n,52,8),r+8}b.prototype.slice=function(t,e){var r,n=this.length;if(t=~~t,e=void 0===e?n:~~e,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),e<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},b.prototype.readUInt8=function(t,e){return e||F(t,1,this.length),this[t]},b.prototype.readUInt16LE=function(t,e){return e||F(t,2,this.length),this[t]|this[t+1]<<8},b.prototype.readUInt16BE=function(t,e){return e||F(t,2,this.length),this[t]<<8|this[t+1]},b.prototype.readUInt32LE=function(t,e){return e||F(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},b.prototype.readUInt32BE=function(t,e){return e||F(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},b.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||F(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},b.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||F(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},b.prototype.readInt8=function(t,e){return e||F(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},b.prototype.readInt16LE=function(t,e){e||F(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},b.prototype.readInt16BE=function(t,e){e||F(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},b.prototype.readInt32LE=function(t,e){return e||F(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},b.prototype.readInt32BE=function(t,e){return e||F(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},b.prototype.readFloatLE=function(t,e){return e||F(t,4,this.length),g(this,t,!0,23,4)},b.prototype.readFloatBE=function(t,e){return e||F(t,4,this.length),g(this,t,!1,23,4)},b.prototype.readDoubleLE=function(t,e){return e||F(t,8,this.length),g(this,t,!0,52,8)},b.prototype.readDoubleBE=function(t,e){return e||F(t,8,this.length),g(this,t,!1,52,8)},b.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Y(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},b.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,255,0),b.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},b.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),b.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):H(this,t,e,!0),e+2},b.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):H(this,t,e,!1),e+2},b.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),b.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):$(this,t,e,!0),e+4},b.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):$(this,t,e,!1),e+4},b.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},b.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},b.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,127,-128),b.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},b.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),b.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):H(this,t,e,!0),e+2},b.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):H(this,t,e,!1),e+2},b.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),b.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):$(this,t,e,!0),e+4},b.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),b.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):$(this,t,e,!1),e+4},b.prototype.writeFloatLE=function(t,e,r){return K(this,t,e,!0,r)},b.prototype.writeFloatBE=function(t,e,r){return K(this,t,e,!1,r)},b.prototype.writeDoubleLE=function(t,e,r){return X(this,t,e,!0,r)},b.prototype.writeDoubleBE=function(t,e,r){return X(this,t,e,!1,r)},b.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!b.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function tt(t){return function(t){var e,r,n,i,o,s;f||c();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[a-2]?2:"="===t[a-1]?1:0,s=new h(3*a/4-o),n=o>0?a-4:a;var l=0;for(e=0,r=0;e>16&255,s[l++]=i>>8&255,s[l++]=255&i;return 2===o?(i=u[t.charCodeAt(e)]<<2|u[t.charCodeAt(e+1)]>>4,s[l++]=255&i):1===o&&(i=u[t.charCodeAt(e)]<<10|u[t.charCodeAt(e+1)]<<4|u[t.charCodeAt(e+2)]>>2,s[l++]=i>>8&255,s[l++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(V,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function et(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function rt(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}const nt={level:{LNone:"none",LError:"error",LDebug:"debug",LTrace:"trace"}},it={formats:{JSON:"json",TEXT:"text"}};class ot{get logLevelEnum(){return nt}get logFormatEnum(){return it}constructor(){this.log_level=nt.level.LNone,this.log_format=it.formats.TEXT,this.log_to_console=!0,this.log_file_path,this.log_response_body=!1,this.log_request_body=!1,this.setLogger()}setLogger(){}log(t,e,r,n,i,o,s,a){var u=this.formatLog(t,e,r,n,i,o,s,a);"undefined"!=typeof window?this.calculateLogLevel(t)>0&&!0===this.log_to_console&&(this.log_format===this.logFormatEnum.formats.JSON?console.log(u):console.log(`${t.toUpperCase()}: ${u}`)):this.logger.transports.length>0&&this.logger.log(t,u)}calculateLogLevel(t){switch(this.log_level){case this.logLevelEnum.level.LError:return t!==this.logLevelEnum.level.LError?-1:1;case this.logLevelEnum.level.LDebug:return t===this.logLevelEnum.level.LTrace?-1:1;case this.logLevelEnum.level.LTrace:return 1;default:return-1}}formatLog(t,e,r,n,i,o,s,a){var u;return i&&(i.Authorization="[REDACTED]"),this.log_request_body||(s=void 0),this.log_response_body||(a=void 0),this.log_format&&this.log_format===it.formats.JSON?(u={level:t,date:(new Date).toISOString(),method:r,url:decodeURIComponent(n),correlationId:o&&o["inin-correlation-id"]?o["inin-correlation-id"]:"",statusCode:e},i&&(u.requestHeaders=i),o&&(u.responseHeaders=o),s&&(u.requestBody=s),a&&(u.responseBody=a)):u=`${(new Date).toISOString()}\n=== REQUEST === \n${this.formatValue("URL",decodeURIComponent(n))}${this.formatValue("Method",r)}${this.formatValue("Headers",this.formatHeaderString(i))}${this.formatValue("Body",s?JSON.stringify(s,null,2):"")}\n=== RESPONSE ===\n${this.formatValue("Status",e)}${this.formatValue("Headers",this.formatHeaderString(o))}${this.formatValue("CorrelationId",o&&o["inin-correlation-id"]?o["inin-correlation-id"]:"")}${this.formatValue("Body",a?JSON.stringify(a,null,2):"")}`,u}formatHeaderString(t){var e="";if(!t)return e;for(const[r,n]of Object.entries(t))e+=`\n\t${r}: ${n}`;return e}formatValue(t,e){return e&&""!==e&&"{}"!==e?`${t}: ${e}\n`:""}getLogLevel(t){switch(t){case"error":return nt.level.LError;case"debug":return nt.level.LDebug;case"trace":return nt.level.LTrace;default:return nt.level.LNone}}getLogFormat(t){switch(t){case"json":return it.formats.JSON;default:return it.formats.TEXT}}}class st{get instance(){return st.instance}set instance(t){st.instance=t}constructor(){if(st.instance||(st.instance=this),"undefined"!=typeof window)this.configPath="";else{const e=t("os"),r=t("path");this.configPath=r.join(e.homedir(),".genesyscloudjavascript-guest","config")}this.live_reload_config=!0,this.host,this.environment,this.basePath,this.authUrl,this.config,this.logger=new ot,this.setEnvironment(),this.liveLoadConfig()}liveLoadConfig(){if("undefined"==typeof window){if(this.updateConfigFromFile(),this.live_reload_config&&!0===this.live_reload_config)try{const e=t("fs");e.watchFile(this.configPath,{persistent:!1},(t,r)=>{this.updateConfigFromFile(),this.live_reload_config||e.unwatchFile(this.configPath)})}catch(t){}}else this.configPath=""}setConfigPath(t){t&&t!==this.configPath&&(this.configPath=t,this.liveLoadConfig())}updateConfigFromFile(){var e=new(t("configparser"));try{e.read(this.configPath),this.config=e}catch(e){if(e.name&&"MissingSectionHeaderError"===e.name){var r=t("fs").readFileSync(this.configPath,"utf8");this.config={_sections:JSON.parse(r)}}}this.config&&this.updateConfigValues()}updateConfigValues(){this.logger.log_level=this.logger.getLogLevel(this.getConfigString("logging","log_level")),this.logger.log_format=this.logger.getLogFormat(this.getConfigString("logging","log_format")),this.logger.log_to_console=void 0!==this.getConfigBoolean("logging","log_to_console")?this.getConfigBoolean("logging","log_to_console"):this.logger.log_to_console,this.logger.log_file_path=void 0!==this.getConfigString("logging","log_file_path")?this.getConfigString("logging","log_file_path"):this.logger.log_file_path,this.logger.log_response_body=void 0!==this.getConfigBoolean("logging","log_response_body")?this.getConfigBoolean("logging","log_response_body"):this.logger.log_response_body,this.logger.log_request_body=void 0!==this.getConfigBoolean("logging","log_request_body")?this.getConfigBoolean("logging","log_request_body"):this.logger.log_request_body,this.live_reload_config=void 0!==this.getConfigBoolean("general","live_reload_config")?this.getConfigBoolean("general","live_reload_config"):this.live_reload_config,this.host=void 0!==this.getConfigString("general","host")?this.getConfigString("general","host"):this.host,this.setEnvironment(),this.logger.setLogger()}setEnvironment(t){this.environment=t||(this.host?this.host:"mypurecloud.com"),this.environment=this.environment.replace(/\/+$/,""),this.environment.startsWith("https://")&&(this.environment=this.environment.substring(8)),this.environment.startsWith("http://")&&(this.environment=this.environment.substring(7)),this.environment.startsWith("api.")&&(this.environment=this.environment.substring(4)),this.basePath=`https://api.${this.environment}`,this.authUrl=`https://login.${this.environment}`}getConfigString(t,e){if(this.config._sections[t])return this.config._sections[t][e]}getConfigBoolean(t,e){if(this.config._sections[t]&&void 0!==this.config._sections[t][e])return"string"==typeof this.config._sections[t][e]?"true"===this.config._sections[t][e]:this.config._sections[t][e]}}class at{get instance(){return at.instance}set instance(t){at.instance=t}constructor(){at.instance||(at.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(t){this.hasLocalStorage=!1}this.config=new st,this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=i,"undefined"!=typeof window&&(window.ApiClient=this)}setReturnExtendedResponses(t){this.returnExtended=t}setPersistSettings(t,e){this.persistSettings=t,this.settingsPrefix=e?e.replace(/\W+/g,"_"):"purecloud"}_saveSettings(t){try{if(this.authData.apiKey=t.apiKey,this.authentications["Guest Chat JWT"].apiKey=t.apiKey,t.state&&(this.authData.state=t.state),t.tokenExpiryTime&&(this.authData.tokenExpiryTime=t.tokenExpiryTime,this.authData.tokenExpiryTimeString=t.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;let e=JSON.parse(JSON.stringify(this.authData));delete e.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(e))}catch(t){console.error(t)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;const t=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=t}setEnvironment(t){this.config.setEnvironment(t)}_testTokenAccess(){return new Promise((t,e)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{t()}).catch(t=>{this._saveSettings({apiKey:void 0}),e(t)}):e(new Error("Token is not set"))})}setJwt(t){this._saveSettings({apiKey:t})}setStorageKey(t){this.storageKey=t,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(t,e){return e||(e={}),Object.keys(e).reduce((t,r)=>e[r]?`${t}&${r}=${e[r]}`:t,`${this.config.authUrl}/${t}?`)}paramToString(t){return t?t instanceof Date?t.toJSON():t.toString():""}buildUrl(t,e){t.match(/^\//)||(t=`/${t}`);var r=this.config.basePath+t;return r=r.replace(/\{([\w-]+)\}/g,(t,r)=>{var n;return n=e.hasOwnProperty(r)?this.paramToString(e[r]):t,encodeURIComponent(n)})}isJsonMime(t){return Boolean(t&&t.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(t){for(var e=0;e{var r=this.authentications[e];switch(r.type){case"basic":(r.username||r.password)&&t.auth(r.username||"",r.password||"");break;case"apiKey":if(r.apiKey){var n={};r.apiKeyPrefix?n[r.name]=`${r.apiKeyPrefix} ${r.apiKey}`:n[r.name]=r.apiKey,"header"===r.in?t.set(n):t.query(n)}break;case"oauth2":r.accessToken&&t.set({Authorization:`Bearer ${r.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${r.type}`)}})}callApi(t,e,r,n,o,s,a,u,h,f){var c=this.buildUrl(t,r),l=i(e,c);this.proxy&&l.proxy&&l.proxy(this.proxy),this.applyAuthToRequest(l,u),l.query(this.normalizeParams(n)),l.set(this.defaultHeaders).set(this.normalizeParams(o)),l.timeout(this.timeout);var p=this.jsonPreferredMime(h);if(p?l.type(p):l.header["Content-Type"]||l.type("application/json"),"application/x-www-form-urlencoded"===p)l.send(this.normalizeParams(s));else if("multipart/form-data"==p){var g=this.normalizeParams(s);for(var d in g)g.hasOwnProperty(d)&&(this.isFileParam(g[d])?l.attach(d,g[d]):l.field(d,g[d]))}else a&&l.send(a);var y=this.jsonPreferredMime(f);return y&&l.accept(y),new Promise((t,r)=>{l.end((n,i)=>{if(!n||i){var o=!0===this.returnExtended||n?{status:i.status,statusText:i.statusText,headers:i.headers,body:i.body,text:i.text,error:n}:i.body?i.body:i.text;this.config.logger.log("trace",i.statusCode,e,c,l.header,i.headers,a,void 0),this.config.logger.log("debug",i.statusCode,e,c,l.header,void 0,a,void 0),n?(this.config.logger.log("error",i.statusCode,e,c,l.header,i.headers,a,i.body),r(o)):t(o)}else r({status:0,statusText:"error",headers:[],body:{},text:"error",error:n})})})}}class ut{constructor(t){this.apiClient=t||at.instance}deleteWebchatGuestConversationMember(t,e){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling deleteWebchatGuestConversationMember';if(void 0===e||null===e)throw'Missing the required parameter "memberId" when calling deleteWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","DELETE",{conversationId:t,memberId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequest(t,e){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequest';if(void 0===e||null===e)throw'Missing the required parameter "mediaRequestId" when calling getWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","GET",{conversationId:t,mediaRequestId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequests(t){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequests';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests","GET",{conversationId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMember(t,e){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMember';if(void 0===e||null===e)throw'Missing the required parameter "memberId" when calling getWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","GET",{conversationId:t,memberId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMembers(t,e){if(e=e||{},void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMembers';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members","GET",{conversationId:t},{pageSize:e.pageSize,pageNumber:e.pageNumber,excludeDisconnectedMembers:e.excludeDisconnectedMembers},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessage(t,e){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessage';if(void 0===e||null===e)throw'Missing the required parameter "messageId" when calling getWebchatGuestConversationMessage';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages/{messageId}","GET",{conversationId:t,messageId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessages(t,e){if(e=e||{},void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages","GET",{conversationId:t},{after:e.after,before:e.before,sortOrder:e.sortOrder,maxResults:e.maxResults},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}patchWebchatGuestConversationMediarequest(t,e,r){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling patchWebchatGuestConversationMediarequest';if(void 0===e||null===e)throw'Missing the required parameter "mediaRequestId" when calling patchWebchatGuestConversationMediarequest';if(void 0===r||null===r)throw'Missing the required parameter "body" when calling patchWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","PATCH",{conversationId:t,mediaRequestId:e},{},{},{},r,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberMessages(t,e,r){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberMessages';if(void 0===e||null===e)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberMessages';if(void 0===r||null===r)throw'Missing the required parameter "body" when calling postWebchatGuestConversationMemberMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/messages","POST",{conversationId:t,memberId:e},{},{},{},r,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberTyping(t,e){if(void 0===t||null===t)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberTyping';if(void 0===e||null===e)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberTyping';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/typing","POST",{conversationId:t,memberId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversations(t){if(void 0===t||null===t)throw'Missing the required parameter "body" when calling postWebchatGuestConversations';return this.apiClient.callApi("/api/v2/webchat/guest/conversations","POST",{},{},{},{},t,[],["application/json"],["application/json"])}}var ht=new class{constructor(){this.ApiClient=new at,this.WebChatApi=ut,this.PureCloudRegionHosts=o}};e.exports=ht}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{buffer:3,configparser:12,fs:1,os:5,path:6,superagent:17}]},{},[]); \ No newline at end of file diff --git a/build/docs/index.md b/build/docs/index.md index f190d97f..0a6b34bb 100644 --- a/build/docs/index.md +++ b/build/docs/index.md @@ -31,7 +31,7 @@ For direct use in a browser script: ```{"language":"html"} - + @@ -149,6 +149,78 @@ webChatApi.postWebchatGuestConversations(createChatBody) .catch(console.error); ``` +## SDK Logging + +Logging of API requests and responses can be controlled by a number of parameters on the `Configuration`'s `Logger` instance. + +`log_level` values: +1. LTrace (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers, Response Headers) +2. LDebug (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers) +3. LError (HTTP Method, URL, Request Body, Response Body, HTTP Status Code, Request Headers, Response Headers) +4. LNone - default + +`log_format` values: +1. JSON +2. TEXT - default + +By default, the request and response bodies are not logged because these can contain PII. Be mindful of this data if choosing to log it. +To log to a file, provide a `log_file_path` value. SDK users are responsible for the rotation of the log file. This feature is not available in browser-based applications. + +Example logging configuration: +```{"language":"javascript"} +client.config.logger.log_level = client.config.logger.logLevelEnum.level.LTrace; +client.config.logger.log_format = client.config.logger.logFormatEnum.formats.JSON; +client.config.logger.log_request_body = true; +client.config.logger.log_response_body = true; +client.config.logger.log_to_console = true; +client.config.logger.log_file_path = "/var/log/javascriptguestsdk.log"; + +client.config.logger.setLogger(); // To apply above changes +``` + +#### Configuration file + +**Note:** This feature is not available in browser-based applications + +A number of configuration parameters can be applied using a configuration file. There are two sources for this file: + +1. The SDK will look for `%USERPROFILE%\.genesyscloudjavascript-guest\config` on Windows if the environment variable USERPROFILE is defined, otherwise uses the path to the profile directory of the current user as home, or `$HOME/.genesyscloudjavascript-guest/config` on Unix. +2. Provide a valid file path to `client.config.setConfigPath()` + +The SDK will constantly check to see if the config file has been updated, regardless of whether a config file was present at start-up. To disable this behaviour, set `client.config.live_reload_config` to false. +INI and JSON formats are supported. See below for examples of configuration values in both formats: + +INI: +```{"language":"ini"} +[logging] +log_level = trace +log_format = text +log_to_console = false +log_file_path = /var/log/javascriptguestsdk.log +log_response_body = false +log_request_body = false +[general] +live_reload_config = true +host = https://api.mypurecloud.com +``` + +JSON: +```{"language":"json"} +{ + "logging": { + "log_level": "trace", + "log_format": "text", + "log_to_console": false, + "log_file_path": "/var/log/javascriptguestsdk.log", + "log_response_body": false, + "log_request_body": false + }, + "general": { + "live_reload_config": true, + "host": "https://api.mypurecloud.com" + } +} +``` ## Environments @@ -281,16 +353,6 @@ Example error response object: ``` -## Debug Logging - -There are hooks to trace requests and responses. To enable debug tracing, provide a log object. Optionally, specify a maximum number of lines. If specified, the response body trace will be truncated. If not specified, the entire response body will be traced out. - -```{"language":"javascript"} -const client = platformClient.ApiClient.instance; -client.setDebugLog(console.log, 25); -``` - - ## Versioning The SDK's version is incremented according to the [Semantic Versioning Specification](https://semver.org/). The decision to increment version numbers is determined by [diffing the Platform API's swagger](https://github.com/purecloudlabs/platform-client-sdk-common/blob/master/modules/swaggerDiff.js) for automated builds, and optionally forcing a version bump when a build is triggered manually (e.g. releasing a bugfix). diff --git a/build/docs/releaseNotes.md b/build/docs/releaseNotes.md index 3e76be49..c6c099b1 100644 --- a/build/docs/releaseNotes.md +++ b/build/docs/releaseNotes.md @@ -1,7 +1,7 @@ Platform API version: 4658 -Reverting logging and configuration changes because of regression introduced. +Adding the configuration and logging changes back because the browser issues have been resolved. See https://developer.genesys.cloud/api/rest/client-libraries/ for more information # Major Changes (0 changes) diff --git a/build/index.d.ts b/build/index.d.ts index 0c806ca1..bd99cfa1 100644 --- a/build/index.d.ts +++ b/build/index.d.ts @@ -1,4 +1,5 @@ import platformClient = require('purecloud-guest-chat-client'); +import Configuration = require('./src/purecloud-guest-chat-client/configuration'); declare module 'purecloud-guest-chat-client' { export const ApiClient: ApiClientClass; @@ -8,10 +9,10 @@ declare class ApiClientClass { instance: ApiClientClass; proxy: ProxyConfig; superagent: any; + config: Configuration; callApi(path: string, httpMethod: string, pathParams: { [key: string]: string; }, queryParams: { [key: string]: object; }, headerParams: { [key: string]: object; }, formParams: { [key: string]: object; }, bodyParam: any, authNames: Array, contentTypes: Array, accepts: Array): Promise; setJwt(jwt: string): void; - setDebugLog(debugLog: any, maxLines: number): void; setEnvironment(environment: string): void; setPersistSettings(doPersist: boolean, prefix?: string): void; setReturnExtendedResponses(returnExtended: boolean): void; diff --git a/build/node_modules/@dabh/diagnostics/CHANGELOG.md b/build/node_modules/@dabh/diagnostics/CHANGELOG.md new file mode 100644 index 00000000..b04af38b --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/CHANGELOG.md @@ -0,0 +1,26 @@ +# CHANGELOG + +### 2.0.2 + +- Bump to kuler 2.0, which removes colornames as dependency, which we + never used. So smaller install size, less dependencies for all. + +### 2.0.1 + +- Use `storag-engine@3.0` which will automatically detect the correct + AsyncStorage implementation. +- The upgrade also fixes a bug where it the `debug` and `diagnostics` values + to be JSON encoded instead of regular plain text. + +### 2.0.0 + +- Documentation improvements. +- Fixed a issue where async adapters were incorrectly detected. +- Correctly inherit colors after applying colors the browser's console. + +### 2.0.0-alpha + +- Complete rewrite of all internals, now comes with separate builds for `browser` + `node` and `react-native` as well as dedicated builds for `production` and + `development` environments. Various utility methods and properties have + been added to the returned logger to make your lives even easier. diff --git a/build/node_modules/@dabh/diagnostics/LICENSE b/build/node_modules/@dabh/diagnostics/LICENSE new file mode 100644 index 00000000..9beaab11 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the 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. diff --git a/build/node_modules/@dabh/diagnostics/README.md b/build/node_modules/@dabh/diagnostics/README.md new file mode 100644 index 00000000..9354a74e --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/README.md @@ -0,0 +1,473 @@ +# `diagnostics` + +Diagnostics in the evolution of debug pattern that is used in the Node.js core, +this extremely small but powerful technique can best be compared as feature +flags for loggers. The created debug logger is disabled by default but can be +enabled without changing a line of code, using flags. + +- Allows debugging in multiple JavaScript environments such as Node.js, browsers + and React-Native. +- Separated development and production builds to minimize impact on your + application when bundled. +- Allows for customization of logger, messages, and much more. + +![Output Example](example.png) + +## Installation + +The module is released in the public npm registry and can be installed by +running: + +``` +npm install --save diagnostics +``` + +## Usage + +- [Introduction](#introduction) +- [Advanced usage](#advanced-usage) + - [Production and development builds](#production-and-development-builds) + - [WebPack](#webpack) + - [Node.js](#nodejs) +- [API](#api) + - [.enabled](#enabled) + - [.namespace](#namespace) + - [.dev/prod](#devprod) + - [set](#set) + - [modify](#modify) + - [use](#use) +- [Modifiers](#modifiers) + - [namespace](#namespace-1) +- [Adapters](#adapters) + - [process.env](#process-env) + - [hash](#hash) + - [localStorage](#localstorage) + - [AsyncStorage](#asyncstorage) +- [Loggers](#loggers) + +### Introduction + +To create a new logger simply `require` the `diagnostics` module and call +the returned function. It accepts 2 arguments: + +1. `namespace` **Required** This is the namespace of your logger so we know if we need to + enable your logger when a debug flag is used. Generally you use the name of + your library or application as first root namespace. For example if you're + building a parser in a library (example) you would set namespace + `example:parser`. +2. `options` An object with additional configuration for the logger. + following keys are recognized: + - `force` Force the logger to be enabled. + - `colors` Colors are enabled by default for the logs, but you can set this + option to `false` to disable it. + +```js +const debug = require('diagnostics')('foo:bar:baz'); +const debug = require('diagnostics')('foo:bar:baz', { options }); + +debug('this is a log message %s', 'that will only show up when enabled'); +debug('that is pretty neat', { log: 'more', data: 1337 }); +``` + +Unlike `console.log` statements that add and remove during your development +lifecycle you create meaningful log statements that will give you insight in +the library or application that you're developing. + +The created debugger uses different "adapters" to extract the debug flag +out of the JavaScript environment. To learn more about enabling the debug flag +in your specific environment click on one of the enabled adapters below. + +- **browser**: [localStorage](#localstorage), [hash](#hash) +- **node.js**: [environment variables](#processenv) +- **react-native**: [AsyncStorage](#asyncstorage) + +Please note that the returned logger is fully configured out of the box, you +do not need to set any of the adapters/modifiers your self, they are there +for when you want more advanced control over the process. But if you want to +learn more about that, read the next section. + +### Advanced usage + +There are 2 specific usage patterns for `diagnostic`, library developers who +implement it as part of their modules and applications developers who either +use it in their application or are searching for ways to consume the messages. + +With the simple log interface as discussed in the [introduction](#introduction) +section we make it easy for developers to add it as part of their libraries +and applications, and with powerful [API](#api) we allow infinite customization +by allowing custom adapters, loggers and modifiers to ensure that this library +maintains relevant. These methods not only allow introduction of new loggers, +but allow you think outside the box. For example you can maintain a history +of past log messages, and output those when an uncaught exception happens in +your application so you have additional context + +```js +const diagnostics = require('diagnostics'); + +let index = 0; +const limit = 200; +const history = new Array(limit); + +// +// Force all `diagnostic` loggers to be enabled. +// +diagnostics.force = process.env.NODE_ENV === 'prod'; +diagnostics.set(function customLogger(meta, message) { + history[index]= { meta, message, now: Date.now() }; + if (index++ === limit) index = 0; + + // + // We're running a development build, so output. + // + if (meta.dev) console.log.apply(console, message); +}); + +process.on('uncaughtException', async function (err) { + await saveErrorToDisk(err, history); + process.exit(1); +}); +``` + +The small snippet above will maintain a 200 limited FIFO (First In First Out) +queue of all debug messages that can be referenced when your application crashes + +#### Production and development builds + +When you `require` the `diagnostics` module you will be given a logger that is +optimized for `development` so it can provide the best developer experience +possible. + +The development logger enables all the [adapters](#adapters) for your +JavaScript environment, adds a logger that outputs the messages to `console.log` +and registers our message modifiers so log messages will be prefixed with the +supplied namespace so you know where the log messages originates from. + +The development logger does not have any adapter, modifier and logger enabled +by default. This ensures that your log messages never accidentally show up in +production. However this does not mean that it's not possible to get debug +messages in production. You can `force` the debugger to be enabled, and +supply a [custom logger](#loggers). + +```js +const diagnostics = require('diagnostics'); +const debug = debug('foo:bar', { force: true }); + +// +// Or enable _every_ diagnostic instance: +// +diagnostics.force = true; +``` + +##### WebPack + +WebPack has the concept of [mode](https://webpack.js.org/concepts/mode/#usage)'s +which creates different + +```js +module.exports = { + mode: 'development' // 'production' +} +``` + +When you are building your app using the WebPack CLI you can use the `--mode` +flag: + +``` +webpack --mode=production app.js -o /dist/bundle.js +``` + +##### Node.js + +When you are running your app using `Node.js` you should the `NODE_ENV` +environment variable to `production` to ensure that you libraries that you +import are optimized for production. + +``` +NODE_ENV=production node app.js +``` + +### API + +The returned logger exposes some addition properties that can be used used in +your application or library: + +#### .enabled + +The returned logger will have a `.enabled` property assigned to it. This boolean +can be used to check if the logger was enabled: + +```js +const debug = require('diagnostics')('foo:bar'); + +if (debug.enabled) { + // + // Do something special + // +} +``` + +This property is exposed as: + +- Property on the logger. +- Property on the meta/options object. + +#### .namespace + +This is the namespace that you originally provided to the function. + +```js +const debug = require('diagnostics')('foo:bar'); + +console.log(debug.namespace); // foo:bar +``` + +This property is exposed as: + +- Property on the logger. +- Property on the meta/options object. + +#### .dev/prod + +There are different builds available of `diagnostics`, when you create a +production build of your application using `NODE_ENV=production` you will be +given an optimized, smaller build of `diagnostics` to reduce your bundle size. +The `dev` and `prod` booleans on the returned logger indicate if you have a +production or development version of the logger. + +```js +const debug = require('diagnostics')('foo:bar'); + +if (debug.prod) { + // do stuff +} +``` + +This property is exposed as: + +- Property on the logger. +- Property on the meta/options object. + +#### set + +Sets a new logger as default for **all** `diagnostic` instances. The passed +argument should be a function that write the log messages to where ever you +want. It receives 2 arguments: + +1. `meta` An object with all the options that was provided to the original + logger that wants to write the log message as well as properties of the + debugger such as `prod`, `dev`, `namespace`, `enabled`. See [API](#api) for + all exposed properties. +2. `args` An array of the log messages that needs to be written. + +```js +const debug = require('diagnostics')('foo:more:namespaces'); + +debug.use(function logger(meta, args) { + console.log(meta); + console.debug(...args); +}); +``` + +This method is exposed as: + +- Method on the logger. +- Method on the meta/options object. +- Method on `diagnostics` module. + +#### modify + +The modify method allows you add a new message modifier to **all** `diagnostic` +instances. The passed argument should be a function that returns the passed +message after modification. The function receives 2 arguments: + +1. `message`, Array, the log message. +2. `options`, Object, the options that were passed into the logger when it was + initially created. + +```js +const debug = require('diagnostics')('example:modifiers'); + +debug.modify(function (message, options) { + return messages; +}); +``` + +This method is exposed as: + +- Method on the logger. +- Method on the meta/options object. +- Method on `diagnostics` module. + +See [modifiers](#modifiers) for more information. + +#### use + +Adds a new `adapter` to **all** `diagnostic` instances. The passed argument +should be a function returns a boolean that indicates if the passed in +`namespace` is allowed to write log messages. + +```js +const diagnostics = require('diagnostics'); +const debug = diagnostics('foo:bar'); + +debug.use(function (namespace) { + return namespace === 'foo:bar'; +}); +``` + +This method is exposed as: + +- Method on the logger. +- Method on the meta/options object. +- Method on `diagnostics` module. + +See [adapters](#adapters) for more information. + +### Modifiers + +To be as flexible as possible when it comes to transforming messages we've +come up with the concept of `modifiers` which can enhance the debug messages. +This allows you to introduce functionality or details that you find important +for debug messages, and doesn't require us to add additional bloat to the +`diagnostic` core. + +For example, you want the messages to be prefixed with the date-time of when +the log message occured: + +```js +const diagnostics = require('diagnostics'); + +diagnostics.modify(function datetime(args, options) { + args.unshift(new Date()); + return args; +}); +``` + +Now all messages will be prefixed with date that is outputted by `new Date()`. +The following modifiers are shipped with `diagnostics` and are enabled in +**development** mode only: + +- [namespace](#namespace) + +#### namespace + +This modifier is enabled for all debug instances and prefixes the messages +with the name of namespace under which it is logged. The namespace is colored +using the `colorspace` module which groups similar namespaces under the same +colorspace. You can have multiple namespaces for the debuggers where each +namespace should be separated by a `:` + +``` +foo +foo:bar +foo:bar:baz +``` + +For console based output the `namespace-ansi` is used. + +### Adapters + +Adapters allows `diagnostics` to pull the `DEBUG` and `DIAGNOSTICS` environment +variables from different sources. Not every JavaScript environment has a +`process.env` that we can leverage. Adapters allows us to have different +adapters for different environments. It means you can write your own custom +adapter if needed as well. + +The `adapter` function should be passed a function as argument, this function +will receive the `namespace` of a logger as argument and it should return a +boolean that indicates if that logger should be enabled or not. + +```js +const debug = require('diagnostics')('example:namespace'); + +debug.adapter(require('diagnostics/adapters/localstorage')); +``` + +The modifiers are only enabled for `development`. The following adapters are +available are available: + +#### process.env + +This adapter is enabled for `node.js`. + +Uses the `DEBUG` or `DIAGNOSTICS` (both are recognized) environment variables to +pass in debug flag: + +**UNIX/Linux/Mac** +``` +DEBUG=foo* node index.js +``` + +Using environment variables on Windows is a bit different, and also depends on +toolchain you are using: + +**Windows** +``` +set DEBUG=foo* & node index.js +``` + +**Powershell** +``` +$env:DEBUG='foo*';node index.js +``` + +#### hash + +This adapter is enabled for `browsers`. + +This adapter uses the `window.location.hash` of as source for the environment +variables. It assumes that hash is formatted using the same syntax as query +strings: + +```js +http://example.com/foo/bar#debug=foo* +``` + +It triggers on both the `debug=` and `diagnostics=` names. + +#### localStorage + +This adapter is enabled for `browsers`. + +This adapter uses the `localStorage` of the browser to store the debug flags. +You can set the debug flag your self in your application code, but you can +also open browser WebInspector and enable it through the console. + +```js +localStorage.setItem('debug', 'foo*'); +``` + +It triggers on both the `debug` and `diagnostics` storage items. (Please note +that these keys should be entered in lowercase) + +#### AsyncStorage + +This adapter is enabled for `react-native`. + +This adapter uses the `AsyncStorage` API that is exposed by the `react-native` +library to store and read the `debug` or `diagnostics` storage items. + +```js +import { AsyncStorage } from 'react-native'; + +AsyncStorage.setItem('debug', 'foo*'); +``` + +Unlike other adapters, this is the only adapter that is `async` so that means +that we're not able to instantly determine if a created logger should be +enabled or disabled. So when a logger is created in `react-native` we initially +assume it's disabled, any message that send during period will be queued +internally. + +Once we've received the data from the `AsyncStorage` API we will determine +if the logger should be enabled, flush the queued messages if needed and set +all `enabled` properties accordingly on the returned logger. + +### Loggers + +By default it will log all messages to `console.log` in when the logger is +enabled using the debug flag that is set using one of the adapters. + +## License + +[MIT](LICENSE) diff --git a/build/node_modules/@dabh/diagnostics/adapters/hash.js b/build/node_modules/@dabh/diagnostics/adapters/hash.js new file mode 100644 index 00000000..a41aae5c --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/adapters/hash.js @@ -0,0 +1,11 @@ +var adapter = require('./'); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function hash() { + return /(debug|diagnostics)=([^&]+)/i.exec(window.location.hash)[2]; +}); diff --git a/build/node_modules/@dabh/diagnostics/adapters/index.js b/build/node_modules/@dabh/diagnostics/adapters/index.js new file mode 100644 index 00000000..d60aaea5 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/adapters/index.js @@ -0,0 +1,18 @@ +var enabled = require('enabled'); + +/** + * Creates a new Adapter. + * + * @param {Function} fn Function that returns the value. + * @returns {Function} The adapter logic. + * @public + */ +module.exports = function create(fn) { + return function adapter(namespace) { + try { + return enabled(namespace, fn()); + } catch (e) { /* Any failure means that we found nothing */ } + + return false; + }; +} diff --git a/build/node_modules/@dabh/diagnostics/adapters/localstorage.js b/build/node_modules/@dabh/diagnostics/adapters/localstorage.js new file mode 100644 index 00000000..bb889875 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/adapters/localstorage.js @@ -0,0 +1,11 @@ +var adapter = require('./'); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function storage() { + return localStorage.getItem('debug') || localStorage.getItem('diagnostics'); +}); diff --git a/build/node_modules/@dabh/diagnostics/adapters/process.env.js b/build/node_modules/@dabh/diagnostics/adapters/process.env.js new file mode 100644 index 00000000..5ab166a4 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/adapters/process.env.js @@ -0,0 +1,11 @@ +var adapter = require('./'); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function processenv() { + return process.env.DEBUG || process.env.DIAGNOSTICS; +}); diff --git a/build/node_modules/@dabh/diagnostics/browser/development.js b/build/node_modules/@dabh/diagnostics/browser/development.js new file mode 100644 index 00000000..e36dfaa5 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/browser/development.js @@ -0,0 +1,35 @@ +var create = require('../diagnostics'); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = false; + options.dev = true; + + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); + } + + return dev.yep(options); +}); + +// +// Configure the logger for the given environment. +// +diagnostics.modify(require('../modifiers/namespace')); +diagnostics.use(require('../adapters/localstorage')); +diagnostics.use(require('../adapters/hash')); +diagnostics.set(require('../logger/console')); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/build/node_modules/@dabh/diagnostics/browser/index.js b/build/node_modules/@dabh/diagnostics/browser/index.js new file mode 100644 index 00000000..ae0f2f80 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/browser/index.js @@ -0,0 +1,8 @@ +// +// Select the correct build version depending on the environment. +// +if (process.env.NODE_ENV === 'production') { + module.exports = require('./production.js'); +} else { + module.exports = require('./development.js'); +} diff --git a/build/node_modules/@dabh/diagnostics/browser/override.js b/build/node_modules/@dabh/diagnostics/browser/override.js new file mode 100644 index 00000000..8f363772 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/browser/override.js @@ -0,0 +1,6 @@ +var diagnostics = require('./'); + +// +// No way to override `debug` with `diagnostics` in the browser. +// +module.exports = diagnostics; diff --git a/build/node_modules/@dabh/diagnostics/browser/production.js b/build/node_modules/@dabh/diagnostics/browser/production.js new file mode 100644 index 00000000..1a19ce39 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/browser/production.js @@ -0,0 +1,24 @@ +var create = require('../diagnostics'); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function prod(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = true; + options.dev = false; + + if (!(options.force || prod.force)) return prod.nope(options); + return prod.yep(options); +}); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/build/node_modules/@dabh/diagnostics/diagnostics.js b/build/node_modules/@dabh/diagnostics/diagnostics.js new file mode 100644 index 00000000..12dc1f35 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/diagnostics.js @@ -0,0 +1,212 @@ +/** + * Contains all configured adapters for the given environment. + * + * @type {Array} + * @public + */ +var adapters = []; + +/** + * Contains all modifier functions. + * + * @typs {Array} + * @public + */ +var modifiers = []; + +/** + * Our default logger. + * + * @public + */ +var logger = function devnull() {}; + +/** + * Register a new adapter that will used to find environments. + * + * @param {Function} adapter A function that will return the possible env. + * @returns {Boolean} Indication of a successful add. + * @public + */ +function use(adapter) { + if (~adapters.indexOf(adapter)) return false; + + adapters.push(adapter); + return true; +} + +/** + * Assign a new log method. + * + * @param {Function} custom The log method. + * @public + */ +function set(custom) { + logger = custom; +} + +/** + * Check if the namespace is allowed by any of our adapters. + * + * @param {String} namespace The namespace that needs to be enabled + * @returns {Boolean|Promise} Indication if the namespace is enabled by our adapters. + * @public + */ +function enabled(namespace) { + var async = []; + + for (var i = 0; i < adapters.length; i++) { + if (adapters[i].async) { + async.push(adapters[i]); + continue; + } + + if (adapters[i](namespace)) return true; + } + + if (!async.length) return false; + + // + // Now that we know that we Async functions, we know we run in an ES6 + // environment and can use all the API's that they offer, in this case + // we want to return a Promise so that we can `await` in React-Native + // for an async adapter. + // + return new Promise(function pinky(resolve) { + Promise.all( + async.map(function prebind(fn) { + return fn(namespace); + }) + ).then(function resolved(values) { + resolve(values.some(Boolean)); + }); + }); +} + +/** + * Add a new message modifier to the debugger. + * + * @param {Function} fn Modification function. + * @returns {Boolean} Indication of a successful add. + * @public + */ +function modify(fn) { + if (~modifiers.indexOf(fn)) return false; + + modifiers.push(fn); + return true; +} + +/** + * Write data to the supplied logger. + * + * @param {Object} meta Meta information about the log. + * @param {Array} args Arguments for console.log. + * @public + */ +function write() { + logger.apply(logger, arguments); +} + +/** + * Process the message with the modifiers. + * + * @param {Mixed} message The message to be transformed by modifers. + * @returns {String} Transformed message. + * @public + */ +function process(message) { + for (var i = 0; i < modifiers.length; i++) { + message = modifiers[i].apply(modifiers[i], arguments); + } + + return message; +} + +/** + * Introduce options to the logger function. + * + * @param {Function} fn Calback function. + * @param {Object} options Properties to introduce on fn. + * @returns {Function} The passed function + * @public + */ +function introduce(fn, options) { + var has = Object.prototype.hasOwnProperty; + + for (var key in options) { + if (has.call(options, key)) { + fn[key] = options[key]; + } + } + + return fn; +} + +/** + * Nope, we're not allowed to write messages. + * + * @returns {Boolean} false + * @public + */ +function nope(options) { + options.enabled = false; + options.modify = modify; + options.set = set; + options.use = use; + + return introduce(function diagnopes() { + return false; + }, options); +} + +/** + * Yep, we're allowed to write debug messages. + * + * @param {Object} options The options for the process. + * @returns {Function} The function that does the logging. + * @public + */ +function yep(options) { + /** + * The function that receives the actual debug information. + * + * @returns {Boolean} indication that we're logging. + * @public + */ + function diagnostics() { + var args = Array.prototype.slice.call(arguments, 0); + + write.call(write, options, process(args, options)); + return true; + } + + options.enabled = true; + options.modify = modify; + options.set = set; + options.use = use; + + return introduce(diagnostics, options); +} + +/** + * Simple helper function to introduce various of helper methods to our given + * diagnostics function. + * + * @param {Function} diagnostics The diagnostics function. + * @returns {Function} diagnostics + * @public + */ +module.exports = function create(diagnostics) { + diagnostics.introduce = introduce; + diagnostics.enabled = enabled; + diagnostics.process = process; + diagnostics.modify = modify; + diagnostics.write = write; + diagnostics.nope = nope; + diagnostics.yep = yep; + diagnostics.set = set; + diagnostics.use = use; + + return diagnostics; +} diff --git a/build/node_modules/@dabh/diagnostics/example.png b/build/node_modules/@dabh/diagnostics/example.png new file mode 100644 index 00000000..323bc7c4 Binary files /dev/null and b/build/node_modules/@dabh/diagnostics/example.png differ diff --git a/build/node_modules/@dabh/diagnostics/logger/console.js b/build/node_modules/@dabh/diagnostics/logger/console.js new file mode 100644 index 00000000..7423eff9 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/logger/console.js @@ -0,0 +1,19 @@ +/** + * An idiot proof logger to be used as default. We've wrapped it in a try/catch + * statement to ensure the environments without the `console` API do not crash + * as well as an additional fix for ancient browsers like IE8 where the + * `console.log` API doesn't have an `apply`, so we need to use the Function's + * apply functionality to apply the arguments. + * + * @param {Object} meta Options of the logger. + * @param {Array} messages The actuall message that needs to be logged. + * @public + */ +module.exports = function (meta, messages) { + // + // So yea. IE8 doesn't have an apply so we need a work around to puke the + // arguments in place. + // + try { Function.prototype.apply.call(console.log, console, messages); } + catch (e) {} +} diff --git a/build/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js b/build/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js new file mode 100644 index 00000000..e3d1ec69 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js @@ -0,0 +1,20 @@ +var colorspace = require('colorspace'); +var kuler = require('kuler'); + +/** + * Prefix the messages with a colored namespace. + * + * @param {Array} args The messages array that is getting written. + * @param {Object} options Options for diagnostics. + * @returns {Array} Altered messages array. + * @public + */ +module.exports = function ansiModifier(args, options) { + var namespace = options.namespace; + var ansi = options.colors !== false + ? kuler(namespace +':', colorspace(namespace)) + : namespace +':'; + + args[0] = ansi +' '+ args[0]; + return args; +}; diff --git a/build/node_modules/@dabh/diagnostics/modifiers/namespace.js b/build/node_modules/@dabh/diagnostics/modifiers/namespace.js new file mode 100644 index 00000000..ac190773 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/modifiers/namespace.js @@ -0,0 +1,32 @@ +var colorspace = require('colorspace'); + +/** + * Prefix the messages with a colored namespace. + * + * @param {Array} messages The messages array that is getting written. + * @param {Object} options Options for diagnostics. + * @returns {Array} Altered messages array. + * @public + */ +module.exports = function colorNamespace(args, options) { + var namespace = options.namespace; + + if (options.colors === false) { + args[0] = namespace +': '+ args[0]; + return args; + } + + var color = colorspace(namespace); + + // + // The console API supports a special %c formatter in browsers. This is used + // to style console messages with any CSS styling, in our case we want to + // use colorize the namespace for clarity. As these are formatters, and + // we need to inject our CSS string as second messages argument so it + // gets picked up correctly. + // + args[0] = '%c'+ namespace +':%c '+ args[0]; + args.splice(1, 0, 'color:'+ color, 'color:inherit'); + + return args; +}; diff --git a/build/node_modules/@dabh/diagnostics/node/development.js b/build/node_modules/@dabh/diagnostics/node/development.js new file mode 100644 index 00000000..51dc51b6 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/node/development.js @@ -0,0 +1,36 @@ +var create = require('../diagnostics'); +var tty = require('tty').isatty(1); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.colors = 'colors' in options ? options.colors : tty; + options.namespace = namespace; + options.prod = false; + options.dev = true; + + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); + } + + return dev.yep(options); +}); + +// +// Configure the logger for the given environment. +// +diagnostics.modify(require('../modifiers/namespace-ansi')); +diagnostics.use(require('../adapters/process.env')); +diagnostics.set(require('../logger/console')); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/build/node_modules/@dabh/diagnostics/node/index.js b/build/node_modules/@dabh/diagnostics/node/index.js new file mode 100644 index 00000000..ae0f2f80 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/node/index.js @@ -0,0 +1,8 @@ +// +// Select the correct build version depending on the environment. +// +if (process.env.NODE_ENV === 'production') { + module.exports = require('./production.js'); +} else { + module.exports = require('./development.js'); +} diff --git a/build/node_modules/@dabh/diagnostics/node/override.js b/build/node_modules/@dabh/diagnostics/node/override.js new file mode 100644 index 00000000..936e28be --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/node/override.js @@ -0,0 +1,21 @@ +const diagnostics = require('./'); + +// +// Override the existing `debug` call so it will use `diagnostics` instead +// of the `debug` module. +// +try { + var key = require.resolve('debug'); + + require.cache[key] = { + exports: diagnostics, + filename: key, + loaded: true, + id: key + }; +} catch (e) { /* We don't really care if it fails */ } + +// +// Export the default import as exports again. +// +module.exports = diagnostics; diff --git a/build/node_modules/@dabh/diagnostics/node/production.js b/build/node_modules/@dabh/diagnostics/node/production.js new file mode 100644 index 00000000..1a19ce39 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/node/production.js @@ -0,0 +1,24 @@ +var create = require('../diagnostics'); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function prod(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = true; + options.dev = false; + + if (!(options.force || prod.force)) return prod.nope(options); + return prod.yep(options); +}); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; diff --git a/build/node_modules/@dabh/diagnostics/package.json b/build/node_modules/@dabh/diagnostics/package.json new file mode 100644 index 00000000..62ceb860 --- /dev/null +++ b/build/node_modules/@dabh/diagnostics/package.json @@ -0,0 +1,101 @@ +{ + "_from": "@dabh/diagnostics@^2.0.2", + "_id": "@dabh/diagnostics@2.0.2", + "_inBundle": false, + "_integrity": "sha512-+A1YivoVDNNVCdfozHSR8v/jyuuLTMXwjWuxPFlFlUapXoGc+Gj9mDlTDDfrwl7rXCl2tNZ0kE8sIBO6YOn96Q==", + "_location": "/@dabh/diagnostics", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@dabh/diagnostics@^2.0.2", + "name": "@dabh/diagnostics", + "escapedName": "@dabh%2fdiagnostics", + "scope": "@dabh", + "rawSpec": "^2.0.2", + "saveSpec": null, + "fetchSpec": "^2.0.2" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.2.tgz", + "_shasum": "290d08f7b381b8f94607dc8f471a12c675f9db31", + "_spec": "@dabh/diagnostics@^2.0.2", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Arnout Kazemier" + }, + "browser": "./browser", + "bugs": { + "url": "https://github.com/3rd-Eden/diagnostics/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Martijn Swaagman", + "url": "https://github.com/swaagie" + }, + { + "name": "Jarrett Cruger", + "url": "https://github.com/jcrugzz" + }, + { + "name": "Sevastos", + "url": "https://github.com/sevastos" + } + ], + "dependencies": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + }, + "deprecated": false, + "description": "Tools for debugging your node.js modules and event loop", + "devDependencies": { + "assume": "2.1.x", + "asyncstorageapi": "^1.0.2", + "mocha": "5.2.x", + "nyc": "^14.1.1", + "objstorage": "^1.0.0", + "pre-commit": "1.2.x", + "require-poisoning": "^2.0.0", + "webpack": "^4.29.5", + "webpack-bundle-size-analyzer": "^3.0.0", + "webpack-cli": "^3.2.3" + }, + "directories": { + "test": "test" + }, + "homepage": "https://github.com/3rd-Eden/diagnostics", + "keywords": [ + "debug", + "debugger", + "debugging", + "diagnostic", + "diagnostics", + "event", + "loop", + "metrics", + "stats" + ], + "license": "MIT", + "main": "./node", + "name": "@dabh/diagnostics", + "repository": { + "type": "git", + "url": "git://github.com/3rd-Eden/diagnostics.git" + }, + "scripts": { + "test": "nyc --reporter=text --reporter=lcov npm run test:runner", + "test:basic": "mocha --require test/mock.js test/*.test.js", + "test:browser": "mocha --require test/mock test/browser.js", + "test:node": "mocha --require test/mock test/node.js", + "test:runner": "npm run test:basic && npm run test:node && npm run test:browser", + "webpack:browser:dev": "webpack --mode=development browser/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "webpack:browser:prod": "webpack --mode=production browser/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "webpack:node:dev": "webpack --mode=development node/index.js -o /dev/null --json | webpack-bundle-size-analyzer", + "webpack:node:prod": "webpack --mode=production node/index.js -o /dev/null --json | webpack-bundle-size-analyzer" + }, + "version": "2.0.2" +} diff --git a/build/node_modules/async/CHANGELOG.md b/build/node_modules/async/CHANGELOG.md new file mode 100644 index 00000000..32dca5ce --- /dev/null +++ b/build/node_modules/async/CHANGELOG.md @@ -0,0 +1,331 @@ +# v3.2.0 +- Fix a bug in Safari related to overwriting `func.name` +- Remove built-in browserify configuration (#1653) +- Varios doc fixes (#1688, #1703, #1704) + +# v3.1.1 +- Allow redefining `name` property on wrapped functions. + +# v3.1.0 + +- Added `q.pushAsync` and `q.unshiftAsync`, analagous to `q.push` and `q.unshift`, except they always do not accept a callback, and reject if processing the task errors. (#1659) +- Promises returned from `q.push` and `q.unshift` when a callback is not passed now resolve even if an error ocurred. (#1659) +- Fixed a parsing bug in `autoInject` with complicated function bodies (#1663) +- Added ES6+ configuration for Browserify bundlers (#1653) +- Various doc fixes (#1664, #1658, #1665, #1652) + +# v3.0.1 + +## Bug fixes +- Fixed a regression where arrays passed to `queue` and `cargo` would be completely flattened. (#1645) +- Clarified Async's browser support (#1643) + + +# v3.0.0 + +The `async`/`await` release! + +There are a lot of new features and subtle breaking changes in this major version, but the biggest feature is that most Async methods return a Promise if you omit the callback, meaning you can `await` them from within an `async` function. + +```js +const results = await async.mapLimit(urls, 5, async url => { + const resp = await fetch(url) + return resp.body +}) +``` + +## Breaking Changes +- Most Async methods return a Promise when the final callback is omitted, making them `await`-able! (#1572) +- We are now making heavy use of ES2015 features, this means we have dropped out-of-the-box support for Node 4 and earlier, and many old versions of browsers. (#1541, #1553) +- In `queue`, `priorityQueue`, `cargo` and `cargoQueue`, the "event"-style methods, like `q.drain` and `q.saturated` are now methods that register a callback, rather than properties you assign a callback to. They are now of the form `q.drain(callback)`. If you do not pass a callback a Promise will be returned for the next occurrence of the event, making them `await`-able, e.g. `await q.drain()`. (#1586, #1641) +- Calling `callback(false)` will cancel an async method, preventing further iteration and callback calls. This is useful for preventing memory leaks when you break out of an async flow by calling an outer callback. (#1064, #1542) +- `during` and `doDuring` have been removed, and instead `whilst`, `doWhilst`, `until` and `doUntil` now have asynchronous `test` functions. (#850, #1557) +- `limits` of less than 1 now cause an error to be thrown in queues and collection methods. (#1249, #1552) +- `memoize` no longer memoizes errors (#1465, #1466) +- `applyEach`/`applyEachSeries` have a simpler interface, to make them more easily type-able. It always returns a function that takes in a single callback argument. If that callback is omitted, a promise is returned, making it awaitable. (#1228, #1640) + +## New Features +- Async generators are now supported in all the Collection methods. (#1560) +- Added `cargoQueue`, a queue with both `concurrency` and `payload` size parameters. (#1567) +- Queue objects returned from `queue` now have a `Symbol.iterator` method, meaning they can be iterated over to inspect the current list of items in the queue. (#1459, #1556) +- A ESM-flavored `async.mjs` is included in the `async` package. This is described in the `package.json` `"module"` field, meaning it should be automatically used by Webpack and other compatible bundlers. + +## Bug fixes +- Better handle arbitrary error objects in `asyncify` (#1568, #1569) + +## Other +- Removed Lodash as a dependency (#1283, #1528) +- Miscellaneous docs fixes (#1393, #1501, #1540, #1543, #1558, #1563, #1564, #1579, #1581) +- Miscellaneous test fixes (#1538) + +------- + +# v2.6.1 +- Updated lodash to prevent `npm audit` warnings. (#1532, #1533) +- Made `async-es` more optimized for webpack users (#1517) +- Fixed a stack overflow with large collections and a synchronous iterator (#1514) +- Various small fixes/chores (#1505, #1511, #1527, #1530) + +# v2.6.0 +- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) +- Improved `queue` performance. (#1448, #1454) +- Add missing sourcemap (#1452, #1453) +- Various doc updates (#1448, #1471, #1483) + +# v2.5.0 +- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) +- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) +- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) +- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) + +# v2.4.1 +- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) + +# v2.4.0 +- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) +- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) +- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) +- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) +- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) +- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) +- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) + +# v2.3.0 +- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) +- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) + +# v2.2.0 +- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) +- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) +- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) + +# v2.1.5 +- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) +- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) +- Avoid stack overflow case in queue +- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. +- Cleanup implementations of `some`, `every` and `find` + +# v2.1.3 +- Make bundle size smaller +- Create optimized hotpath for `filter` in array case. + +# v2.1.2 +- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). + +# v2.1.0 + +- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) +- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) +- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) +- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) +- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) + +# v2.0.1 + +- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). + +# v2.0.0 + +Lots of changes here! + +First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. + +The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. + +We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. + +Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. + +Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: + +1. Takes a variable number of arguments +2. The last argument is always a callback +3. The callback can accept any number of arguments +4. The first argument passed to the callback will be treated as an error result, if the argument is truthy +5. Any number of result arguments can be passed after the "error" argument +6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. + +There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, `filter`, `reject` and `detect`. + +Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. + +Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). + +## New Features + +- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) +- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) +- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) +- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) +- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) +- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) +- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). +- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) +- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) +- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) +- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) +- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). +- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) +- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) +- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) + +## Breaking changes + +- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) +- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) +- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) +- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- `filter`, `reject`, `some`, `every`, `detect` and their families like `{METHOD}Series` and `{METHOD}Limit` now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) +- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) +- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) +- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) +- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). +- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) +- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) +- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) + +## Bug Fixes + +- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). +- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). +- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). + +## Other + +- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. +- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). +- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) + +Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. + +------------------------------------------ + +# v1.5.2 +- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) +- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) +- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) +- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) +- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) +- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) +- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) +- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) +- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) +- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) +- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) + +# v1.4.2 + +- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) + +# v1.4.1 + +- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) +- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) +- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) + +# v1.4.0 + +- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) +- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) +- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers +- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) +- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) +- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) +- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) +- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) +- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769)) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)). +- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) +- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) +- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) +- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) +- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) +- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) +- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766)) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) +- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) +- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) +- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) +- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) +- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) +- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) +- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/build/node_modules/async/LICENSE b/build/node_modules/async/LICENSE new file mode 100644 index 00000000..b18aed69 --- /dev/null +++ b/build/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2018 Caolan McMahon + +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. diff --git a/build/node_modules/async/README.md b/build/node_modules/async/README.md new file mode 100644 index 00000000..c679263b --- /dev/null +++ b/build/node_modules/async/README.md @@ -0,0 +1,60 @@ +![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg) + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) +[![Build Status via Azure Pipelines](https://dev.azure.com/caolanmcmahon/async/_apis/build/status/caolan.async?branchName=master)](https://dev.azure.com/caolanmcmahon/async/_build/latest?definitionId=1&branchName=master) +[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async) + + + +Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/v3/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm i async`, it can also be used directly in the browser. A ESM/MJS version is included in the main `async` package that should automatically be used with compatible bundlers such as Webpack and Rollup. + +A pure ESM version of Async is available as [`async-es`](https://www.npmjs.com/package/async-es). + +For Documentation, visit + +*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* + + +```javascript +// for use with Node-style callbacks... +var async = require("async"); + +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, (value, key, callback) => { + fs.readFile(__dirname + value, "utf8", (err, data) => { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }); +}, err => { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}); +``` + +```javascript +var async = require("async"); + +// ...or ES2017 async functions +async.mapLimit(urls, 5, async function(url) { + const response = await fetch(url) + return response.body +}, (err, results) => { + if (err) throw err + // results is now an array of the response bodies + console.log(results) +}) +``` diff --git a/build/node_modules/async/all.js b/build/node_modules/async/all.js new file mode 100644 index 00000000..1c2e5360 --- /dev/null +++ b/build/node_modules/async/all.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/allLimit.js b/build/node_modules/async/allLimit.js new file mode 100644 index 00000000..bb78378d --- /dev/null +++ b/build/node_modules/async/allLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/allSeries.js b/build/node_modules/async/allSeries.js new file mode 100644 index 00000000..76eeaf7e --- /dev/null +++ b/build/node_modules/async/allSeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/any.js b/build/node_modules/async/any.js new file mode 100644 index 00000000..0e987a16 --- /dev/null +++ b/build/node_modules/async/any.js @@ -0,0 +1,56 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/anyLimit.js b/build/node_modules/async/anyLimit.js new file mode 100644 index 00000000..22b60dbb --- /dev/null +++ b/build/node_modules/async/anyLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/anySeries.js b/build/node_modules/async/anySeries.js new file mode 100644 index 00000000..7f7f801f --- /dev/null +++ b/build/node_modules/async/anySeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/apply.js b/build/node_modules/async/apply.js new file mode 100644 index 00000000..5246833a --- /dev/null +++ b/build/node_modules/async/apply.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn, ...args) { + return (...callArgs) => fn(...args, ...callArgs); +}; + +module.exports = exports["default"]; /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ \ No newline at end of file diff --git a/build/node_modules/async/applyEach.js b/build/node_modules/async/applyEach.js new file mode 100644 index 00000000..2ecefc18 --- /dev/null +++ b/build/node_modules/async/applyEach.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +exports.default = (0, _applyEach2.default)(_map2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/applyEachSeries.js b/build/node_modules/async/applyEachSeries.js new file mode 100644 index 00000000..c9d56464 --- /dev/null +++ b/build/node_modules/async/applyEachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +exports.default = (0, _applyEach2.default)(_mapSeries2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/asyncify.js b/build/node_modules/async/asyncify.js new file mode 100644 index 00000000..23623175 --- /dev/null +++ b/build/node_modules/async/asyncify.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/auto.js b/build/node_modules/async/auto.js new file mode 100644 index 00000000..f15f0bdf --- /dev/null +++ b/build/node_modules/async/auto.js @@ -0,0 +1,267 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = auto; + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return; + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = (0, _onlyOnce2.default)((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return; + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return; + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/autoInject.js b/build/node_modules/async/autoInject.js new file mode 100644 index 00000000..80125ab8 --- /dev/null +++ b/build/node_modules/async/autoInject.js @@ -0,0 +1,156 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = autoInject; + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + +function parseParams(func) { + const src = func.toString().replace(STRIP_COMMENTS, ''); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src); + let [, args] = match; + return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + (0, _wrapAsync2.default)(taskFn)(...newArgs); + } + }); + + return (0, _auto2.default)(newTasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/bower.json b/build/node_modules/async/bower.json new file mode 100644 index 00000000..390c6502 --- /dev/null +++ b/build/node_modules/async/bower.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "main": "dist/async.js", + "ignore": [ + "bower_components", + "lib", + "test", + "node_modules", + "perf", + "support", + "**/.*", + "*.config.js", + "*.json", + "index.js", + "Makefile" + ] +} diff --git a/build/node_modules/async/cargo.js b/build/node_modules/async/cargo.js new file mode 100644 index 00000000..bfb17579 --- /dev/null +++ b/build/node_modules/async/cargo.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = cargo; + +var _queue = require('./internal/queue'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/concatSeries.js b/build/node_modules/async/concatSeries.js new file mode 100644 index 00000000..fbc105b9 --- /dev/null +++ b/build/node_modules/async/concatSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/constant.js b/build/node_modules/async/constant.js new file mode 100644 index 00000000..07596538 --- /dev/null +++ b/build/node_modules/async/constant.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (...args) { + return function (...ignoredArgs /*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +}; + +module.exports = exports["default"]; /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ \ No newline at end of file diff --git a/build/node_modules/async/detect.js b/build/node_modules/async/detect.js new file mode 100644 index 00000000..1066b9e8 --- /dev/null +++ b/build/node_modules/async/detect.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/detectLimit.js b/build/node_modules/async/detectLimit.js new file mode 100644 index 00000000..9e2d3a0d --- /dev/null +++ b/build/node_modules/async/detectLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/detectSeries.js b/build/node_modules/async/detectSeries.js new file mode 100644 index 00000000..cdf38b1d --- /dev/null +++ b/build/node_modules/async/detectSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/dir.js b/build/node_modules/async/dir.js new file mode 100644 index 00000000..85fbcced --- /dev/null +++ b/build/node_modules/async/dir.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +exports.default = (0, _consoleFunc2.default)('dir'); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/dist/async.js b/build/node_modules/async/dist/async.js new file mode 100644 index 00000000..57e9478f --- /dev/null +++ b/build/node_modules/async/dist/async.js @@ -0,0 +1,4846 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.async = {}))); +}(this, (function (exports) { 'use strict'; + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } + + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } + + /* istanbul ignore file */ + + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + + function fallback(fn) { + setTimeout(fn, 0); + } + + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } + + var _defer; + + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback; + } + + var setImmediate$1 = wrap(_defer); + + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } + + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } + + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } + + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } + + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } + + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } + + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable + } + + function applyEach (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } + + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } + + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } + + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } + + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? {value: obj[key], key} : null; + }; + } + + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } + + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); + } + + var eachOfLimit = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; + }; + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } + + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); + } + + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); + + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach$1 = applyEach(map$1); + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach(mapSeries$1); + + const PROMISE_SYMBOL = Symbol('promiseCallback'); + + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback + } + + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] + } + + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + + function parseParams(func) { + const src = func.toString().replace(STRIP_COMMENTS, ''); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } + + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); + } + + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } + + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } + + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = { + data, + callback: rejectOnError ? + promiseCallback : + (callback || promiseCallback) + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } + + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); + + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; + } + + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } + + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); + + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } + + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } + + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + resultArgs.forEach(x => console[name](x)); + } + } + }) + } + + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); + + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); + } + + var doWhilst$1 = awaitify(doWhilst, 3); + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ + function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$2 = awaitify(eachLimit$1, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } + + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); + + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } + + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } + + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); + } + + var groupByLimit$1 = awaitify(groupByLimit, 4); + + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer$1; + + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else { + _defer$1 = fallback; + } + + var nextTick = wrap(_defer$1); + + var parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); + + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + function parallel$1(tasks, callback) { + return parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return parallel(eachOfLimit(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue$1 (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } + + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } + } + + function leftChi(i) { + return (i<<1)+1; + } + + function parent(i) { + return ((i+1)>>1)-1; + } + + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } + + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + q._tasks = new Heap(); + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback = () => {}) { + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!Array.isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(() => q.drain()); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority, + callback + }; + + q._tasks.push(item); + } + + setImmediate$1(q.process); + }; + + // Remove unshift function + delete q.unshift; + + return q; + } + + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } + + function reject(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ + function reject$1 (coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback) + } + var reject$2 = awaitify(reject$1, 3); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant$1(value) { + return function () { + return value; + } + } + + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; + + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] + } + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); + } + + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ + function series(tasks, callback) { + return parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); + + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); + + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } + + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } + + var tryEach$1 = awaitify(tryEach); + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); + + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(page, cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + var index = { + apply, + applyEach: applyEach$1, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo, + cargoQueue: cargo$1, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel: parallel$1, + parallelLimit, + priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.default = index; + exports.apply = apply; + exports.applyEach = applyEach$1; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.cargoQueue = cargo$1; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.each = each; + exports.eachLimit = eachLimit$2; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$2; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel$1; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$2; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.forEach = each; + exports.forEachSeries = eachSeries$1; + exports.forEachLimit = eachLimit$2; + exports.forEachOf = eachOf$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachOfLimit = eachOfLimit$2; + exports.inject = reduce$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.wrapSync = asyncify; + exports.during = whilst$1; + exports.doDuring = doWhilst$1; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/build/node_modules/async/dist/async.min.js b/build/node_modules/async/dist/async.min.js new file mode 100644 index 00000000..b247c3e5 --- /dev/null +++ b/build/node_modules/async/dist/async.min.js @@ -0,0 +1 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.async={})})(this,function(e){'use strict';function t(e,...t){return(...a)=>e(...t,...a)}function a(e){return function(...t){var a=t.pop();return e.call(this,t,a)}}function n(e){setTimeout(e,0)}function i(e){return(t,...a)=>e(()=>t(...a))}function r(e){return u(e)?function(...t){const a=t.pop(),n=e.apply(this,t);return s(n,a)}:a(function(t,a){var n;try{n=e.apply(this,t)}catch(t){return a(t)}return n&&"function"==typeof n.then?s(n,a):void a(null,n)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&e.message?e:new Error(e))})}function l(e,t,a){try{e(t,a)}catch(e){Ee(t=>{throw t},e)}}function u(e){return"AsyncFunction"===e[Symbol.toStringTag]}function c(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function p(e){return"function"==typeof e[Symbol.asyncIterator]}function d(e){if("function"!=typeof e)throw new Error("expected a function");return u(e)?r(e):e}function o(e,t=e.length){if(!t)throw new Error("arity is undefined");return function(...a){return"function"==typeof a[t-1]?e.apply(this,a):new Promise((n,i)=>{a[t-1]=(e,...t)=>e?i(e):void n(1{d(e).apply(i,a.concat(t))},n)});return n}}function f(e,t,a,n){t=t||[];var i=[],r=0,s=d(a);return e(t,(e,t,a)=>{var n=r++;s(e,(e,t)=>{i[n]=t,a(e)})},e=>{n(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var a=e;e=null,a.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,a=e.length;return function(){return++t=t||c||l||(c=!0,e.next().then(({value:e,done:t})=>{if(!(u||l))return c=!1,t?(l=!0,void(0>=p&&n(null))):void(p++,a(e,d,r),d++,i())}).catch(s))}function r(e,t){return p-=1,u?void 0:e?s(e):!1===e?(l=!0,void(u=!0)):t===be||l&&0>=p?(l=!0,n(null)):void i()}function s(e){u||(c=!1,l=!0,n(e))}let l=!1,u=!1,c=!1,p=0,d=0;i()}function b(e,t,a){function n(e,t){!1===e&&(l=!0);!0===l||(e?a(e):(++r===s||t===be)&&a(null))}a=m(a);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&a(null);i{t=e,a=n}),e}function M(e,t,a){function n(e,t){g.push(()=>l(e,t))}function i(){if(!h){if(0===g.length&&0===o)return a(null,p);for(;g.length&&oe()),i()}function l(e,t){if(!f){var n=x((t,...n)=>{if(o--,!1===t)return void(h=!0);if(2>n.length&&([n]=n),t){var i={};if(Object.keys(p).forEach(e=>{i[e]=p[e]}),i[e]=n,f=!0,y=Object.create(null),h)return;a(t,i)}else p[e]=n,s(e)});o++;var i=d(t[t.length-1]);1{const i=e[n];Array.isArray(i)&&0<=i.indexOf(t)&&a.push(n)}),a}"number"!=typeof t&&(a=t,t=null),a=m(a||_());var c=Object.keys(e).length;if(!c)return a(null);t||(t=c);var p={},o=0,h=!1,f=!1,y=Object.create(null),g=[],k=[],v={};return Object.keys(e).forEach(t=>{var a=e[t];if(!Array.isArray(a))return n(t,[a]),void k.push(t);var i=a.slice(0,a.length-1),s=i.length;return 0===s?(n(t,a),void k.push(t)):void(v[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&n(t,a)})}))}),function(){for(var e,t=0;k.length;)e=k.pop(),t++,u(e).forEach(e=>{0==--v[e]&&k.push(e)});if(t!==c)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),i(),a[Fe]}function A(e){const t=e.toString().replace(ze,"");let a=t.match(Te);if(a||(a=t.match(Ce)),!a)throw new Error("could not parse args in autoInject\nSource:\n"+t);let[,n]=a;return n.replace(/\s/g,"").split(Pe).map(e=>e.replace(Re,"").trim())}function I(e,t){var a={};return Object.keys(e).forEach(t=>{function n(e,t){var a=i.map(t=>e[t]);a.push(t),d(r)(...a)}var i,r=e[t],s=u(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),a[t]=i.concat(0{r(e,a),t(...n)};f[e].push(a)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,a,n){function i(e,...t){return e?a?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=n&&"function"!=typeof n)throw new Error("task callback must be a function");k.started=!0;var r,s,l={data:e,callback:a?i:n||i};if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,Ee(()=>{y=!1,k.process()})),a||!n)return new Promise((e,t)=>{r=e,s=t})}function u(e){return function(t,...a){o-=1;for(var n=0,r=e.length;ns("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var p=d(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),n(e,t)):new Promise((t,a)=>{i(e,(e,n)=>e?a(e):void t(n))});var g=!1,k={_tasks:new Ne,*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:a,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?c(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?c(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?c(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?c(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o{t.apply(a,e.concat((e,...t)=>{n(e,t)}))},(e,t)=>n(e,...t)),n[Fe]}}function C(...e){return T(...e.reverse())}function P(...e){return function(...t){var a=t.pop();return a(null,...e)}}function R(e,t){return(a,n,i,r)=>{var s,l=!1;const u=d(i);a(n,(a,n,i)=>{u(a,(n,r)=>n||!1===n?i(n):e(r)&&!s?(l=!0,s=t(!0,a),i(null,be)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function z(e){return(t,...a)=>d(t)(...a,(t,...a)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&a.forEach(t=>console[e](t)))})}function N(e,t,a){const n=d(t);return Ke(e,(...e)=>{const t=e.pop();n(...e,(e,a)=>t(e,!a))},a)}function V(e){return(t,a,n)=>e(t,n)}function Y(e){return u(e)?e:function(...t){var a=t.pop(),n=!0;t.push((...e)=>{n?Ee(()=>a(...e)):a(...e)}),e.apply(this,t),n=!1}}function q(e,t,a,n){var r=Array(t.length);e(t,(e,t,n)=>{a(e,(e,a)=>{r[t]=!!a,n(e)})},e=>{if(e)return n(e);for(var a=[],s=0;s{a(e,(a,r)=>a?n(a):void(r&&i.push({index:t,value:e}),n(a)))},e=>e?n(e):void n(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function Q(e,t,a,n){var i=y(t)?q:D;return i(e,t,d(a),n)}function U(e,t,a){return lt(e,1/0,t,a)}function G(e,t,a){return lt(e,1,t,a)}function W(e,t,a){return ct(e,1/0,t,a)}function H(e,t,a){return ct(e,1,t,a)}function J(e,t=e=>e){var n=Object.create(null),r=Object.create(null),s=d(e),l=a((e,a)=>{var u=t(...e);u in n?Ee(()=>a(null,...n[u])):u in r?r[u].push(a):(r[u]=[a],s(...e,(e,...t)=>{e||(n[u]=t);var a=r[u];delete r[u];for(var s=0,c=a.length;s{a(e[0],t)},t,1)}function $(e){return(e<<1)+1}function ee(e){return(e+1>>1)-1}function te(e,t){return e.priority===t.priority?e.pushCount{}){if("function"!=typeof n)throw new Error("task callback must be a function");if(a.started=!0,Array.isArray(e)||(e=[e]),0===e.length&&a.idle())return Ee(()=>a.drain());for(var r,s=0,u=e.length;s{let n={};if(e&&(n.error=e),0=t.length&&([i]=t),n.value=i}a(null,n)}),t.apply(this,e)})}function re(e){var t;return Array.isArray(e)?t=e.map(ie):(t={},Object.keys(e).forEach(a=>{t[a]=ie.call(this,e[a])})),t}function se(e,t,a,n){const i=d(a);return Q(e,t,(e,t)=>{i(e,(e,a)=>{t(e,!a)})},n)}function le(e){return function(){return e}}function ue(e,t,a){function n(){r((e,...t)=>{!1===e||(e&&s++arguments.length&&"function"==typeof e?(a=t||_(),t=e):(ce(i,e),a=a||_()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=d(t),s=1;return n(),a[Fe]}function ce(e,a){if("object"==typeof a)e.times=+a.times||gt,e.intervalFunc="function"==typeof a.interval?a.interval:le(+a.interval||kt),e.errorFilter=a.errorFilter;else if("number"==typeof a||"string"==typeof a)e.times=+a||gt;else throw new Error("Invalid arguments for async.retry")}function pe(e,t){t||(t=e,e=null);let n=e&&e.arity||t.length;u(t)&&(n+=1);var i=d(t);return a((t,a)=>{function r(e){i(...t,e)}return(t.length{var s,l=!1;a.push((...e)=>{l||(r(...e),clearTimeout(s))}),s=setTimeout(function(){var t=e.name||"anonymous",a=new Error("Callback function \""+t+"\" timed out.");a.code="ETIMEDOUT",n&&(a.info=n),l=!0,r(a)},t),i(...a)})}function he(e){for(var t=Array(e);e--;)t[e]=e;return t}function fe(e,t,a,n){var i=d(a);return qe(he(e),t,i,n)}function ye(e,t,a){return fe(e,1/0,t,a)}function me(e,t,a){return fe(e,1,t,a)}function ge(e,t,a,n){3>=arguments.length&&"function"==typeof t&&(n=a,a=t,t=Array.isArray(e)?[]:{}),n=m(n||_());var i=d(a);return Me(e,(e,a,n)=>{i(t,e,a,n)},e=>n(e,t)),n[Fe]}function ke(e){return(...t)=>(e.unmemoized||e)(...t)}function ve(e,t,a){const n=d(e);return bt(e=>n((t,a)=>e(t,!a)),t,a)}var Se,Le="function"==typeof setImmediate&&setImmediate,xe="object"==typeof process&&"function"==typeof process.nextTick;Se=Le?setImmediate:xe?process.nextTick:n;var Ee=i(Se);const be={};var Oe=e=>(t,a,n)=>{function i(e,t){if(!u)if(d-=1,e)l=!0,n(e);else if(!1===e)l=!0,u=!0;else{if(t===be||l&&0>=d)return l=!0,n(null);o||r()}}function r(){for(o=!0;d=d&&n(null));d+=1,a(t.value,t.key,x(i))}o=!1}if(n=m(n),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return n(null);if(c(t))return E(t,e,a,n);if(p(t))return E(t[Symbol.asyncIterator](),e,a,n);var s=L(t),l=!1,u=!1,d=0,o=!1;r()},_e=o(function(e,t,a,n){return Oe(t)(e,d(a),n)},4),Me=o(function(e,t,a){var n=y(e)?b:O;return n(e,d(t),a)},3),Ae=o(function(e,t,a){return f(Me,e,t,a)},3),Ie=h(Ae),je=o(function(e,t,a){return _e(e,1,t,a)},3),we=o(function(e,t,a){return f(je,e,t,a)},3),Be=h(we);const Fe=Symbol("promiseCallback");var Te=/^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/,Ce=/^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/,Pe=/,/,Re=/(=.+)?(\s*)$/,ze=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;class Ne{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):j(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):j(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:a}=t;e(t)&&this.removeLink(t),t=a}return this}}var Ve,Ye=o(function(e,t,a,n){n=m(n);var r=d(a);return je(e,(e,a,n)=>{r(t,e,(e,a)=>{t=a,n(e)})},e=>n(e,t))},4),qe=o(function(e,t,a,n){return f(Oe(t),e,a,n)},4),De=o(function(e,t,a,n){var i=d(a);return qe(e,t,(e,t)=>{i(e,(e,...a)=>e?t(e):t(e,a))},(e,t)=>{for(var a=[],r=0;re,(e,t)=>t)(Me,e,t,a)},3),We=o(function(e,t,a,n){return R(e=>e,(e,t)=>t)(Oe(t),e,a,n)},4),He=o(function(e,t,a){return R(e=>e,(e,t)=>t)(Oe(1),e,t,a)},3),Je=z("dir"),Ke=o(function(e,t,a){function n(e,...t){return e?a(e):void(!1===e||(r=t,l(...t,i)))}function i(e,t){return e?a(e):!1===e?void 0:t?void s(n):a(null,...r)}a=x(a);var r,s=d(e),l=d(t);return i(null,!0)},3),Xe=o(function(e,t,a){return Me(e,V(d(t)),a)},3),Ze=o(function(e,t,a,n){return Oe(t)(e,V(d(a)),n)},4),$e=o(function(e,t,a){return Ze(e,1,t,a)},3),et=o(function(e,t,a){return R(e=>!e,e=>!e)(Me,e,t,a)},3),tt=o(function(e,t,a,n){return R(e=>!e,e=>!e)(Oe(t),e,a,n)},4),at=o(function(e,t,a){return R(e=>!e,e=>!e)(je,e,t,a)},3),nt=o(function(e,t,a){return Q(Me,e,t,a)},3),it=o(function(e,t,a,n){return Q(Oe(t),e,a,n)},4),rt=o(function(e,t,a){return Q(je,e,t,a)},3),st=o(function(e,t){function a(e){return e?n(e):void(!1===e||i(a))}var n=x(t),i=d(Y(e));return a()},2),lt=o(function(e,t,a,n){var i=d(a);return qe(e,t,(e,t)=>{i(e,(a,n)=>a?t(a):t(a,{key:n,val:e}))},(e,t)=>{for(var a={},{hasOwnProperty:r}=Object.prototype,s=0;s{r(e,t,(e,n)=>e?a(e):void(i[t]=n,a(e)))},e=>n(e,i))},4);Ve=xe?process.nextTick:Le?setImmediate:n;var pt=i(Ve),dt=o((e,t,a)=>{var n=y(t)?[]:{};e(t,(e,t,a)=>{d(e)((e,...i)=>{2>i.length&&([i]=i),n[t]=i,a(e)})},e=>a(e,n))},3);class ot{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let a;0e)(Me,e,t,a)},3),St=o(function(e,t,a,n){return R(Boolean,e=>e)(Oe(t),e,a,n)},4),Lt=o(function(e,t,a){return R(Boolean,e=>e)(je,e,t,a)},3),xt=o(function(e,t,a){function n(e,t){var n=e.criteria,a=t.criteria;return na?1:0}var i=d(t);return Ae(e,(e,t)=>{i(e,(a,n)=>a?t(a):void t(a,{value:e,criteria:n}))},(e,t)=>e?a(e):void a(null,t.sort(n).map(e=>e.value)))},3),Et=o(function(e,t){var a,n=null;return $e(e,(e,t)=>{d(e)((e,...i)=>!1===e?t(e):void(2>i.length?[a]=i:a=i,n=e,t(e?null:{})))},()=>t(n,a))}),bt=o(function(e,t,a){function n(e,...t){if(e)return a(e);l=t;!1===e||s(i)}function i(e,t){return e?a(e):!1===e?void 0:t?void r(n):a(null,...l)}a=x(a);var r=d(t),s=d(e),l=[];return s(i)},3),Ot=o(function(e,t){function a(t){var a=d(e[i++]);a(...t,x(n))}function n(n,...r){return!1===n?void 0:n||i===e.length?t(n,...r):void a(r)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var i=0;a([])});e.default={apply:t,applyEach:Ie,applyEachSeries:Be,asyncify:r,auto:M,autoInject:I,cargo:B,cargoQueue:F,compose:C,concat:Qe,concatLimit:De,concatSeries:Ue,constant:P,detect:Ge,detectLimit:We,detectSeries:He,dir:Je,doUntil:N,doWhilst:Ke,each:Xe,eachLimit:Ze,eachOf:Me,eachOfLimit:_e,eachOfSeries:je,eachSeries:$e,ensureAsync:Y,every:et,everyLimit:tt,everySeries:at,filter:nt,filterLimit:it,filterSeries:rt,forever:st,groupBy:U,groupByLimit:lt,groupBySeries:G,log:ut,map:Ae,mapLimit:qe,mapSeries:we,mapValues:W,mapValuesLimit:ct,mapValuesSeries:H,memoize:J,nextTick:pt,parallel:K,parallelLimit:X,priorityQueue:ae,queue:Z,race:ht,reduce:Ye,reduceRight:ne,reflect:ie,reflectAll:re,reject:ft,rejectLimit:yt,rejectSeries:mt,retry:ue,retryable:pe,seq:T,series:de,setImmediate:Ee,some:vt,someLimit:St,someSeries:Lt,sortBy:xt,timeout:oe,times:ye,timesLimit:fe,timesSeries:me,transform:ge,tryEach:Et,unmemoize:ke,until:ve,waterfall:Ot,whilst:bt,all:et,allLimit:tt,allSeries:at,any:vt,anyLimit:St,anySeries:Lt,find:Ge,findLimit:We,findSeries:He,flatMap:Qe,flatMapLimit:De,flatMapSeries:Ue,forEach:Xe,forEachSeries:$e,forEachLimit:Ze,forEachOf:Me,forEachOfSeries:je,forEachOfLimit:_e,inject:Ye,foldl:Ye,foldr:ne,select:nt,selectLimit:it,selectSeries:rt,wrapSync:r,during:bt,doDuring:Ke},e.apply=t,e.applyEach=Ie,e.applyEachSeries=Be,e.asyncify=r,e.auto=M,e.autoInject=I,e.cargo=B,e.cargoQueue=F,e.compose=C,e.concat=Qe,e.concatLimit=De,e.concatSeries=Ue,e.constant=P,e.detect=Ge,e.detectLimit=We,e.detectSeries=He,e.dir=Je,e.doUntil=N,e.doWhilst=Ke,e.each=Xe,e.eachLimit=Ze,e.eachOf=Me,e.eachOfLimit=_e,e.eachOfSeries=je,e.eachSeries=$e,e.ensureAsync=Y,e.every=et,e.everyLimit=tt,e.everySeries=at,e.filter=nt,e.filterLimit=it,e.filterSeries=rt,e.forever=st,e.groupBy=U,e.groupByLimit=lt,e.groupBySeries=G,e.log=ut,e.map=Ae,e.mapLimit=qe,e.mapSeries=we,e.mapValues=W,e.mapValuesLimit=ct,e.mapValuesSeries=H,e.memoize=J,e.nextTick=pt,e.parallel=K,e.parallelLimit=X,e.priorityQueue=ae,e.queue=Z,e.race=ht,e.reduce=Ye,e.reduceRight=ne,e.reflect=ie,e.reflectAll=re,e.reject=ft,e.rejectLimit=yt,e.rejectSeries=mt,e.retry=ue,e.retryable=pe,e.seq=T,e.series=de,e.setImmediate=Ee,e.some=vt,e.someLimit=St,e.someSeries=Lt,e.sortBy=xt,e.timeout=oe,e.times=ye,e.timesLimit=fe,e.timesSeries=me,e.transform=ge,e.tryEach=Et,e.unmemoize=ke,e.until=ve,e.waterfall=Ot,e.whilst=bt,e.all=et,e.allLimit=tt,e.allSeries=at,e.any=vt,e.anyLimit=St,e.anySeries=Lt,e.find=Ge,e.findLimit=We,e.findSeries=He,e.flatMap=Qe,e.flatMapLimit=De,e.flatMapSeries=Ue,e.forEach=Xe,e.forEachSeries=$e,e.forEachLimit=Ze,e.forEachOf=Me,e.forEachOfSeries=je,e.forEachOfLimit=_e,e.inject=Ye,e.foldl=Ye,e.foldr=ne,e.select=nt,e.selectLimit=it,e.selectSeries=rt,e.wrapSync=r,e.during=bt,e.doDuring=Ke,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/build/node_modules/async/dist/async.mjs b/build/node_modules/async/dist/async.mjs new file mode 100644 index 00000000..2bd479de --- /dev/null +++ b/build/node_modules/async/dist/async.mjs @@ -0,0 +1,4734 @@ +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); +} + +function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +} + +/* istanbul ignore file */ + +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +var setImmediate$1 = wrap(_defer); + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } +} + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify (asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable +} + +function applyEach (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +} + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} + +function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; + +function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper +} + +function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +} + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? {value: obj[key], key} : null; + }; +} + +function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} + +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} + +var eachOfLimit = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); +} + +var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); +} + +var eachOf$1 = awaitify(eachOf, 3); + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ +function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) +} +var map$1 = awaitify(map, 3); + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +var applyEach$1 = applyEach(map$1); + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback) +} +var eachOfSeries$1 = awaitify(eachOfSeries, 3); + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) +} +var mapSeries$1 = awaitify(mapSeries, 3); + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +var applyEachSeries = applyEach(mapSeries$1); + +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback +} + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] +} + +var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + +function parseParams(func) { + const src = func.toString().replace(STRIP_COMMENTS, ''); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); +} + +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = { + data, + callback: rejectOnError ? + promiseCallback : + (callback || promiseCallback) + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; +} + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +var reduce$1 = awaitify(reduce, 4); + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; +} + +/** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ +function compose(...args) { + return seq(...args.reverse()); +} + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) +} +var mapLimit$1 = awaitify(mapLimit, 4); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +var concatLimit$1 = awaitify(concatLimit, 4); + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ +function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) +} +var concat$1 = awaitify(concat, 3); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) +} +var concatSeries$1 = awaitify(concatSeries, 3); + +/** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ +function constant(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +} + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ +function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) +} +var detect$1 = awaitify(detect, 3); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) +} +var detectLimit$1 = awaitify(detectLimit, 4); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) +} + +var detectSeries$1 = awaitify(detectSeries, 3); + +function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + resultArgs.forEach(x => console[name](x)); + } + } + }) +} + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +var dir = consoleFunc('dir'); + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +var doWhilst$1 = awaitify(doWhilst, 3); + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); +} + +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +var each = awaitify(eachLimit, 3); + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} +var eachLimit$2 = awaitify(eachLimit$1, 4); + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback) +} +var eachSeries$1 = awaitify(eachSeries, 3); + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) +} +var every$1 = awaitify(every, 3); + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) +} +var everyLimit$1 = awaitify(everyLimit, 4); + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) +} +var everySeries$1 = awaitify(everySeries, 3); + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); +} + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) +} +var filter$1 = awaitify(filter, 3); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback) +} +var filterLimit$1 = awaitify(filterLimit, 4); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) +} +var filterSeries$1 = awaitify(filterSeries, 3); + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +var forever$1 = awaitify(forever, 2); + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +var groupByLimit$1 = awaitify(groupByLimit, 4); + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ +function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) +} + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) +} + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +var log = consoleFunc('log'); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ +function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) +} + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer$1; + +if (hasNextTick) { + _defer$1 = process.nextTick; +} else if (hasSetImmediate) { + _defer$1 = setImmediate; +} else { + _defer$1 = fallback; +} + +var nextTick = wrap(_defer$1); + +var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ +function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); +} + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit(limit), tasks, callback); +} + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +function queue$1 (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +} + +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +function leftChi(i) { + return (i<<1)+1; +} + +function parent(i) { + return ((i+1)>>1)-1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } +} + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ +function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + q._tasks = new Heap(); + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback = () => {}) { + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!Array.isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(() => q.drain()); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority, + callback + }; + + q._tasks.push(item); + } + + setImmediate$1(q.process); + }; + + // Remove unshift function + delete q.unshift; + + return q; +} + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } +} + +var race$1 = awaitify(race, 2); + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); +} + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; +} + +function reject(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ +function reject$1 (coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback) +} +var reject$2 = awaitify(reject$1, 3); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit (coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback) +} +var rejectLimit$1 = awaitify(rejectLimit, 4); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries (coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback) +} +var rejectSeries$1 = awaitify(rejectSeries, 3); + +function constant$1(value) { + return function () { + return value; + } +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); +} + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ +function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); +} + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) +} +var some$1 = awaitify(some, 3); + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) +} +var someLimit$1 = awaitify(someLimit, 4); + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) +} +var someSeries$1 = awaitify(someSeries, 3); + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +var sortBy$1 = awaitify(sortBy, 3); + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} + +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); +} + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) +} + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ +function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] +} + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +var tryEach$1 = awaitify(tryEach); + +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +var whilst$1 = awaitify(whilst, 3); + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(page, cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); +} + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +var waterfall$1 = awaitify(waterfall); + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +var index = { + apply, + applyEach: applyEach$1, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo, + cargoQueue: cargo$1, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 +}; + +export default index; +export { apply, applyEach$1 as applyEach, applyEachSeries, asyncify, auto, autoInject, cargo, cargo$1 as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doUntil, doWhilst$1 as doWhilst, each, eachLimit$2 as eachLimit, eachOf$1 as eachOf, eachOfLimit$2 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue$1 as queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$2 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, each as forEach, eachSeries$1 as forEachSeries, eachLimit$2 as forEachLimit, eachOf$1 as forEachOf, eachOfSeries$1 as forEachOfSeries, eachOfLimit$2 as forEachOfLimit, reduce$1 as inject, reduce$1 as foldl, reduceRight as foldr, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, asyncify as wrapSync, whilst$1 as during, doWhilst$1 as doDuring }; diff --git a/build/node_modules/async/doDuring.js b/build/node_modules/async/doDuring.js new file mode 100644 index 00000000..c0def6f1 --- /dev/null +++ b/build/node_modules/async/doDuring.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/doUntil.js b/build/node_modules/async/doUntil.js new file mode 100644 index 00000000..644cb372 --- /dev/null +++ b/build/node_modules/async/doUntil.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doUntil; + +var _doWhilst = require('./doWhilst'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _doWhilst2.default)(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb(err, !truth)); + }, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/doWhilst.js b/build/node_modules/async/doWhilst.js new file mode 100644 index 00000000..c0def6f1 --- /dev/null +++ b/build/node_modules/async/doWhilst.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/during.js b/build/node_modules/async/during.js new file mode 100644 index 00000000..4f4a39b4 --- /dev/null +++ b/build/node_modules/async/during.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/each.js b/build/node_modules/async/each.js new file mode 100644 index 00000000..39e15d91 --- /dev/null +++ b/build/node_modules/async/each.js @@ -0,0 +1,88 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/eachLimit.js b/build/node_modules/async/eachLimit.js new file mode 100644 index 00000000..7e9f9ae4 --- /dev/null +++ b/build/node_modules/async/eachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/eachOf.js b/build/node_modules/async/eachOf.js new file mode 100644 index 00000000..4123ef57 --- /dev/null +++ b/build/node_modules/async/eachOf.js @@ -0,0 +1,116 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/eachOfLimit.js b/build/node_modules/async/eachOfLimit.js new file mode 100644 index 00000000..48dc3e56 --- /dev/null +++ b/build/node_modules/async/eachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/eachOfSeries.js b/build/node_modules/async/eachOfSeries.js new file mode 100644 index 00000000..75de61fe --- /dev/null +++ b/build/node_modules/async/eachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/eachSeries.js b/build/node_modules/async/eachSeries.js new file mode 100644 index 00000000..ec18a777 --- /dev/null +++ b/build/node_modules/async/eachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/ensureAsync.js b/build/node_modules/async/ensureAsync.js new file mode 100644 index 00000000..dee0a55f --- /dev/null +++ b/build/node_modules/async/ensureAsync.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ensureAsync; + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if ((0, _wrapAsync.isAsync)(fn)) return fn; + return function (...args /*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + (0, _setImmediate2.default)(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/every.js b/build/node_modules/async/every.js new file mode 100644 index 00000000..1c2e5360 --- /dev/null +++ b/build/node_modules/async/every.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/everyLimit.js b/build/node_modules/async/everyLimit.js new file mode 100644 index 00000000..bb78378d --- /dev/null +++ b/build/node_modules/async/everyLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/everySeries.js b/build/node_modules/async/everySeries.js new file mode 100644 index 00000000..76eeaf7e --- /dev/null +++ b/build/node_modules/async/everySeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/filter.js b/build/node_modules/async/filter.js new file mode 100644 index 00000000..fadd16a7 --- /dev/null +++ b/build/node_modules/async/filter.js @@ -0,0 +1,53 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/filterLimit.js b/build/node_modules/async/filterLimit.js new file mode 100644 index 00000000..7fdee119 --- /dev/null +++ b/build/node_modules/async/filterLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/filterSeries.js b/build/node_modules/async/filterSeries.js new file mode 100644 index 00000000..ee8bde9d --- /dev/null +++ b/build/node_modules/async/filterSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/find.js b/build/node_modules/async/find.js new file mode 100644 index 00000000..1066b9e8 --- /dev/null +++ b/build/node_modules/async/find.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns A Promise, if no callback is passed + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/findLimit.js b/build/node_modules/async/findLimit.js new file mode 100644 index 00000000..9e2d3a0d --- /dev/null +++ b/build/node_modules/async/findLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/findSeries.js b/build/node_modules/async/findSeries.js new file mode 100644 index 00000000..cdf38b1d --- /dev/null +++ b/build/node_modules/async/findSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns a Promise if no callback is passed + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/flatMap.js b/build/node_modules/async/flatMap.js new file mode 100644 index 00000000..39555c8f --- /dev/null +++ b/build/node_modules/async/flatMap.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { + * // files is now a list of filenames that exist in the 3 directories + * }); + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/flatMapLimit.js b/build/node_modules/async/flatMapLimit.js new file mode 100644 index 00000000..3ef4b5fd --- /dev/null +++ b/build/node_modules/async/flatMapLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/flatMapSeries.js b/build/node_modules/async/flatMapSeries.js new file mode 100644 index 00000000..fbc105b9 --- /dev/null +++ b/build/node_modules/async/flatMapSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/foldl.js b/build/node_modules/async/foldl.js new file mode 100644 index 00000000..e7816830 --- /dev/null +++ b/build/node_modules/async/foldl.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reduce([1,2,3], 0, function(memo, item, callback) { + * // pointless async: + * process.nextTick(function() { + * callback(null, memo + item) + * }); + * }, function(err, result) { + * // result is now equal to the last value of memo, which is 6 + * }); + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/foldr.js b/build/node_modules/async/foldr.js new file mode 100644 index 00000000..e3da2a4d --- /dev/null +++ b/build/node_modules/async/foldr.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forEach.js b/build/node_modules/async/forEach.js new file mode 100644 index 00000000..39e15d91 --- /dev/null +++ b/build/node_modules/async/forEach.js @@ -0,0 +1,88 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forEachLimit.js b/build/node_modules/async/forEachLimit.js new file mode 100644 index 00000000..7e9f9ae4 --- /dev/null +++ b/build/node_modules/async/forEachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forEachOf.js b/build/node_modules/async/forEachOf.js new file mode 100644 index 00000000..4123ef57 --- /dev/null +++ b/build/node_modules/async/forEachOf.js @@ -0,0 +1,116 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forEachOfLimit.js b/build/node_modules/async/forEachOfLimit.js new file mode 100644 index 00000000..48dc3e56 --- /dev/null +++ b/build/node_modules/async/forEachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forEachOfSeries.js b/build/node_modules/async/forEachOfSeries.js new file mode 100644 index 00000000..75de61fe --- /dev/null +++ b/build/node_modules/async/forEachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forEachSeries.js b/build/node_modules/async/forEachSeries.js new file mode 100644 index 00000000..ec18a777 --- /dev/null +++ b/build/node_modules/async/forEachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/forever.js b/build/node_modules/async/forever.js new file mode 100644 index 00000000..0d9a5c71 --- /dev/null +++ b/build/node_modules/async/forever.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = (0, _onlyOnce2.default)(errback); + var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +exports.default = (0, _awaitify2.default)(forever, 2); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/groupBy.js b/build/node_modules/async/groupBy.js new file mode 100644 index 00000000..a7e4304d --- /dev/null +++ b/build/node_modules/async/groupBy.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBy; + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ +function groupBy(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/groupByLimit.js b/build/node_modules/async/groupByLimit.js new file mode 100644 index 00000000..f7da249a --- /dev/null +++ b/build/node_modules/async/groupByLimit.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, { key, val }); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var { hasOwnProperty } = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var { key } = mapResults[i]; + var { val } = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +exports.default = (0, _awaitify2.default)(groupByLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/groupBySeries.js b/build/node_modules/async/groupBySeries.js new file mode 100644 index 00000000..b3a945aa --- /dev/null +++ b/build/node_modules/async/groupBySeries.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBySeries; + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, 1, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/index.js b/build/node_modules/async/index.js new file mode 100644 index 00000000..ce647d59 --- /dev/null +++ b/build/node_modules/async/index.js @@ -0,0 +1,588 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.doDuring = exports.during = exports.wrapSync = undefined; +exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.flatMapSeries = exports.flatMapLimit = exports.flatMap = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.doWhilst = exports.doUntil = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargoQueue = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; + +var _apply = require('./apply'); + +var _apply2 = _interopRequireDefault(_apply); + +var _applyEach = require('./applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _applyEachSeries = require('./applyEachSeries'); + +var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); + +var _asyncify = require('./asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _autoInject = require('./autoInject'); + +var _autoInject2 = _interopRequireDefault(_autoInject); + +var _cargo = require('./cargo'); + +var _cargo2 = _interopRequireDefault(_cargo); + +var _cargoQueue = require('./cargoQueue'); + +var _cargoQueue2 = _interopRequireDefault(_cargoQueue); + +var _compose = require('./compose'); + +var _compose2 = _interopRequireDefault(_compose); + +var _concat = require('./concat'); + +var _concat2 = _interopRequireDefault(_concat); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _concatSeries = require('./concatSeries'); + +var _concatSeries2 = _interopRequireDefault(_concatSeries); + +var _constant = require('./constant'); + +var _constant2 = _interopRequireDefault(_constant); + +var _detect = require('./detect'); + +var _detect2 = _interopRequireDefault(_detect); + +var _detectLimit = require('./detectLimit'); + +var _detectLimit2 = _interopRequireDefault(_detectLimit); + +var _detectSeries = require('./detectSeries'); + +var _detectSeries2 = _interopRequireDefault(_detectSeries); + +var _dir = require('./dir'); + +var _dir2 = _interopRequireDefault(_dir); + +var _doUntil = require('./doUntil'); + +var _doUntil2 = _interopRequireDefault(_doUntil); + +var _doWhilst = require('./doWhilst'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _each = require('./each'); + +var _each2 = _interopRequireDefault(_each); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _every = require('./every'); + +var _every2 = _interopRequireDefault(_every); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _everySeries = require('./everySeries'); + +var _everySeries2 = _interopRequireDefault(_everySeries); + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _filterSeries = require('./filterSeries'); + +var _filterSeries2 = _interopRequireDefault(_filterSeries); + +var _forever = require('./forever'); + +var _forever2 = _interopRequireDefault(_forever); + +var _groupBy = require('./groupBy'); + +var _groupBy2 = _interopRequireDefault(_groupBy); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +var _groupBySeries = require('./groupBySeries'); + +var _groupBySeries2 = _interopRequireDefault(_groupBySeries); + +var _log = require('./log'); + +var _log2 = _interopRequireDefault(_log); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +var _mapValues = require('./mapValues'); + +var _mapValues2 = _interopRequireDefault(_mapValues); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _mapValuesSeries = require('./mapValuesSeries'); + +var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); + +var _memoize = require('./memoize'); + +var _memoize2 = _interopRequireDefault(_memoize); + +var _nextTick = require('./nextTick'); + +var _nextTick2 = _interopRequireDefault(_nextTick); + +var _parallel = require('./parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +var _parallelLimit = require('./parallelLimit'); + +var _parallelLimit2 = _interopRequireDefault(_parallelLimit); + +var _priorityQueue = require('./priorityQueue'); + +var _priorityQueue2 = _interopRequireDefault(_priorityQueue); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _race = require('./race'); + +var _race2 = _interopRequireDefault(_race); + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _reduceRight = require('./reduceRight'); + +var _reduceRight2 = _interopRequireDefault(_reduceRight); + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +var _reflectAll = require('./reflectAll'); + +var _reflectAll2 = _interopRequireDefault(_reflectAll); + +var _reject = require('./reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _rejectLimit = require('./rejectLimit'); + +var _rejectLimit2 = _interopRequireDefault(_rejectLimit); + +var _rejectSeries = require('./rejectSeries'); + +var _rejectSeries2 = _interopRequireDefault(_rejectSeries); + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _retryable = require('./retryable'); + +var _retryable2 = _interopRequireDefault(_retryable); + +var _seq = require('./seq'); + +var _seq2 = _interopRequireDefault(_seq); + +var _series = require('./series'); + +var _series2 = _interopRequireDefault(_series); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _some = require('./some'); + +var _some2 = _interopRequireDefault(_some); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _someSeries = require('./someSeries'); + +var _someSeries2 = _interopRequireDefault(_someSeries); + +var _sortBy = require('./sortBy'); + +var _sortBy2 = _interopRequireDefault(_sortBy); + +var _timeout = require('./timeout'); + +var _timeout2 = _interopRequireDefault(_timeout); + +var _times = require('./times'); + +var _times2 = _interopRequireDefault(_times); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _timesSeries = require('./timesSeries'); + +var _timesSeries2 = _interopRequireDefault(_timesSeries); + +var _transform = require('./transform'); + +var _transform2 = _interopRequireDefault(_transform); + +var _tryEach = require('./tryEach'); + +var _tryEach2 = _interopRequireDefault(_tryEach); + +var _unmemoize = require('./unmemoize'); + +var _unmemoize2 = _interopRequireDefault(_unmemoize); + +var _until = require('./until'); + +var _until2 = _interopRequireDefault(_until); + +var _waterfall = require('./waterfall'); + +var _waterfall2 = _interopRequireDefault(_waterfall); + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +/** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @module async + * @see AsyncFunction + */ + +/** + * A collection of `async` functions for manipulating collections, such as + * arrays and objects. + * @module Collections + */ + +/** + * A collection of `async` functions for controlling the flow through a script. + * @module ControlFlow + */ + +/** + * A collection of `async` utility functions. + * @module Utils + */ + +exports.default = { + apply: _apply2.default, + applyEach: _applyEach2.default, + applyEachSeries: _applyEachSeries2.default, + asyncify: _asyncify2.default, + auto: _auto2.default, + autoInject: _autoInject2.default, + cargo: _cargo2.default, + cargoQueue: _cargoQueue2.default, + compose: _compose2.default, + concat: _concat2.default, + concatLimit: _concatLimit2.default, + concatSeries: _concatSeries2.default, + constant: _constant2.default, + detect: _detect2.default, + detectLimit: _detectLimit2.default, + detectSeries: _detectSeries2.default, + dir: _dir2.default, + doUntil: _doUntil2.default, + doWhilst: _doWhilst2.default, + each: _each2.default, + eachLimit: _eachLimit2.default, + eachOf: _eachOf2.default, + eachOfLimit: _eachOfLimit2.default, + eachOfSeries: _eachOfSeries2.default, + eachSeries: _eachSeries2.default, + ensureAsync: _ensureAsync2.default, + every: _every2.default, + everyLimit: _everyLimit2.default, + everySeries: _everySeries2.default, + filter: _filter2.default, + filterLimit: _filterLimit2.default, + filterSeries: _filterSeries2.default, + forever: _forever2.default, + groupBy: _groupBy2.default, + groupByLimit: _groupByLimit2.default, + groupBySeries: _groupBySeries2.default, + log: _log2.default, + map: _map2.default, + mapLimit: _mapLimit2.default, + mapSeries: _mapSeries2.default, + mapValues: _mapValues2.default, + mapValuesLimit: _mapValuesLimit2.default, + mapValuesSeries: _mapValuesSeries2.default, + memoize: _memoize2.default, + nextTick: _nextTick2.default, + parallel: _parallel2.default, + parallelLimit: _parallelLimit2.default, + priorityQueue: _priorityQueue2.default, + queue: _queue2.default, + race: _race2.default, + reduce: _reduce2.default, + reduceRight: _reduceRight2.default, + reflect: _reflect2.default, + reflectAll: _reflectAll2.default, + reject: _reject2.default, + rejectLimit: _rejectLimit2.default, + rejectSeries: _rejectSeries2.default, + retry: _retry2.default, + retryable: _retryable2.default, + seq: _seq2.default, + series: _series2.default, + setImmediate: _setImmediate2.default, + some: _some2.default, + someLimit: _someLimit2.default, + someSeries: _someSeries2.default, + sortBy: _sortBy2.default, + timeout: _timeout2.default, + times: _times2.default, + timesLimit: _timesLimit2.default, + timesSeries: _timesSeries2.default, + transform: _transform2.default, + tryEach: _tryEach2.default, + unmemoize: _unmemoize2.default, + until: _until2.default, + waterfall: _waterfall2.default, + whilst: _whilst2.default, + + // aliases + all: _every2.default, + allLimit: _everyLimit2.default, + allSeries: _everySeries2.default, + any: _some2.default, + anyLimit: _someLimit2.default, + anySeries: _someSeries2.default, + find: _detect2.default, + findLimit: _detectLimit2.default, + findSeries: _detectSeries2.default, + flatMap: _concat2.default, + flatMapLimit: _concatLimit2.default, + flatMapSeries: _concatSeries2.default, + forEach: _each2.default, + forEachSeries: _eachSeries2.default, + forEachLimit: _eachLimit2.default, + forEachOf: _eachOf2.default, + forEachOfSeries: _eachOfSeries2.default, + forEachOfLimit: _eachOfLimit2.default, + inject: _reduce2.default, + foldl: _reduce2.default, + foldr: _reduceRight2.default, + select: _filter2.default, + selectLimit: _filterLimit2.default, + selectSeries: _filterSeries2.default, + wrapSync: _asyncify2.default, + during: _whilst2.default, + doDuring: _doWhilst2.default +}; +exports.apply = _apply2.default; +exports.applyEach = _applyEach2.default; +exports.applyEachSeries = _applyEachSeries2.default; +exports.asyncify = _asyncify2.default; +exports.auto = _auto2.default; +exports.autoInject = _autoInject2.default; +exports.cargo = _cargo2.default; +exports.cargoQueue = _cargoQueue2.default; +exports.compose = _compose2.default; +exports.concat = _concat2.default; +exports.concatLimit = _concatLimit2.default; +exports.concatSeries = _concatSeries2.default; +exports.constant = _constant2.default; +exports.detect = _detect2.default; +exports.detectLimit = _detectLimit2.default; +exports.detectSeries = _detectSeries2.default; +exports.dir = _dir2.default; +exports.doUntil = _doUntil2.default; +exports.doWhilst = _doWhilst2.default; +exports.each = _each2.default; +exports.eachLimit = _eachLimit2.default; +exports.eachOf = _eachOf2.default; +exports.eachOfLimit = _eachOfLimit2.default; +exports.eachOfSeries = _eachOfSeries2.default; +exports.eachSeries = _eachSeries2.default; +exports.ensureAsync = _ensureAsync2.default; +exports.every = _every2.default; +exports.everyLimit = _everyLimit2.default; +exports.everySeries = _everySeries2.default; +exports.filter = _filter2.default; +exports.filterLimit = _filterLimit2.default; +exports.filterSeries = _filterSeries2.default; +exports.forever = _forever2.default; +exports.groupBy = _groupBy2.default; +exports.groupByLimit = _groupByLimit2.default; +exports.groupBySeries = _groupBySeries2.default; +exports.log = _log2.default; +exports.map = _map2.default; +exports.mapLimit = _mapLimit2.default; +exports.mapSeries = _mapSeries2.default; +exports.mapValues = _mapValues2.default; +exports.mapValuesLimit = _mapValuesLimit2.default; +exports.mapValuesSeries = _mapValuesSeries2.default; +exports.memoize = _memoize2.default; +exports.nextTick = _nextTick2.default; +exports.parallel = _parallel2.default; +exports.parallelLimit = _parallelLimit2.default; +exports.priorityQueue = _priorityQueue2.default; +exports.queue = _queue2.default; +exports.race = _race2.default; +exports.reduce = _reduce2.default; +exports.reduceRight = _reduceRight2.default; +exports.reflect = _reflect2.default; +exports.reflectAll = _reflectAll2.default; +exports.reject = _reject2.default; +exports.rejectLimit = _rejectLimit2.default; +exports.rejectSeries = _rejectSeries2.default; +exports.retry = _retry2.default; +exports.retryable = _retryable2.default; +exports.seq = _seq2.default; +exports.series = _series2.default; +exports.setImmediate = _setImmediate2.default; +exports.some = _some2.default; +exports.someLimit = _someLimit2.default; +exports.someSeries = _someSeries2.default; +exports.sortBy = _sortBy2.default; +exports.timeout = _timeout2.default; +exports.times = _times2.default; +exports.timesLimit = _timesLimit2.default; +exports.timesSeries = _timesSeries2.default; +exports.transform = _transform2.default; +exports.tryEach = _tryEach2.default; +exports.unmemoize = _unmemoize2.default; +exports.until = _until2.default; +exports.waterfall = _waterfall2.default; +exports.whilst = _whilst2.default; +exports.all = _every2.default; +exports.allLimit = _everyLimit2.default; +exports.allSeries = _everySeries2.default; +exports.any = _some2.default; +exports.anyLimit = _someLimit2.default; +exports.anySeries = _someSeries2.default; +exports.find = _detect2.default; +exports.findLimit = _detectLimit2.default; +exports.findSeries = _detectSeries2.default; +exports.flatMap = _concat2.default; +exports.flatMapLimit = _concatLimit2.default; +exports.flatMapSeries = _concatSeries2.default; +exports.forEach = _each2.default; +exports.forEachSeries = _eachSeries2.default; +exports.forEachLimit = _eachLimit2.default; +exports.forEachOf = _eachOf2.default; +exports.forEachOfSeries = _eachOfSeries2.default; +exports.forEachOfLimit = _eachOfLimit2.default; +exports.inject = _reduce2.default; +exports.foldl = _reduce2.default; +exports.foldr = _reduceRight2.default; +exports.select = _filter2.default; +exports.selectLimit = _filterLimit2.default; +exports.selectSeries = _filterSeries2.default; +exports.wrapSync = _asyncify2.default; +exports.during = _whilst2.default; +exports.doDuring = _doWhilst2.default; \ No newline at end of file diff --git a/build/node_modules/async/inject.js b/build/node_modules/async/inject.js new file mode 100644 index 00000000..e7816830 --- /dev/null +++ b/build/node_modules/async/inject.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reduce([1,2,3], 0, function(memo, item, callback) { + * // pointless async: + * process.nextTick(function() { + * callback(null, memo + item) + * }); + * }, function(err, result) { + * // result is now equal to the last value of memo, which is 6 + * }); + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/DoublyLinkedList.js b/build/node_modules/async/internal/DoublyLinkedList.js new file mode 100644 index 00000000..cd11c3b3 --- /dev/null +++ b/build/node_modules/async/internal/DoublyLinkedList.js @@ -0,0 +1,92 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty() { + while (this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove(testFn) { + var curr = this.head; + while (curr) { + var { next } = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +exports.default = DLL; +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/Heap.js b/build/node_modules/async/internal/Heap.js new file mode 100644 index 00000000..80762fe0 --- /dev/null +++ b/build/node_modules/async/internal/Heap.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty() { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p = parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l = leftChi(index)) < this.heap.length) { + if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) { + l = l + 1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length - 1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove(testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length - 1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +exports.default = Heap; +function leftChi(i) { + return (i << 1) + 1; +} + +function parent(i) { + return (i + 1 >> 1) - 1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } else { + return x.pushCount < y.pushCount; + } +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/applyEach.js b/build/node_modules/async/internal/applyEach.js new file mode 100644 index 00000000..3c3c6f66 --- /dev/null +++ b/build/node_modules/async/internal/applyEach.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = (0, _awaitify2.default)(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + (0, _wrapAsync2.default)(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +}; + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/asyncEachOfLimit.js b/build/node_modules/async/internal/asyncEachOfLimit.js new file mode 100644 index 00000000..df228c73 --- /dev/null +++ b/build/node_modules/async/internal/asyncEachOfLimit.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncEachOfLimit; + +var _breakLoop = require('./breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return; + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({ value, done: iterDone }) => { + //console.log('got value', value) + if (canceled || done) return; + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return; + if (err) return handleError(err); + + if (err === false) { + done = true; + canceled = true; + return; + } + + if (result === _breakLoop2.default || done && running <= 0) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/awaitify.js b/build/node_modules/async/internal/awaitify.js new file mode 100644 index 00000000..7b36f1ac --- /dev/null +++ b/build/node_modules/async/internal/awaitify.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = awaitify; +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify(asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined'); + function awaitable(...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args); + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err); + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }); + } + + return awaitable; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/breakLoop.js b/build/node_modules/async/internal/breakLoop.js new file mode 100644 index 00000000..8245e553 --- /dev/null +++ b/build/node_modules/async/internal/breakLoop.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; +exports.default = breakLoop; +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/consoleFunc.js b/build/node_modules/async/internal/consoleFunc.js new file mode 100644 index 00000000..1e592734 --- /dev/null +++ b/build/node_modules/async/internal/consoleFunc.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = consoleFunc; + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function consoleFunc(name) { + return (fn, ...args) => (0, _wrapAsync2.default)(fn)(...args, (err, ...resultArgs) => { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + resultArgs.forEach(x => console[name](x)); + } + } + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/createTester.js b/build/node_modules/async/internal/createTester.js new file mode 100644 index 00000000..7df34987 --- /dev/null +++ b/build/node_modules/async/internal/createTester.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _createTester; + +var _breakLoop = require('./breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = (0, _wrapAsync2.default)(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, _breakLoop2.default); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/eachOfLimit.js b/build/node_modules/async/internal/eachOfLimit.js new file mode 100644 index 00000000..69e22a29 --- /dev/null +++ b/build/node_modules/async/internal/eachOfLimit.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./once'); + +var _once2 = _interopRequireDefault(_once); + +var _iterator = require('./iterator'); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _onlyOnce = require('./onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./wrapAsync'); + +var _asyncEachOfLimit = require('./asyncEachOfLimit'); + +var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); + +var _breakLoop = require('./breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = limit => { + return (obj, iteratee, callback) => { + callback = (0, _once2.default)(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1'); + } + if (!obj) { + return callback(null); + } + if ((0, _wrapAsync.isAsyncGenerator)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); + } + if ((0, _wrapAsync.isAsyncIterable)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; + if (err) { + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); + } + } + + function replenish() { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/filter.js b/build/node_modules/async/internal/filter.js new file mode 100644 index 00000000..df68185e --- /dev/null +++ b/build/node_modules/async/internal/filter.js @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _filter; + +var _isArrayLike = require('./isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({ index, value: x }); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results.sort((a, b) => a.index - b.index).map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/getIterator.js b/build/node_modules/async/internal/getIterator.js new file mode 100644 index 00000000..830a5452 --- /dev/null +++ b/build/node_modules/async/internal/getIterator.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +}; + +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/initialParams.js b/build/node_modules/async/internal/initialParams.js new file mode 100644 index 00000000..245378cf --- /dev/null +++ b/build/node_modules/async/internal/initialParams.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn) { + return function (...args /*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +}; + +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/isArrayLike.js b/build/node_modules/async/internal/isArrayLike.js new file mode 100644 index 00000000..ce076704 --- /dev/null +++ b/build/node_modules/async/internal/isArrayLike.js @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isArrayLike; +function isArrayLike(value) { + return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/iterator.js b/build/node_modules/async/internal/iterator.js new file mode 100644 index 00000000..a49b8bbc --- /dev/null +++ b/build/node_modules/async/internal/iterator.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = createIterator; + +var _isArrayLike = require('./isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _getIterator = require('./getIterator'); + +var _getIterator2 = _interopRequireDefault(_getIterator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? { value: obj[key], key } : null; + }; +} + +function createIterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + + var iterator = (0, _getIterator2.default)(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/map.js b/build/node_modules/async/internal/map.js new file mode 100644 index 00000000..27a6481e --- /dev/null +++ b/build/node_modules/async/internal/map.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _asyncMap; + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/once.js b/build/node_modules/async/internal/once.js new file mode 100644 index 00000000..49f37270 --- /dev/null +++ b/build/node_modules/async/internal/once.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = once; +function once(fn) { + function wrapper(...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/onlyOnce.js b/build/node_modules/async/internal/onlyOnce.js new file mode 100644 index 00000000..6ad721bd --- /dev/null +++ b/build/node_modules/async/internal/onlyOnce.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onlyOnce; +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/parallel.js b/build/node_modules/async/internal/parallel.js new file mode 100644 index 00000000..183c6678 --- /dev/null +++ b/build/node_modules/async/internal/parallel.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/promiseCallback.js b/build/node_modules/async/internal/promiseCallback.js new file mode 100644 index 00000000..17a83016 --- /dev/null +++ b/build/node_modules/async/internal/promiseCallback.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback() { + let resolve, reject; + function callback(err, ...args) { + if (err) return reject(err); + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, reject = rej; + }); + + return callback; +} + +exports.promiseCallback = promiseCallback; +exports.PROMISE_SYMBOL = PROMISE_SYMBOL; \ No newline at end of file diff --git a/build/node_modules/async/internal/queue.js b/build/node_modules/async/internal/queue.js new file mode 100644 index 00000000..8973d98d --- /dev/null +++ b/build/node_modules/async/internal/queue.js @@ -0,0 +1,291 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = queue; + +var _onlyOnce = require('./onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _DoublyLinkedList = require('./DoublyLinkedList'); + +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = (0, _wrapAsync2.default)(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on(event, handler) { + events[event].push(handler); + } + + function once(event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off(event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []); + if (!handler) return events[event] = []; + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger(event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback(err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res(); + if (args.length <= 1) return res(args[0]); + res(args); + } + + var item = { + data, + callback: rejectOnError ? promiseCallback : callback || promiseCallback + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + (0, _setImmediate2.default)(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= q.concurrency - q.buffer) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + (0, _setImmediate2.default)(() => trigger('drain')); + return true; + } + return false; + } + + const eventMethod = name => handler => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err); + resolve(data); + }); + }); + } + off(name); + on(name, handler); + }; + + var isProcessing = false; + var q = { + _tasks: new _DoublyLinkedList2.default(), + *[Symbol.iterator]() { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, false, callback)); + } + return _insert(data, false, false, callback); + }, + pushAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, true, callback)); + } + return _insert(data, false, true, callback); + }, + kill() { + off(); + q._tasks.empty(); + }, + unshift(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, false, callback)); + } + return _insert(data, true, false, callback); + }, + unshiftAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, true, callback)); + } + return _insert(data, true, true, callback); + }, + remove(testFn) { + q._tasks.remove(testFn); + }, + process() { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while (!q.paused && numRunning < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = (0, _onlyOnce2.default)(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length() { + return q._tasks.length; + }, + running() { + return numRunning; + }, + workersList() { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause() { + q.paused = true; + }, + resume() { + if (q.paused === false) { + return; + } + q.paused = false; + (0, _setImmediate2.default)(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + } + }); + return q; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/range.js b/build/node_modules/async/internal/range.js new file mode 100644 index 00000000..6680e642 --- /dev/null +++ b/build/node_modules/async/internal/range.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = range; +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/reject.js b/build/node_modules/async/internal/reject.js new file mode 100644 index 00000000..ba6cddac --- /dev/null +++ b/build/node_modules/async/internal/reject.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reject; + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reject(eachfn, arr, _iteratee, callback) { + const iteratee = (0, _wrapAsync2.default)(_iteratee); + return (0, _filter2.default)(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/internal/setImmediate.js b/build/node_modules/async/internal/setImmediate.js new file mode 100644 index 00000000..d0505c7d --- /dev/null +++ b/build/node_modules/async/internal/setImmediate.js @@ -0,0 +1,30 @@ +'use strict'; +/* istanbul ignore file */ + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fallback = fallback; +exports.wrap = wrap; +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +exports.default = wrap(_defer); \ No newline at end of file diff --git a/build/node_modules/async/internal/withoutIndex.js b/build/node_modules/async/internal/withoutIndex.js new file mode 100644 index 00000000..ec45fa35 --- /dev/null +++ b/build/node_modules/async/internal/withoutIndex.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _withoutIndex; +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/internal/wrapAsync.js b/build/node_modules/async/internal/wrapAsync.js new file mode 100644 index 00000000..5719450a --- /dev/null +++ b/build/node_modules/async/internal/wrapAsync.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined; + +var _asyncify = require('../asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function'); + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; +} + +exports.default = wrapAsync; +exports.isAsync = isAsync; +exports.isAsyncGenerator = isAsyncGenerator; +exports.isAsyncIterable = isAsyncIterable; \ No newline at end of file diff --git a/build/node_modules/async/log.js b/build/node_modules/async/log.js new file mode 100644 index 00000000..c643867b --- /dev/null +++ b/build/node_modules/async/log.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +exports.default = (0, _consoleFunc2.default)('log'); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/map.js b/build/node_modules/async/map.js new file mode 100644 index 00000000..2d85f2e2 --- /dev/null +++ b/build/node_modules/async/map.js @@ -0,0 +1,62 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ +function map(coll, iteratee, callback) { + return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(map, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/mapLimit.js b/build/node_modules/async/mapLimit.js new file mode 100644 index 00000000..0f390ab6 --- /dev/null +++ b/build/node_modules/async/mapLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit(coll, limit, iteratee, callback) { + return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/mapSeries.js b/build/node_modules/async/mapSeries.js new file mode 100644 index 00000000..973033a0 --- /dev/null +++ b/build/node_modules/async/mapSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries(coll, iteratee, callback) { + return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/mapValues.js b/build/node_modules/async/mapValues.js new file mode 100644 index 00000000..7eab584e --- /dev/null +++ b/build/node_modules/async/mapValues.js @@ -0,0 +1,62 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValues; + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ +function mapValues(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/mapValuesLimit.js b/build/node_modules/async/mapValuesLimit.js new file mode 100644 index 00000000..15cda346 --- /dev/null +++ b/build/node_modules/async/mapValuesLimit.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = (0, _once2.default)(callback); + var newObj = {}; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfLimit2.default)(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +exports.default = (0, _awaitify2.default)(mapValuesLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/mapValuesSeries.js b/build/node_modules/async/mapValuesSeries.js new file mode 100644 index 00000000..f0dda6b9 --- /dev/null +++ b/build/node_modules/async/mapValuesSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValuesSeries; + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/memoize.js b/build/node_modules/async/memoize.js new file mode 100644 index 00000000..425f93b9 --- /dev/null +++ b/build/node_modules/async/memoize.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize; + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = (0, _wrapAsync2.default)(fn); + var memoized = (0, _initialParams2.default)((args, callback) => { + var key = hasher(...args); + if (key in memo) { + (0, _setImmediate2.default)(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/nextTick.js b/build/node_modules/async/nextTick.js new file mode 100644 index 00000000..a55b6921 --- /dev/null +++ b/build/node_modules/async/nextTick.js @@ -0,0 +1,52 @@ +'use strict'; +/* istanbul ignore file */ + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate'); + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; + +if (_setImmediate.hasNextTick) { + _defer = process.nextTick; +} else if (_setImmediate.hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = _setImmediate.fallback; +} + +exports.default = (0, _setImmediate.wrap)(_defer); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/package.json b/build/node_modules/async/package.json new file mode 100644 index 00000000..4f07681a --- /dev/null +++ b/build/node_modules/async/package.json @@ -0,0 +1,109 @@ +{ + "_from": "async@^3.1.0", + "_id": "async@3.2.0", + "_inBundle": false, + "_integrity": "sha512-TR2mEZFVOj2pLStYxLht7TyfuRzaydfpxr3k9RpHIzMgw7A64dzsdqCxH1WJyQdoe8T10nDXd9wnEigmiuHIZw==", + "_location": "/async", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "async@^3.1.0", + "name": "async", + "escapedName": "async", + "rawSpec": "^3.1.0", + "saveSpec": null, + "fetchSpec": "^3.1.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/async/-/async-3.2.0.tgz", + "_shasum": "b3a2685c5ebb641d3de02d161002c60fc9f85720", + "_spec": "async@^3.1.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Caolan McMahon" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Higher-order functions and common patterns for asynchronous code", + "devDependencies": { + "babel-core": "^6.26.3", + "babel-eslint": "^8.2.6", + "babel-minify": "^0.5.0", + "babel-plugin-add-module-exports": "^0.2.1", + "babel-plugin-istanbul": "^5.1.4", + "babel-plugin-syntax-async-generators": "^6.13.0", + "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", + "babel-preset-es2015": "^6.3.13", + "babel-preset-es2017": "^6.22.0", + "babel-register": "^6.26.0", + "babelify": "^8.0.0", + "benchmark": "^2.1.1", + "bluebird": "^3.4.6", + "browserify": "^16.2.3", + "chai": "^4.2.0", + "cheerio": "^0.22.0", + "coveralls": "^3.0.4", + "es6-promise": "^2.3.0", + "eslint": "^6.0.1", + "eslint-plugin-prefer-arrow": "^1.1.5", + "fs-extra": "^0.26.7", + "jsdoc": "^3.6.2", + "karma": "^4.1.0", + "karma-browserify": "^5.3.0", + "karma-edge-launcher": "^0.4.2", + "karma-firefox-launcher": "^1.1.0", + "karma-junit-reporter": "^1.2.0", + "karma-mocha": "^1.2.0", + "karma-mocha-reporter": "^2.2.0", + "karma-safari-launcher": "^1.0.0", + "mocha": "^6.1.4", + "mocha-junit-reporter": "^1.18.0", + "native-promise-only": "^0.8.0-a", + "nyc": "^14.1.1", + "rimraf": "^2.5.0", + "rollup": "^0.63.4", + "rollup-plugin-node-resolve": "^2.0.0", + "rollup-plugin-npm": "^2.0.0", + "rsvp": "^3.0.18", + "semver": "^5.5.0", + "yargs": "^11.0.0" + }, + "homepage": "https://caolan.github.io/async/", + "keywords": [ + "async", + "callback", + "module", + "utility" + ], + "license": "MIT", + "main": "dist/async.js", + "module": "dist/async.mjs", + "name": "async", + "nyc": { + "exclude": [ + "test" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/caolan/async.git" + }, + "scripts": { + "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", + "coveralls": "npm run coverage && nyc report --reporter=text-lcov | coveralls", + "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", + "lint": "eslint --fix lib/ test/ perf/memory.js perf/suites.js perf/benchmark.js support/build/ support/*.js karma.conf.js", + "mocha-browser-test": "karma start", + "mocha-node-test": "mocha", + "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", + "test": "npm run lint && npm run mocha-node-test" + }, + "version": "3.2.0" +} diff --git a/build/node_modules/async/parallel.js b/build/node_modules/async/parallel.js new file mode 100644 index 00000000..a36b0458 --- /dev/null +++ b/build/node_modules/async/parallel.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallel; + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _parallel2 = require('./internal/parallel'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ +function parallel(tasks, callback) { + return (0, _parallel3.default)(_eachOf2.default, tasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/parallelLimit.js b/build/node_modules/async/parallelLimit.js new file mode 100644 index 00000000..f01a6188 --- /dev/null +++ b/build/node_modules/async/parallelLimit.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallelLimit; + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _parallel = require('./internal/parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/priorityQueue.js b/build/node_modules/async/priorityQueue.js new file mode 100644 index 00000000..ed0e6b6b --- /dev/null +++ b/build/node_modules/async/priorityQueue.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + // Start with a normal queue + var q = (0, _queue2.default)(worker, concurrency); + + q._tasks = new _Heap2.default(); + + // Override push to accept second parameter representing priority + q.push = function (data, priority = 0, callback = () => {}) { + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!Array.isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return (0, _setImmediate2.default)(() => q.drain()); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority, + callback + }; + + q._tasks.push(item); + } + + (0, _setImmediate2.default)(q.process); + }; + + // Remove unshift function + delete q.unshift; + + return q; +}; + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _Heap = require('./internal/Heap'); + +var _Heap2 = _interopRequireDefault(_Heap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ \ No newline at end of file diff --git a/build/node_modules/async/queue.js b/build/node_modules/async/queue.js new file mode 100644 index 00000000..3550a0e2 --- /dev/null +++ b/build/node_modules/async/queue.js @@ -0,0 +1,167 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + var _worker = (0, _wrapAsync2.default)(worker); + return (0, _queue2.default)((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +}; + +var _queue = require('./internal/queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = aync.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ \ No newline at end of file diff --git a/build/node_modules/async/race.js b/build/node_modules/async/race.js new file mode 100644 index 00000000..3003064c --- /dev/null +++ b/build/node_modules/async/race.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + (0, _wrapAsync2.default)(tasks[i])(callback); + } +} + +exports.default = (0, _awaitify2.default)(race, 2); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/reduce.js b/build/node_modules/async/reduce.js new file mode 100644 index 00000000..e7816830 --- /dev/null +++ b/build/node_modules/async/reduce.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reduce([1,2,3], 0, function(memo, item, callback) { + * // pointless async: + * process.nextTick(function() { + * callback(null, memo + item) + * }); + * }, function(err, result) { + * // result is now equal to the last value of memo, which is 6 + * }); + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/reduceRight.js b/build/node_modules/async/reduceRight.js new file mode 100644 index 00000000..e3da2a4d --- /dev/null +++ b/build/node_modules/async/reduceRight.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/reflect.js b/build/node_modules/async/reflect.js new file mode 100644 index 00000000..937937c8 --- /dev/null +++ b/build/node_modules/async/reflect.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflect; + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = (0, _wrapAsync2.default)(fn); + return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0) { + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/reflectAll.js b/build/node_modules/async/reflectAll.js new file mode 100644 index 00000000..112a307c --- /dev/null +++ b/build/node_modules/async/reflectAll.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflectAll; + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(_reflect2.default); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = _reflect2.default.call(this, tasks[key]); + }); + } + return results; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/reject.js b/build/node_modules/async/reject.js new file mode 100644 index 00000000..12f175a0 --- /dev/null +++ b/build/node_modules/async/reject.js @@ -0,0 +1,53 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ +function reject(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(reject, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/rejectLimit.js b/build/node_modules/async/rejectLimit.js new file mode 100644 index 00000000..9f0bb3fb --- /dev/null +++ b/build/node_modules/async/rejectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit(coll, limit, iteratee, callback) { + return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/rejectSeries.js b/build/node_modules/async/rejectSeries.js new file mode 100644 index 00000000..7803a14b --- /dev/null +++ b/build/node_modules/async/rejectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/retry.js b/build/node_modules/async/retry.js new file mode 100644 index 00000000..a8f67eea --- /dev/null +++ b/build/node_modules/async/retry.js @@ -0,0 +1,159 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retry; + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function constant(value) { + return function () { + return value; + }; +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || (0, _promiseCallback.promiseCallback)(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || (0, _promiseCallback.promiseCallback)(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = (0, _wrapAsync2.default)(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return; + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/retryable.js b/build/node_modules/async/retryable.js new file mode 100644 index 00000000..cdfa866d --- /dev/null +++ b/build/node_modules/async/retryable.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retryable; + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = opts && opts.arity || task.length; + if ((0, _wrapAsync.isAsync)(task)) { + arity += 1; + } + var _task = (0, _wrapAsync2.default)(task); + return (0, _initialParams2.default)((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = (0, _promiseCallback.promiseCallback)(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); + + return callback[_promiseCallback.PROMISE_SYMBOL]; + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/select.js b/build/node_modules/async/select.js new file mode 100644 index 00000000..fadd16a7 --- /dev/null +++ b/build/node_modules/async/select.js @@ -0,0 +1,53 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/selectLimit.js b/build/node_modules/async/selectLimit.js new file mode 100644 index 00000000..7fdee119 --- /dev/null +++ b/build/node_modules/async/selectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/selectSeries.js b/build/node_modules/async/selectSeries.js new file mode 100644 index 00000000..ee8bde9d --- /dev/null +++ b/build/node_modules/async/selectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/seq.js b/build/node_modules/async/seq.js new file mode 100644 index 00000000..cd0a0b5d --- /dev/null +++ b/build/node_modules/async/seq.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = seq; + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(_wrapAsync2.default); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = (0, _promiseCallback.promiseCallback)(); + } + + (0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, (err, results) => cb(err, ...results)); + + return cb[_promiseCallback.PROMISE_SYMBOL]; + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/series.js b/build/node_modules/async/series.js new file mode 100644 index 00000000..e3c29545 --- /dev/null +++ b/build/node_modules/async/series.js @@ -0,0 +1,86 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = series; + +var _parallel2 = require('./internal/parallel'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ +function series(tasks, callback) { + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/setImmediate.js b/build/node_modules/async/setImmediate.js new file mode 100644 index 00000000..e52f7c54 --- /dev/null +++ b/build/node_modules/async/setImmediate.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `setImmediate`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name setImmediate + * @static + * @memberOf module:Utils + * @method + * @see [async.nextTick]{@link module:Utils.nextTick} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +exports.default = _setImmediate2.default; +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/some.js b/build/node_modules/async/some.js new file mode 100644 index 00000000..0e987a16 --- /dev/null +++ b/build/node_modules/async/some.js @@ -0,0 +1,56 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/someLimit.js b/build/node_modules/async/someLimit.js new file mode 100644 index 00000000..22b60dbb --- /dev/null +++ b/build/node_modules/async/someLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/someSeries.js b/build/node_modules/async/someSeries.js new file mode 100644 index 00000000..7f7f801f --- /dev/null +++ b/build/node_modules/async/someSeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/sortBy.js b/build/node_modules/async/sortBy.js new file mode 100644 index 00000000..da0075e6 --- /dev/null +++ b/build/node_modules/async/sortBy.js @@ -0,0 +1,88 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ +function sortBy(coll, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _map2.default)(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, { value: x, criteria }); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +exports.default = (0, _awaitify2.default)(sortBy, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/timeout.js b/build/node_modules/async/timeout.js new file mode 100644 index 00000000..8bbfc3a8 --- /dev/null +++ b/build/node_modules/async/timeout.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timeout; + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = (0, _wrapAsync2.default)(asyncFn); + + return (0, _initialParams2.default)((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/times.js b/build/node_modules/async/times.js new file mode 100644 index 00000000..f294d025 --- /dev/null +++ b/build/node_modules/async/times.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = times; + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, Infinity, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/timesLimit.js b/build/node_modules/async/timesLimit.js new file mode 100644 index 00000000..38d776a3 --- /dev/null +++ b/build/node_modules/async/timesLimit.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesLimit; + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _range = require('./internal/range'); + +var _range2 = _interopRequireDefault(_range); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/timesSeries.js b/build/node_modules/async/timesSeries.js new file mode 100644 index 00000000..267a6389 --- /dev/null +++ b/build/node_modules/async/timesSeries.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesSeries; + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, 1, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/transform.js b/build/node_modules/async/transform.js new file mode 100644 index 00000000..9483c2bd --- /dev/null +++ b/build/node_modules/async/transform.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = transform; + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc[index] = item * 2 + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ +function transform(coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + (0, _eachOf2.default)(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/tryEach.js b/build/node_modules/async/tryEach.js new file mode 100644 index 00000000..7544d64b --- /dev/null +++ b/build/node_modules/async/tryEach.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return (0, _eachSeries2.default)(tasks, (task, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +exports.default = (0, _awaitify2.default)(tryEach); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/unmemoize.js b/build/node_modules/async/unmemoize.js new file mode 100644 index 00000000..47a92b42 --- /dev/null +++ b/build/node_modules/async/unmemoize.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = unmemoize; +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/build/node_modules/async/until.js b/build/node_modules/async/until.js new file mode 100644 index 00000000..67ff1dea --- /dev/null +++ b/build/node_modules/async/until.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = until; + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(page, cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/waterfall.js b/build/node_modules/async/waterfall.js new file mode 100644 index 00000000..9aeb915a --- /dev/null +++ b/build/node_modules/async/waterfall.js @@ -0,0 +1,105 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); + task(...args, (0, _onlyOnce2.default)(next)); + } + + function next(err, ...args) { + if (err === false) return; + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +exports.default = (0, _awaitify2.default)(waterfall); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/whilst.js b/build/node_modules/async/whilst.js new file mode 100644 index 00000000..4f4a39b4 --- /dev/null +++ b/build/node_modules/async/whilst.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/async/wrapSync.js b/build/node_modules/async/wrapSync.js new file mode 100644 index 00000000..23623175 --- /dev/null +++ b/build/node_modules/async/wrapSync.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports['default']; \ No newline at end of file diff --git a/build/node_modules/color-convert/CHANGELOG.md b/build/node_modules/color-convert/CHANGELOG.md new file mode 100644 index 00000000..0a7bce4f --- /dev/null +++ b/build/node_modules/color-convert/CHANGELOG.md @@ -0,0 +1,54 @@ +# 1.0.0 - 2016-01-07 + +- Removed: unused speed test +- Added: Automatic routing between previously unsupported conversions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `convert()` class +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: all functions to lookup dictionary +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: `ansi` to `ansi256` +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Fixed: argument grouping for functions requiring only one argument +([#27](https://github.com/Qix-/color-convert/pull/27)) + +# 0.6.0 - 2015-07-23 + +- Added: methods to handle +[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: + - rgb2ansi16 + - rgb2ansi + - hsl2ansi16 + - hsl2ansi + - hsv2ansi16 + - hsv2ansi + - hwb2ansi16 + - hwb2ansi + - cmyk2ansi16 + - cmyk2ansi + - keyword2ansi16 + - keyword2ansi + - ansi162rgb + - ansi162hsl + - ansi162hsv + - ansi162hwb + - ansi162cmyk + - ansi162keyword + - ansi2rgb + - ansi2hsl + - ansi2hsv + - ansi2hwb + - ansi2cmyk + - ansi2keyword +([#18](https://github.com/harthur/color-convert/pull/18)) + +# 0.5.3 - 2015-06-02 + +- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` +([#15](https://github.com/harthur/color-convert/issues/15)) + +--- + +Check out commit logs for older releases diff --git a/build/node_modules/color-convert/LICENSE b/build/node_modules/color-convert/LICENSE new file mode 100644 index 00000000..5b4c386f --- /dev/null +++ b/build/node_modules/color-convert/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011-2016 Heather Arthur + +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. + diff --git a/build/node_modules/color-convert/README.md b/build/node_modules/color-convert/README.md new file mode 100644 index 00000000..d4b08fc3 --- /dev/null +++ b/build/node_modules/color-convert/README.md @@ -0,0 +1,68 @@ +# color-convert + +[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) + +Color-convert is a color conversion library for JavaScript and node. +It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): + +```js +var convert = require('color-convert'); + +convert.rgb.hsl(140, 200, 100); // [96, 48, 59] +convert.keyword.rgb('blue'); // [0, 0, 255] + +var rgbChannels = convert.rgb.channels; // 3 +var cmykChannels = convert.cmyk.channels; // 4 +var ansiChannels = convert.ansi16.channels; // 1 +``` + +# Install + +```console +$ npm install color-convert +``` + +# API + +Simply get the property of the _from_ and _to_ conversion that you're looking for. + +All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. + +All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). + +```js +var convert = require('color-convert'); + +// Hex to LAB +convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] +convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] + +// RGB to CMYK +convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] +convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] +``` + +### Arrays +All functions that accept multiple arguments also support passing an array. + +Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) + +```js +var convert = require('color-convert'); + +convert.rgb.hex(123, 45, 67); // '7B2D43' +convert.rgb.hex([123, 45, 67]); // '7B2D43' +``` + +## Routing + +Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). + +Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). + +# Contribute + +If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. + +# License +Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). diff --git a/build/node_modules/color-convert/conversions.js b/build/node_modules/color-convert/conversions.js new file mode 100644 index 00000000..32172007 --- /dev/null +++ b/build/node_modules/color-convert/conversions.js @@ -0,0 +1,868 @@ +/* MIT license */ +var cssKeywords = require('color-name'); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; diff --git a/build/node_modules/color-convert/index.js b/build/node_modules/color-convert/index.js new file mode 100644 index 00000000..e65b5d77 --- /dev/null +++ b/build/node_modules/color-convert/index.js @@ -0,0 +1,78 @@ +var conversions = require('./conversions'); +var route = require('./route'); + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; diff --git a/build/node_modules/color-convert/package.json b/build/node_modules/color-convert/package.json new file mode 100644 index 00000000..bf83564e --- /dev/null +++ b/build/node_modules/color-convert/package.json @@ -0,0 +1,81 @@ +{ + "_from": "color-convert@^1.9.1", + "_id": "color-convert@1.9.3", + "_inBundle": false, + "_integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "_location": "/color-convert", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "color-convert@^1.9.1", + "name": "color-convert", + "escapedName": "color-convert", + "rawSpec": "^1.9.1", + "saveSpec": null, + "fetchSpec": "^1.9.1" + }, + "_requiredBy": [ + "/color" + ], + "_resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "_shasum": "bb71850690e1f136567de629d2d5471deda4c1e8", + "_spec": "color-convert@^1.9.1", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/color", + "author": { + "name": "Heather Arthur", + "email": "fayearthur@gmail.com" + }, + "bugs": { + "url": "https://github.com/Qix-/color-convert/issues" + }, + "bundleDependencies": false, + "dependencies": { + "color-name": "1.1.3" + }, + "deprecated": false, + "description": "Plain color conversion functions", + "devDependencies": { + "chalk": "1.1.1", + "xo": "0.11.2" + }, + "files": [ + "index.js", + "conversions.js", + "css-keywords.js", + "route.js" + ], + "homepage": "https://github.com/Qix-/color-convert#readme", + "keywords": [ + "color", + "colour", + "convert", + "converter", + "conversion", + "rgb", + "hsl", + "hsv", + "hwb", + "cmyk", + "ansi", + "ansi16" + ], + "license": "MIT", + "name": "color-convert", + "repository": { + "type": "git", + "url": "git+https://github.com/Qix-/color-convert.git" + }, + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "version": "1.9.3", + "xo": { + "rules": { + "default-case": 0, + "no-inline-comments": 0, + "operator-linebreak": 0 + } + } +} diff --git a/build/node_modules/color-convert/route.js b/build/node_modules/color-convert/route.js new file mode 100644 index 00000000..0a1fdea6 --- /dev/null +++ b/build/node_modules/color-convert/route.js @@ -0,0 +1,97 @@ +var conversions = require('./conversions'); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + diff --git a/build/node_modules/color-name/.eslintrc.json b/build/node_modules/color-name/.eslintrc.json new file mode 100644 index 00000000..c50c2504 --- /dev/null +++ b/build/node_modules/color-name/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/build/node_modules/color-name/.npmignore b/build/node_modules/color-name/.npmignore new file mode 100644 index 00000000..f9f28164 --- /dev/null +++ b/build/node_modules/color-name/.npmignore @@ -0,0 +1,107 @@ +//this will affect all the git repos +git config --global core.excludesfile ~/.gitignore + + +//update files since .ignore won't if already tracked +git rm --cached + +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +# Icon? +ehthumbs.db +Thumbs.db +.cache +.project +.settings +.tmproj +*.esproj +nbproject + +# Numerous always-ignore extensions # +##################################### +*.diff +*.err +*.orig +*.rej +*.swn +*.swo +*.swp +*.vi +*~ +*.sass-cache +*.grunt +*.tmp + +# Dreamweaver added files # +########################### +_notes +dwsync.xml + +# Komodo # +########################### +*.komodoproject +.komodotools + +# Node # +##################### +node_modules + +# Bower # +##################### +bower_components + +# Folders to ignore # +##################### +.hg +.svn +.CVS +intermediate +publish +.idea +.graphics +_test +_archive +uploads +tmp + +# Vim files to ignore # +####################### +.VimballRecord +.netrwhist + +bundle.* + +_demo \ No newline at end of file diff --git a/build/node_modules/color-name/LICENSE b/build/node_modules/color-name/LICENSE new file mode 100644 index 00000000..c6b10012 --- /dev/null +++ b/build/node_modules/color-name/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +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. \ No newline at end of file diff --git a/build/node_modules/color-name/README.md b/build/node_modules/color-name/README.md new file mode 100644 index 00000000..932b9791 --- /dev/null +++ b/build/node_modules/color-name/README.md @@ -0,0 +1,11 @@ +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. + +[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) + + +```js +var colors = require('color-name'); +colors.red //[255,0,0] +``` + + diff --git a/build/node_modules/color-name/index.js b/build/node_modules/color-name/index.js new file mode 100644 index 00000000..b7c198a6 --- /dev/null +++ b/build/node_modules/color-name/index.js @@ -0,0 +1,152 @@ +'use strict' + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; diff --git a/build/node_modules/color-name/package.json b/build/node_modules/color-name/package.json new file mode 100644 index 00000000..7fec7b3d --- /dev/null +++ b/build/node_modules/color-name/package.json @@ -0,0 +1,54 @@ +{ + "_from": "color-name@1.1.3", + "_id": "color-name@1.1.3", + "_inBundle": false, + "_integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "_location": "/color-name", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "color-name@1.1.3", + "name": "color-name", + "escapedName": "color-name", + "rawSpec": "1.1.3", + "saveSpec": null, + "fetchSpec": "1.1.3" + }, + "_requiredBy": [ + "/color-convert", + "/color-string" + ], + "_resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "_shasum": "a7d0558bd89c42f795dd42328f740831ca53bc25", + "_spec": "color-name@1.1.3", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/color-convert", + "author": { + "name": "DY", + "email": "dfcreative@gmail.com" + }, + "bugs": { + "url": "https://github.com/dfcreative/color-name/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A list of color names and its values", + "homepage": "https://github.com/dfcreative/color-name", + "keywords": [ + "color-name", + "color", + "color-keyword", + "keyword" + ], + "license": "MIT", + "main": "index.js", + "name": "color-name", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/dfcreative/color-name.git" + }, + "scripts": { + "test": "node test.js" + }, + "version": "1.1.3" +} diff --git a/build/node_modules/color-name/test.js b/build/node_modules/color-name/test.js new file mode 100644 index 00000000..6e6bf30b --- /dev/null +++ b/build/node_modules/color-name/test.js @@ -0,0 +1,7 @@ +'use strict' + +var names = require('./'); +var assert = require('assert'); + +assert.deepEqual(names.red, [255,0,0]); +assert.deepEqual(names.aliceblue, [240,248,255]); diff --git a/build/node_modules/color-string/CHANGELOG.md b/build/node_modules/color-string/CHANGELOG.md new file mode 100644 index 00000000..c537fa61 --- /dev/null +++ b/build/node_modules/color-string/CHANGELOG.md @@ -0,0 +1,18 @@ +# 0.4.0 + +- Changed: Invalid conversions now return `null` instead of `undefined` +- Changed: Moved to XO standard +- Fixed: a few details in package.json +- Fixed: readme output regarding wrapped hue values ([#21](https://github.com/MoOx/color-string/pull/21)) + +# 0.3.0 + +- Fixed: HSL alpha channel ([#16](https://github.com/harthur/color-string/pull/16)) +- Fixed: ability to parse signed number ([#15](https://github.com/harthur/color-string/pull/15)) +- Removed: component.json +- Removed: browser build +- Added: license field to package.json ([#17](https://github.com/harthur/color-string/pull/17)) + +--- + +Check out commit logs for earlier releases diff --git a/build/node_modules/color-string/LICENSE b/build/node_modules/color-string/LICENSE new file mode 100644 index 00000000..a8b08d4f --- /dev/null +++ b/build/node_modules/color-string/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Heather Arthur + +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. + diff --git a/build/node_modules/color-string/README.md b/build/node_modules/color-string/README.md new file mode 100644 index 00000000..3469d7ae --- /dev/null +++ b/build/node_modules/color-string/README.md @@ -0,0 +1,58 @@ +# color-string + +[![Build Status](https://travis-ci.org/Qix-/color-string.svg?branch=master)](https://travis-ci.org/Qix-/color-string) + +> library for parsing and generating CSS color strings. + +## Install + +With [npm](http://npmjs.org/): + +```console +$ npm install color-string +``` + +## Usage + +### Parsing + +```js +colorString.get('#FFF') // {model: 'rgb', value: [255, 255, 255, 1]} +colorString.get('#FFFA') // {model: 'rgb', value: [255, 255, 255, 0.67]} +colorString.get('#FFFFFFAA') // {model: 'rgb', value: [255, 255, 255, 0.67]} +colorString.get('hsl(360, 100%, 50%)') // {model: 'hsl', value: [0, 100, 50, 1]} +colorString.get('hwb(60, 3%, 60%)') // {model: 'hwb', value: [60, 3, 60, 1]} + +colorString.get.rgb('#FFF') // [255, 255, 255, 1] +colorString.get.rgb('blue') // [0, 0, 255, 1] +colorString.get.rgb('rgba(200, 60, 60, 0.3)') // [200, 60, 60, 0.3] +colorString.get.rgb('rgb(200, 200, 200)') // [200, 200, 200, 1] + +colorString.get.hsl('hsl(360, 100%, 50%)') // [0, 100, 50, 1] +colorString.get.hsl('hsla(360, 60%, 50%, 0.4)') // [0, 60, 50, 0.4] + +colorString.get.hwb('hwb(60, 3%, 60%)') // [60, 3, 60, 1] +colorString.get.hwb('hwb(60, 3%, 60%, 0.6)') // [60, 3, 60, 0.6] + +colorString.get.rgb('invalid color string') // null +``` + +### Generation + +```js +colorString.to.hex([255, 255, 255]) // "#FFFFFF" +colorString.to.hex([0, 0, 255, 0.4]) // "#0000FF66" +colorString.to.hex([0, 0, 255], 0.4) // "#0000FF66" +colorString.to.rgb([255, 255, 255]) // "rgb(255, 255, 255)" +colorString.to.rgb([0, 0, 255, 0.4]) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb([0, 0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb.percent([0, 0, 255]) // "rgb(0%, 0%, 100%)" +colorString.to.keyword([255, 255, 0]) // "yellow" +colorString.to.hsl([360, 100, 100]) // "hsl(360, 100%, 100%)" +colorString.to.hwb([50, 3, 15]) // "hwb(50, 3%, 15%)" + +// all functions also support swizzling +colorString.to.rgb(0, [0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb([0, 0], [255], 0.4) // "rgba(0, 0, 255, 0.4)" +colorString.to.rgb([0], 0, [255, 0.4]) // "rgba(0, 0, 255, 0.4)" +``` diff --git a/build/node_modules/color-string/index.js b/build/node_modules/color-string/index.js new file mode 100644 index 00000000..25fba851 --- /dev/null +++ b/build/node_modules/color-string/index.js @@ -0,0 +1,234 @@ +/* MIT license */ +var colorNames = require('color-name'); +var swizzle = require('simple-swizzle'); + +var reverseNames = {}; + +// create a list of reverse color names +for (var name in colorNames) { + if (colorNames.hasOwnProperty(name)) { + reverseNames[colorNames[name]] = name; + } +} + +var cs = module.exports = { + to: {}, + get: {} +}; + +cs.get = function (string) { + var prefix = string.substring(0, 3).toLowerCase(); + var val; + var model; + switch (prefix) { + case 'hsl': + val = cs.get.hsl(string); + model = 'hsl'; + break; + case 'hwb': + val = cs.get.hwb(string); + model = 'hwb'; + break; + default: + val = cs.get.rgb(string); + model = 'rgb'; + break; + } + + if (!val) { + return null; + } + + return {model: model, value: val}; +}; + +cs.get.rgb = function (string) { + if (!string) { + return null; + } + + var abbr = /^#([a-f0-9]{3,4})$/i; + var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; + var rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/; + var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/; + var keyword = /(\D+)/; + + var rgb = [0, 0, 0, 1]; + var match; + var i; + var hexAlpha; + + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + + for (i = 0; i < 3; i++) { + // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 + var i2 = i * 2; + rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); + } + + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i] + match[i], 16); + } + + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i + 1], 0); + } + + if (match[4]) { + rgb[3] = parseFloat(match[4]); + } + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); + } + + if (match[4]) { + rgb[3] = parseFloat(match[4]); + } + } else if (match = string.match(keyword)) { + if (match[1] === 'transparent') { + return [0, 0, 0, 0]; + } + + rgb = colorNames[match[1]]; + + if (!rgb) { + return null; + } + + rgb[3] = 1; + + return rgb; + } else { + return null; + } + + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); + } + rgb[3] = clamp(rgb[3], 0, 1); + + return rgb; +}; + +cs.get.hsl = function (string) { + if (!string) { + return null; + } + + var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/; + var match = string.match(hsl); + + if (match) { + var alpha = parseFloat(match[4]); + var h = (parseFloat(match[1]) + 360) % 360; + var s = clamp(parseFloat(match[2]), 0, 100); + var l = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + + return [h, s, l, a]; + } + + return null; +}; + +cs.get.hwb = function (string) { + if (!string) { + return null; + } + + var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/; + var match = string.match(hwb); + + if (match) { + var alpha = parseFloat(match[4]); + var h = ((parseFloat(match[1]) % 360) + 360) % 360; + var w = clamp(parseFloat(match[2]), 0, 100); + var b = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w, b, a]; + } + + return null; +}; + +cs.to.hex = function () { + var rgba = swizzle(arguments); + + return ( + '#' + + hexDouble(rgba[0]) + + hexDouble(rgba[1]) + + hexDouble(rgba[2]) + + (rgba[3] < 1 + ? (hexDouble(Math.round(rgba[3] * 255))) + : '') + ); +}; + +cs.to.rgb = function () { + var rgba = swizzle(arguments); + + return rgba.length < 4 || rgba[3] === 1 + ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')' + : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')'; +}; + +cs.to.rgb.percent = function () { + var rgba = swizzle(arguments); + + var r = Math.round(rgba[0] / 255 * 100); + var g = Math.round(rgba[1] / 255 * 100); + var b = Math.round(rgba[2] / 255 * 100); + + return rgba.length < 4 || rgba[3] === 1 + ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)' + : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')'; +}; + +cs.to.hsl = function () { + var hsla = swizzle(arguments); + return hsla.length < 4 || hsla[3] === 1 + ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)' + : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')'; +}; + +// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax +// (hwb have alpha optional & 1 is default value) +cs.to.hwb = function () { + var hwba = swizzle(arguments); + + var a = ''; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ', ' + hwba[3]; + } + + return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')'; +}; + +cs.to.keyword = function (rgb) { + return reverseNames[rgb.slice(0, 3)]; +}; + +// helpers +function clamp(num, min, max) { + return Math.min(Math.max(min, num), max); +} + +function hexDouble(num) { + var str = num.toString(16).toUpperCase(); + return (str.length < 2) ? '0' + str : str; +} diff --git a/build/node_modules/color-string/package.json b/build/node_modules/color-string/package.json new file mode 100644 index 00000000..3e18aa8e --- /dev/null +++ b/build/node_modules/color-string/package.json @@ -0,0 +1,81 @@ +{ + "_from": "color-string@^1.5.2", + "_id": "color-string@1.5.5", + "_inBundle": false, + "_integrity": "sha512-jgIoum0OfQfq9Whcfc2z/VhCNcmQjWbey6qBX0vqt7YICflUmBCh9E9CiQD5GSJ+Uehixm3NUwHVhqUAWRivZg==", + "_location": "/color-string", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "color-string@^1.5.2", + "name": "color-string", + "escapedName": "color-string", + "rawSpec": "^1.5.2", + "saveSpec": null, + "fetchSpec": "^1.5.2" + }, + "_requiredBy": [ + "/color" + ], + "_resolved": "https://registry.npmjs.org/color-string/-/color-string-1.5.5.tgz", + "_shasum": "65474a8f0e7439625f3d27a6a19d89fc45223014", + "_spec": "color-string@^1.5.2", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/color", + "author": { + "name": "Heather Arthur", + "email": "fayearthur@gmail.com" + }, + "bugs": { + "url": "https://github.com/Qix-/color-string/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Maxime Thirouin" + }, + { + "name": "Dyma Ywanov", + "email": "dfcreative@gmail.com" + }, + { + "name": "Josh Junon" + } + ], + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + }, + "deprecated": false, + "description": "Parser and generator for CSS color strings", + "devDependencies": { + "xo": "^0.12.1" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/Qix-/color-string#readme", + "keywords": [ + "color", + "colour", + "rgb", + "css" + ], + "license": "MIT", + "name": "color-string", + "repository": { + "type": "git", + "url": "git+https://github.com/Qix-/color-string.git" + }, + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "version": "1.5.5", + "xo": { + "rules": { + "no-cond-assign": 0, + "operator-linebreak": 0 + } + } +} diff --git a/build/node_modules/color/LICENSE b/build/node_modules/color/LICENSE new file mode 100644 index 00000000..68c864ee --- /dev/null +++ b/build/node_modules/color/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2012 Heather Arthur + +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. + diff --git a/build/node_modules/color/README.md b/build/node_modules/color/README.md new file mode 100644 index 00000000..af78eb82 --- /dev/null +++ b/build/node_modules/color/README.md @@ -0,0 +1,114 @@ +# color [![Build Status](https://travis-ci.org/Qix-/color.svg?branch=master)](https://travis-ci.org/Qix-/color) + +> JavaScript library for immutable color conversion and manipulation with support for CSS color strings. + +```js +var color = Color('#7743CE').alpha(0.5).lighten(0.5); +console.log(color.hsl().string()); // 'hsla(262, 59%, 81%, 0.5)' + +console.log(color.cmyk().round().array()); // [ 16, 25, 0, 8, 0.5 ] + +console.log(color.ansi256().object()); // { ansi256: 183, alpha: 0.5 } +``` + +## Install +```console +$ npm install color +``` + +## Usage +```js +var Color = require('color'); +``` + +### Constructors +```js +var color = Color('rgb(255, 255, 255)') +var color = Color({r: 255, g: 255, b: 255}) +var color = Color.rgb(255, 255, 255) +var color = Color.rgb([255, 255, 255]) +``` + +Set the values for individual channels with `alpha`, `red`, `green`, `blue`, `hue`, `saturationl` (hsl), `saturationv` (hsv), `lightness`, `whiteness`, `blackness`, `cyan`, `magenta`, `yellow`, `black` + +String constructors are handled by [color-string](https://www.npmjs.com/package/color-string) + +### Getters +```js +color.hsl(); +``` +Convert a color to a different space (`hsl()`, `cmyk()`, etc.). + +```js +color.object(); // {r: 255, g: 255, b: 255} +``` +Get a hash of the color value. Reflects the color's current model (see above). + +```js +color.rgb().array() // [255, 255, 255] +``` +Get an array of the values with `array()`. Reflects the color's current model (see above). + +```js +color.rgbNumber() // 16777215 (0xffffff) +``` +Get the rgb number value. + +```js +color.red() // 255 +``` +Get the value for an individual channel. + +### CSS Strings +```js +color.hsl().string() // 'hsl(320, 50%, 100%)' +``` + +Calling `.string()` with a number rounds the numbers to that decimal place. It defaults to 1. + +### Luminosity +```js +color.luminosity(); // 0.412 +``` +The [WCAG luminosity](http://www.w3.org/TR/WCAG20/#relativeluminancedef) of the color. 0 is black, 1 is white. + +```js +color.contrast(Color("blue")) // 12 +``` +The [WCAG contrast ratio](http://www.w3.org/TR/WCAG20/#contrast-ratiodef) to another color, from 1 (same color) to 21 (contrast b/w white and black). + +```js +color.isLight(); // true +color.isDark(); // false +``` +Get whether the color is "light" or "dark", useful for deciding text color. + +### Manipulation +```js +color.negate() // rgb(0, 100, 255) -> rgb(255, 155, 0) + +color.lighten(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%) +color.darken(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%) + +color.saturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%) +color.desaturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%) +color.grayscale() // #5CBF54 -> #969696 + +color.whiten(0.5) // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%) +color.blacken(0.5) // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%) + +color.fade(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4) +color.opaquer(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0) + +color.rotate(180) // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%) +color.rotate(-90) // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%) + +color.mix(Color("yellow")) // cyan -> rgb(128, 255, 128) +color.mix(Color("yellow"), 0.3) // cyan -> rgb(77, 255, 179) + +// chaining +color.green(100).grayscale().lighten(0.6) +``` + +## Propers +The API was inspired by [color-js](https://github.com/brehaut/color-js). Manipulation functions by CSS tools like Sass, LESS, and Stylus. diff --git a/build/node_modules/color/index.js b/build/node_modules/color/index.js new file mode 100644 index 00000000..3f978925 --- /dev/null +++ b/build/node_modules/color/index.js @@ -0,0 +1,479 @@ +'use strict'; + +var colorString = require('color-string'); +var convert = require('color-convert'); + +var _slice = [].slice; + +var skippedModels = [ + // to be honest, I don't really feel like keyword belongs in color convert, but eh. + 'keyword', + + // gray conflicts with some method names, and has its own method defined. + 'gray', + + // shouldn't really be in color-convert either... + 'hex' +]; + +var hashedModelKeys = {}; +Object.keys(convert).forEach(function (model) { + hashedModelKeys[_slice.call(convert[model].labels).sort().join('')] = model; +}); + +var limiters = {}; + +function Color(obj, model) { + if (!(this instanceof Color)) { + return new Color(obj, model); + } + + if (model && model in skippedModels) { + model = null; + } + + if (model && !(model in convert)) { + throw new Error('Unknown model: ' + model); + } + + var i; + var channels; + + if (!obj) { + this.model = 'rgb'; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (obj instanceof Color) { + this.model = obj.model; + this.color = obj.color.slice(); + this.valpha = obj.valpha; + } else if (typeof obj === 'string') { + var result = colorString.get(obj); + if (result === null) { + throw new Error('Unable to parse color from string: ' + obj); + } + + this.model = result.model; + channels = convert[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1; + } else if (obj.length) { + this.model = model || 'rgb'; + channels = convert[this.model].channels; + var newArr = _slice.call(obj, 0, channels); + this.color = zeroArray(newArr, channels); + this.valpha = typeof obj[channels] === 'number' ? obj[channels] : 1; + } else if (typeof obj === 'number') { + // this is always RGB - can be converted later on. + obj &= 0xFFFFFF; + this.model = 'rgb'; + this.color = [ + (obj >> 16) & 0xFF, + (obj >> 8) & 0xFF, + obj & 0xFF + ]; + this.valpha = 1; + } else { + this.valpha = 1; + + var keys = Object.keys(obj); + if ('alpha' in obj) { + keys.splice(keys.indexOf('alpha'), 1); + this.valpha = typeof obj.alpha === 'number' ? obj.alpha : 0; + } + + var hashedKeys = keys.sort().join(''); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error('Unable to parse color from object: ' + JSON.stringify(obj)); + } + + this.model = hashedModelKeys[hashedKeys]; + + var labels = convert[this.model].labels; + var color = []; + for (i = 0; i < labels.length; i++) { + color.push(obj[labels[i]]); + } + + this.color = zeroArray(color); + } + + // perform limitations (clamping, etc.) + if (limiters[this.model]) { + channels = convert[this.model].channels; + for (i = 0; i < channels; i++) { + var limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } + } + } + + this.valpha = Math.max(0, Math.min(1, this.valpha)); + + if (Object.freeze) { + Object.freeze(this); + } +} + +Color.prototype = { + toString: function () { + return this.string(); + }, + + toJSON: function () { + return this[this.model](); + }, + + string: function (places) { + var self = this.model in colorString.to ? this : this.rgb(); + self = self.round(typeof places === 'number' ? places : 1); + var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha); + return colorString.to[self.model](args); + }, + + percentString: function (places) { + var self = this.rgb().round(typeof places === 'number' ? places : 1); + var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha); + return colorString.to.rgb.percent(args); + }, + + array: function () { + return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha); + }, + + object: function () { + var result = {}; + var channels = convert[this.model].channels; + var labels = convert[this.model].labels; + + for (var i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; + } + + if (this.valpha !== 1) { + result.alpha = this.valpha; + } + + return result; + }, + + unitArray: function () { + var rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + + if (this.valpha !== 1) { + rgb.push(this.valpha); + } + + return rgb; + }, + + unitObject: function () { + var rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + + if (this.valpha !== 1) { + rgb.alpha = this.valpha; + } + + return rgb; + }, + + round: function (places) { + places = Math.max(places || 0, 0); + return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model); + }, + + alpha: function (val) { + if (arguments.length) { + return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model); + } + + return this.valpha; + }, + + // rgb + red: getset('rgb', 0, maxfn(255)), + green: getset('rgb', 1, maxfn(255)), + blue: getset('rgb', 2, maxfn(255)), + + hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, function (val) { return ((val % 360) + 360) % 360; }), // eslint-disable-line brace-style + + saturationl: getset('hsl', 1, maxfn(100)), + lightness: getset('hsl', 2, maxfn(100)), + + saturationv: getset('hsv', 1, maxfn(100)), + value: getset('hsv', 2, maxfn(100)), + + chroma: getset('hcg', 1, maxfn(100)), + gray: getset('hcg', 2, maxfn(100)), + + white: getset('hwb', 1, maxfn(100)), + wblack: getset('hwb', 2, maxfn(100)), + + cyan: getset('cmyk', 0, maxfn(100)), + magenta: getset('cmyk', 1, maxfn(100)), + yellow: getset('cmyk', 2, maxfn(100)), + black: getset('cmyk', 3, maxfn(100)), + + x: getset('xyz', 0, maxfn(100)), + y: getset('xyz', 1, maxfn(100)), + z: getset('xyz', 2, maxfn(100)), + + l: getset('lab', 0, maxfn(100)), + a: getset('lab', 1), + b: getset('lab', 2), + + keyword: function (val) { + if (arguments.length) { + return new Color(val); + } + + return convert[this.model].keyword(this.color); + }, + + hex: function (val) { + if (arguments.length) { + return new Color(val); + } + + return colorString.to.hex(this.rgb().round().color); + }, + + rgbNumber: function () { + var rgb = this.rgb().color; + return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF); + }, + + luminosity: function () { + // http://www.w3.org/TR/WCAG20/#relativeluminancedef + var rgb = this.rgb().color; + + var lum = []; + for (var i = 0; i < rgb.length; i++) { + var chan = rgb[i] / 255; + lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4); + } + + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + + contrast: function (color2) { + // http://www.w3.org/TR/WCAG20/#contrast-ratiodef + var lum1 = this.luminosity(); + var lum2 = color2.luminosity(); + + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + + return (lum2 + 0.05) / (lum1 + 0.05); + }, + + level: function (color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return 'AAA'; + } + + return (contrastRatio >= 4.5) ? 'AA' : ''; + }, + + isDark: function () { + // YIQ equation from http://24ways.org/2010/calculating-color-contrast + var rgb = this.rgb().color; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000; + return yiq < 128; + }, + + isLight: function () { + return !this.isDark(); + }, + + negate: function () { + var rgb = this.rgb(); + for (var i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; + } + return rgb; + }, + + lighten: function (ratio) { + var hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + + darken: function (ratio) { + var hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + + saturate: function (ratio) { + var hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + + desaturate: function (ratio) { + var hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + + whiten: function (ratio) { + var hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + + blacken: function (ratio) { + var hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + + grayscale: function () { + // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale + var rgb = this.rgb().color; + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(val, val, val); + }, + + fade: function (ratio) { + return this.alpha(this.valpha - (this.valpha * ratio)); + }, + + opaquer: function (ratio) { + return this.alpha(this.valpha + (this.valpha * ratio)); + }, + + rotate: function (degrees) { + var hsl = this.hsl(); + var hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + + mix: function (mixinColor, weight) { + // ported from sass implementation in C + // https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + var color1 = mixinColor.rgb(); + var color2 = this.rgb(); + var p = weight === undefined ? 0.5 : weight; + + var w = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + + var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + return Color.rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p)); + } +}; + +// model conversion methods and static constructors +Object.keys(convert).forEach(function (model) { + if (skippedModels.indexOf(model) !== -1) { + return; + } + + var channels = convert[model].channels; + + // conversion methods + Color.prototype[model] = function () { + if (this.model === model) { + return new Color(this); + } + + if (arguments.length) { + return new Color(arguments, model); + } + + var newAlpha = typeof arguments[channels] === 'number' ? channels : this.valpha; + return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model); + }; + + // 'static' construction methods + Color[model] = function (color) { + if (typeof color === 'number') { + color = zeroArray(_slice.call(arguments), channels); + } + return new Color(color, model); + }; +}); + +function roundTo(num, places) { + return Number(num.toFixed(places)); +} + +function roundToPlace(places) { + return function (num) { + return roundTo(num, places); + }; +} + +function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + + model.forEach(function (m) { + (limiters[m] || (limiters[m] = []))[channel] = modifier; + }); + + model = model[0]; + + return function (val) { + var result; + + if (arguments.length) { + if (modifier) { + val = modifier(val); + } + + result = this[model](); + result.color[channel] = val; + return result; + } + + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + + return result; + }; +} + +function maxfn(max) { + return function (v) { + return Math.max(0, Math.min(max, v)); + }; +} + +function assertArray(val) { + return Array.isArray(val) ? val : [val]; +} + +function zeroArray(arr, length) { + for (var i = 0; i < length; i++) { + if (typeof arr[i] !== 'number') { + arr[i] = 0; + } + } + + return arr; +} + +module.exports = Color; diff --git a/build/node_modules/color/package.json b/build/node_modules/color/package.json new file mode 100644 index 00000000..27ae821b --- /dev/null +++ b/build/node_modules/color/package.json @@ -0,0 +1,72 @@ +{ + "_from": "color@3.0.x", + "_id": "color@3.0.0", + "_inBundle": false, + "_integrity": "sha512-jCpd5+s0s0t7p3pHQKpnJ0TpQKKdleP71LWcA0aqiljpiuAkOSUFN/dyH8ZwF0hRmFlrIuRhufds1QyEP9EB+w==", + "_location": "/color", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "color@3.0.x", + "name": "color", + "escapedName": "color", + "rawSpec": "3.0.x", + "saveSpec": null, + "fetchSpec": "3.0.x" + }, + "_requiredBy": [ + "/colorspace" + ], + "_resolved": "https://registry.npmjs.org/color/-/color-3.0.0.tgz", + "_shasum": "d920b4328d534a3ac8295d68f7bd4ba6c427be9a", + "_spec": "color@3.0.x", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/colorspace", + "authors": [ + "Josh Junon ", + "Heather Arthur ", + "Maxime Thirouin" + ], + "bugs": { + "url": "https://github.com/Qix-/color/issues" + }, + "bundleDependencies": false, + "dependencies": { + "color-convert": "^1.9.1", + "color-string": "^1.5.2" + }, + "deprecated": false, + "description": "Color conversion and manipulation with CSS string support", + "devDependencies": { + "mocha": "^2.2.5", + "xo": "^0.12.1" + }, + "files": [ + "CHANGELOG.md", + "LICENSE", + "index.js" + ], + "homepage": "https://github.com/Qix-/color#readme", + "keywords": [ + "color", + "colour", + "css" + ], + "license": "MIT", + "name": "color", + "repository": { + "type": "git", + "url": "git+https://github.com/Qix-/color.git" + }, + "scripts": { + "pretest": "xo", + "test": "mocha" + }, + "version": "3.0.0", + "xo": { + "rules": { + "no-cond-assign": 0, + "new-cap": 0 + } + } +} diff --git a/build/node_modules/colors/LICENSE b/build/node_modules/colors/LICENSE new file mode 100644 index 00000000..17880ff0 --- /dev/null +++ b/build/node_modules/colors/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/build/node_modules/colors/README.md b/build/node_modules/colors/README.md new file mode 100644 index 00000000..fabe5589 --- /dev/null +++ b/build/node_modules/colors/README.md @@ -0,0 +1,221 @@ +# colors.js +[![Build Status](https://travis-ci.org/Marak/colors.js.svg?branch=master)](https://travis-ci.org/Marak/colors.js) +[![version](https://img.shields.io/npm/v/colors.svg)](https://www.npmjs.org/package/colors) +[![dependencies](https://david-dm.org/Marak/colors.js.svg)](https://david-dm.org/Marak/colors.js) +[![devDependencies](https://david-dm.org/Marak/colors.js/dev-status.svg)](https://david-dm.org/Marak/colors.js#info=devDependencies) + +Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback, and check the `develop` branch for the latest bleeding-edge updates. + +## get color and style in your node.js console + +![Demo](https://raw.githubusercontent.com/Marak/colors.js/master/screenshots/colors.png) + +## Installation + + npm install colors + +## colors and styles! + +### text colors + + - black + - red + - green + - yellow + - blue + - magenta + - cyan + - white + - gray + - grey + +### bright text colors + + - brightRed + - brightGreen + - brightYellow + - brightBlue + - brightMagenta + - brightCyan + - brightWhite + +### background colors + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + - bgGray + - bgGrey + +### bright background colors + + - bgBrightRed + - bgBrightGreen + - bgBrightYellow + - bgBrightBlue + - bgBrightMagenta + - bgBrightCyan + - bgBrightWhite + +### styles + + - reset + - bold + - dim + - italic + - underline + - inverse + - hidden + - strikethrough + +### extras + + - rainbow + - zebra + - america + - trap + - random + + +## Usage + +By popular demand, `colors` now ships with two types of usages! + +The super nifty way + +```js +var colors = require('colors'); + +console.log('hello'.green); // outputs green text +console.log('i like cake and pies'.underline.red) // outputs red underlined text +console.log('inverse the color'.inverse); // inverses the color +console.log('OMG Rainbows!'.rainbow); // rainbow +console.log('Run the trap'.trap); // Drops the bass + +``` + +or a slightly less nifty way which doesn't extend `String.prototype` + +```js +var colors = require('colors/safe'); + +console.log(colors.green('hello')); // outputs green text +console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text +console.log(colors.inverse('inverse the color')); // inverses the color +console.log(colors.rainbow('OMG Rainbows!')); // rainbow +console.log(colors.trap('Run the trap')); // Drops the bass + +``` + +I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way. + +If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object. + +## Enabling/Disabling Colors + +The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag: + +```bash +node myapp.js --no-color +node myapp.js --color=false + +node myapp.js --color +node myapp.js --color=true +node myapp.js --color=always + +FORCE_COLOR=1 node myapp.js +``` + +Or in code: + +```javascript +var colors = require('colors'); +colors.enable(); +colors.disable(); +``` + +## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data) + +```js +var name = 'Marak'; +console.log(colors.green('Hello %s'), name); +// outputs -> 'Hello Marak' +``` + +## Custom themes + +### Using standard API + +```js + +var colors = require('colors'); + +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); +``` + +### Using string safe API + +```js +var colors = require('colors/safe'); + +// set single property +var error = colors.red; +error('this is red'); + +// set theme +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +``` + +### Combining Colors + +```javascript +var colors = require('colors'); + +colors.setTheme({ + custom: ['red', 'underline'] +}); + +console.log('test'.custom); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.* diff --git a/build/node_modules/colors/examples/normal-usage.js b/build/node_modules/colors/examples/normal-usage.js new file mode 100644 index 00000000..822db1cc --- /dev/null +++ b/build/node_modules/colors/examples/normal-usage.js @@ -0,0 +1,82 @@ +var colors = require('../lib/index'); + +console.log('First some yellow text'.yellow); + +console.log('Underline that text'.yellow.underline); + +console.log('Make it bold and red'.red.bold); + +console.log(('Double Raindows All Day Long').rainbow); + +console.log('Drop the bass'.trap); + +console.log('DROP THE RAINBOW BASS'.trap.rainbow); + +// styles not widely supported +console.log('Chains are also cool.'.bold.italic.underline.red); + +// styles not widely supported +console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + + ' styles! '.yellow.bold); +console.log('Zebras are so fun!'.zebra); + +// +// Remark: .strikethrough may not work with Mac OS Terminal App +// +console.log('This is ' + 'not'.strikethrough + ' fun.'); + +console.log('Background color attack!'.black.bgWhite); +console.log('Use random styles on everything!'.random); +console.log('America, Heck Yeah!'.america); + +console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen); + +console.log('Setting themes is useful'); + +// +// Custom themes +// +console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}); + +// outputs red text +console.log('this is an error'.error); + +// outputs yellow text +console.log('this is a warning'.warn); + +// outputs grey text +console.log('this is an input'.input); + +console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +try { + colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); +} catch (err) { + console.log(err); +} + +// outputs red text +console.log('this is an error'.error); + +// outputs yellow text +console.log('this is a warning'.warn); + +// outputs grey text +console.log('this is an input'.input); + +// console.log("Don't summon".zalgo) + diff --git a/build/node_modules/colors/examples/safe-string.js b/build/node_modules/colors/examples/safe-string.js new file mode 100644 index 00000000..5bc0168e --- /dev/null +++ b/build/node_modules/colors/examples/safe-string.js @@ -0,0 +1,79 @@ +var colors = require('../safe'); + +console.log(colors.yellow('First some yellow text')); + +console.log(colors.yellow.underline('Underline that text')); + +console.log(colors.red.bold('Make it bold and red')); + +console.log(colors.rainbow('Double Raindows All Day Long')); + +console.log(colors.trap('Drop the bass')); + +console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS'))); + +// styles not widely supported +console.log(colors.bold.italic.underline.red('Chains are also cool.')); + +// styles not widely supported +console.log(colors.green('So ') + colors.underline('are') + ' ' + + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); + +console.log(colors.zebra('Zebras are so fun!')); + +console.log('This is ' + colors.strikethrough('not') + ' fun.'); + + +console.log(colors.black.bgWhite('Background color attack!')); +console.log(colors.random('Use random styles on everything!')); +console.log(colors.america('America, Heck Yeah!')); + +console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!')); + +console.log('Setting themes is useful'); + +// +// Custom themes +// +// console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'blue', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}); + +// outputs red text +console.log(colors.error('this is an error')); + +// outputs yellow text +console.log(colors.warn('this is a warning')); + +// outputs blue text +console.log(colors.input('this is an input')); + + +// console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); + +// outputs red text +console.log(colors.error('this is an error')); + +// outputs yellow text +console.log(colors.warn('this is a warning')); + +// outputs grey text +console.log(colors.input('this is an input')); + +// console.log(colors.zalgo("Don't summon him")) + + diff --git a/build/node_modules/colors/index.d.ts b/build/node_modules/colors/index.d.ts new file mode 100644 index 00000000..baa70686 --- /dev/null +++ b/build/node_modules/colors/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for Colors.js 1.2 +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor , Staffan Eketorp +// Definitions: https://github.com/Marak/colors.js + +export interface Color { + (text: string): string; + + strip: Color; + stripColors: Color; + + black: Color; + red: Color; + green: Color; + yellow: Color; + blue: Color; + magenta: Color; + cyan: Color; + white: Color; + gray: Color; + grey: Color; + + bgBlack: Color; + bgRed: Color; + bgGreen: Color; + bgYellow: Color; + bgBlue: Color; + bgMagenta: Color; + bgCyan: Color; + bgWhite: Color; + + reset: Color; + bold: Color; + dim: Color; + italic: Color; + underline: Color; + inverse: Color; + hidden: Color; + strikethrough: Color; + + rainbow: Color; + zebra: Color; + america: Color; + trap: Color; + random: Color; + zalgo: Color; +} + +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export let enabled: boolean; + +export const strip: Color; +export const stripColors: Color; + +export const black: Color; +export const red: Color; +export const green: Color; +export const yellow: Color; +export const blue: Color; +export const magenta: Color; +export const cyan: Color; +export const white: Color; +export const gray: Color; +export const grey: Color; + +export const bgBlack: Color; +export const bgRed: Color; +export const bgGreen: Color; +export const bgYellow: Color; +export const bgBlue: Color; +export const bgMagenta: Color; +export const bgCyan: Color; +export const bgWhite: Color; + +export const reset: Color; +export const bold: Color; +export const dim: Color; +export const italic: Color; +export const underline: Color; +export const inverse: Color; +export const hidden: Color; +export const strikethrough: Color; + +export const rainbow: Color; +export const zebra: Color; +export const america: Color; +export const trap: Color; +export const random: Color; +export const zalgo: Color; + +declare global { + interface String { + strip: string; + stripColors: string; + + black: string; + red: string; + green: string; + yellow: string; + blue: string; + magenta: string; + cyan: string; + white: string; + gray: string; + grey: string; + + bgBlack: string; + bgRed: string; + bgGreen: string; + bgYellow: string; + bgBlue: string; + bgMagenta: string; + bgCyan: string; + bgWhite: string; + + reset: string; + // @ts-ignore + bold: string; + dim: string; + italic: string; + underline: string; + inverse: string; + hidden: string; + strikethrough: string; + + rainbow: string; + zebra: string; + america: string; + trap: string; + random: string; + zalgo: string; + } +} diff --git a/build/node_modules/colors/lib/colors.js b/build/node_modules/colors/lib/colors.js new file mode 100644 index 00000000..9c7f1d14 --- /dev/null +++ b/build/node_modules/colors/lib/colors.js @@ -0,0 +1,211 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +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 colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var util = require('util'); +var ansiStyles = colors.styles = require('./styles'); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); + +colors.supportsColor = require('./system/supports-colors').supportsColor; + +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} + +colors.enable = function() { + colors.enabled = true; +}; + +colors.disable = function() { + colors.enabled = false; +}; + +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; + +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } + + var styleMap = ansiStyles[style]; + + // Stylize should work for non-ANSI styles, too + if(!styleMap && style in colors){ + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } + + return styleMap.open + str + styleMap.close; +}; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = + new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + }, + }; + }); + return ret; +})(); + +var proto = defineProps(function colors() {}, styles); + +function applyStyle() { + var args = Array.prototype.slice.call(arguments); + + var str = args.map(function(arg) { + // Use weak equality check so we can colorize null/undefined in safe mode + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util.inspect(arg); + } + }).join(' '); + + if (!colors.enabled || !str) { + return str; + } + + var newLinesPresent = str.indexOf('\n') != -1; + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); + } + } + + return str; +} + +colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + for (var style in theme) { + (function(style) { + colors[style] = function(str) { + if (typeof theme[style] === 'object') { + var out = str; + for (var i in theme[style]) { + out = colors[theme[style][i]](out); + } + return out; + } + return colors[theme[style]](str); + }; + })(style); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + }, + }; + }); + return ret; +} + +var sequencer = function sequencer(map, str) { + var exploded = str.split(''); + exploded = exploded.map(map); + return exploded.join(''); +}; + +// custom formatter methods +colors.trap = require('./custom/trap'); +colors.zalgo = require('./custom/zalgo'); + +// maps +colors.maps = {}; +colors.maps.america = require('./maps/america')(colors); +colors.maps.zebra = require('./maps/zebra')(colors); +colors.maps.rainbow = require('./maps/rainbow')(colors); +colors.maps.random = require('./maps/random')(colors); + +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} + +defineProps(colors, init()); diff --git a/build/node_modules/colors/lib/custom/trap.js b/build/node_modules/colors/lib/custom/trap.js new file mode 100644 index 00000000..fbccf88d --- /dev/null +++ b/build/node_modules/colors/lib/custom/trap.js @@ -0,0 +1,46 @@ +module['exports'] = function runTheTrap(text, options) { + var result = ''; + text = text || 'Run the trap, drop the bass'; + text = text.split(''); + var trap = { + a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], + b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], + c: ['\u00a9', '\u023b', '\u03fe'], + d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], + e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', + '\u0a6c'], + f: ['\u04fa'], + g: ['\u0262'], + h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], + i: ['\u0f0f'], + j: ['\u0134'], + k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], + l: ['\u0139'], + m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], + n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], + o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', + '\u06dd', '\u0e4f'], + p: ['\u01f7', '\u048e'], + q: ['\u09cd'], + r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], + s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], + t: ['\u0141', '\u0166', '\u0373'], + u: ['\u01b1', '\u054d'], + v: ['\u05d8'], + w: ['\u0428', '\u0460', '\u047c', '\u0d70'], + x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], + y: ['\u00a5', '\u04b0', '\u04cb'], + z: ['\u01b5', '\u0240'], + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [' ']; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== 'undefined') { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; +}; diff --git a/build/node_modules/colors/lib/custom/zalgo.js b/build/node_modules/colors/lib/custom/zalgo.js new file mode 100644 index 00000000..0ef2b011 --- /dev/null +++ b/build/node_modules/colors/lib/custom/zalgo.js @@ -0,0 +1,110 @@ +// please no +module['exports'] = function zalgo(text, options) { + text = text || ' he is here '; + var soul = { + 'up': [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚', + ], + 'down': [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣', + ], + 'mid': [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉', + ], + }; + var all = [].concat(soul.up, soul.down, soul.mid); + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = ''; + var counts; + var l; + options = options || {}; + options['up'] = + typeof options['up'] !== 'undefined' ? options['up'] : true; + options['mid'] = + typeof options['mid'] !== 'undefined' ? options['mid'] : true; + options['down'] = + typeof options['down'] !== 'undefined' ? options['down'] : true; + options['size'] = + typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; + text = text.split(''); + for (l in text) { + if (isChar(l)) { + continue; + } + result = result + text[l]; + counts = {'up': 0, 'down': 0, 'mid': 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + var arr = ['up', 'mid', 'down']; + for (var d in arr) { + var index = arr[d]; + for (var i = 0; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text, options); +}; + diff --git a/build/node_modules/colors/lib/extendStringPrototype.js b/build/node_modules/colors/lib/extendStringPrototype.js new file mode 100644 index 00000000..46fd386a --- /dev/null +++ b/build/node_modules/colors/lib/extendStringPrototype.js @@ -0,0 +1,110 @@ +var colors = require('./colors'); + +module['exports'] = function() { + // + // Extends prototype of native string object to allow for "foo".red syntax + // + var addProperty = function(color, func) { + String.prototype.__defineGetter__(color, func); + }; + + addProperty('strip', function() { + return colors.strip(this); + }); + + addProperty('stripColors', function() { + return colors.strip(this); + }); + + addProperty('trap', function() { + return colors.trap(this); + }); + + addProperty('zalgo', function() { + return colors.zalgo(this); + }); + + addProperty('zebra', function() { + return colors.zebra(this); + }); + + addProperty('rainbow', function() { + return colors.rainbow(this); + }); + + addProperty('random', function() { + return colors.random(this); + }); + + addProperty('america', function() { + return colors.america(this); + }); + + // + // Iterate through all default styles and colors + // + var x = Object.keys(colors.styles); + x.forEach(function(style) { + addProperty(style, function() { + return colors.stylize(this, style); + }); + }); + + function applyTheme(theme) { + // + // Remark: This is a list of methods that exist + // on String that you should not overwrite. + // + var stringPrototypeBlacklist = [ + '__defineGetter__', '__defineSetter__', '__lookupGetter__', + '__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty', + 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', + 'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length', + 'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice', + 'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase', + 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight', + ]; + + Object.keys(theme).forEach(function(prop) { + if (stringPrototypeBlacklist.indexOf(prop) !== -1) { + console.log('warn: '.red + ('String.prototype' + prop).magenta + + ' is probably something you don\'t want to override. ' + + 'Ignoring style name'); + } else { + if (typeof(theme[prop]) === 'string') { + colors[prop] = colors[theme[prop]]; + addProperty(prop, function() { + return colors[prop](this); + }); + } else { + var themePropApplicator = function(str) { + var ret = str || this; + for (var t = 0; t < theme[prop].length; t++) { + ret = colors[theme[prop][t]](ret); + } + return ret; + }; + addProperty(prop, themePropApplicator); + colors[prop] = function(str) { + return themePropApplicator(str); + }; + } + } + }); + } + + colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } else { + applyTheme(theme); + } + }; +}; diff --git a/build/node_modules/colors/lib/index.js b/build/node_modules/colors/lib/index.js new file mode 100644 index 00000000..9df5ab7d --- /dev/null +++ b/build/node_modules/colors/lib/index.js @@ -0,0 +1,13 @@ +var colors = require('./colors'); +module['exports'] = colors; + +// Remark: By default, colors will add style properties to String.prototype. +// +// If you don't wish to extend String.prototype, you can do this instead and +// native String will not be touched: +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +require('./extendStringPrototype')(); diff --git a/build/node_modules/colors/lib/maps/america.js b/build/node_modules/colors/lib/maps/america.js new file mode 100644 index 00000000..dc969033 --- /dev/null +++ b/build/node_modules/colors/lib/maps/america.js @@ -0,0 +1,10 @@ +module['exports'] = function(colors) { + return function(letter, i, exploded) { + if (letter === ' ') return letter; + switch (i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter); + case 2: return colors.blue(letter); + } + }; +}; diff --git a/build/node_modules/colors/lib/maps/rainbow.js b/build/node_modules/colors/lib/maps/rainbow.js new file mode 100644 index 00000000..2b00ac0a --- /dev/null +++ b/build/node_modules/colors/lib/maps/rainbow.js @@ -0,0 +1,12 @@ +module['exports'] = function(colors) { + // RoY G BiV + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + return function(letter, i, exploded) { + if (letter === ' ') { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; +}; + diff --git a/build/node_modules/colors/lib/maps/random.js b/build/node_modules/colors/lib/maps/random.js new file mode 100644 index 00000000..3d82a39e --- /dev/null +++ b/build/node_modules/colors/lib/maps/random.js @@ -0,0 +1,11 @@ +module['exports'] = function(colors) { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; + return function(letter, i, exploded) { + return letter === ' ' ? letter : + colors[ + available[Math.round(Math.random() * (available.length - 2))] + ](letter); + }; +}; diff --git a/build/node_modules/colors/lib/maps/zebra.js b/build/node_modules/colors/lib/maps/zebra.js new file mode 100644 index 00000000..fa736235 --- /dev/null +++ b/build/node_modules/colors/lib/maps/zebra.js @@ -0,0 +1,5 @@ +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; +}; diff --git a/build/node_modules/colors/lib/styles.js b/build/node_modules/colors/lib/styles.js new file mode 100644 index 00000000..011dafd8 --- /dev/null +++ b/build/node_modules/colors/lib/styles.js @@ -0,0 +1,95 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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 styles = {}; +module['exports'] = styles; + +var codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49], + +}; + +Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); diff --git a/build/node_modules/colors/lib/system/has-flag.js b/build/node_modules/colors/lib/system/has-flag.js new file mode 100644 index 00000000..a347dd4d --- /dev/null +++ b/build/node_modules/colors/lib/system/has-flag.js @@ -0,0 +1,35 @@ +/* +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. +*/ + +'use strict'; + +module.exports = function(flag, argv) { + argv = argv || process.argv; + + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); + + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; diff --git a/build/node_modules/colors/lib/system/supports-colors.js b/build/node_modules/colors/lib/system/supports-colors.js new file mode 100644 index 00000000..f1f9c8ff --- /dev/null +++ b/build/node_modules/colors/lib/system/supports-colors.js @@ -0,0 +1,151 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. + +*/ + +'use strict'; + +var os = require('os'); +var hasFlag = require('./has-flag.js'); + +var env = process.env; + +var forceColor = void 0; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') + || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 + || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + var min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first + // Windows release that supports 256 colors. Windows 10 build 14931 is the + // first release that supports 16m/TrueColor. + var osRelease = os.release().split('.'); + if (Number(process.versions.node.split('.')[0]) >= 8 + && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } + + if ('TERM_PROGRAM' in env) { + var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), +}; diff --git a/build/node_modules/colors/package.json b/build/node_modules/colors/package.json new file mode 100644 index 00000000..7e73cbd4 --- /dev/null +++ b/build/node_modules/colors/package.json @@ -0,0 +1,74 @@ +{ + "_from": "colors@^1.2.1", + "_id": "colors@1.4.0", + "_inBundle": false, + "_integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "_location": "/colors", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "colors@^1.2.1", + "name": "colors", + "escapedName": "colors", + "rawSpec": "^1.2.1", + "saveSpec": null, + "fetchSpec": "^1.2.1" + }, + "_requiredBy": [ + "/logform" + ], + "_resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "_shasum": "c50491479d4c1bdaed2c9ced32cf7c7dc2360f78", + "_spec": "colors@^1.2.1", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/logform", + "author": { + "name": "Marak Squires" + }, + "bugs": { + "url": "https://github.com/Marak/colors.js/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "DABH", + "url": "https://github.com/DABH" + } + ], + "deprecated": false, + "description": "get colors in your node.js console", + "devDependencies": { + "eslint": "^5.2.0", + "eslint-config-google": "^0.11.0" + }, + "engines": { + "node": ">=0.1.90" + }, + "files": [ + "examples", + "lib", + "LICENSE", + "safe.js", + "themes", + "index.d.ts", + "safe.d.ts" + ], + "homepage": "https://github.com/Marak/colors.js", + "keywords": [ + "ansi", + "terminal", + "colors" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "colors", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Marak/colors.js.git" + }, + "scripts": { + "lint": "eslint . --fix", + "test": "node tests/basic-test.js && node tests/safe-test.js" + }, + "version": "1.4.0" +} diff --git a/build/node_modules/colors/safe.d.ts b/build/node_modules/colors/safe.d.ts new file mode 100644 index 00000000..2bafc279 --- /dev/null +++ b/build/node_modules/colors/safe.d.ts @@ -0,0 +1,48 @@ +// Type definitions for Colors.js 1.2 +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor , Staffan Eketorp +// Definitions: https://github.com/Marak/colors.js + +export const enabled: boolean; +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export function strip(str: string): string; +export function stripColors(str: string): string; + +export function black(str: string): string; +export function red(str: string): string; +export function green(str: string): string; +export function yellow(str: string): string; +export function blue(str: string): string; +export function magenta(str: string): string; +export function cyan(str: string): string; +export function white(str: string): string; +export function gray(str: string): string; +export function grey(str: string): string; + +export function bgBlack(str: string): string; +export function bgRed(str: string): string; +export function bgGreen(str: string): string; +export function bgYellow(str: string): string; +export function bgBlue(str: string): string; +export function bgMagenta(str: string): string; +export function bgCyan(str: string): string; +export function bgWhite(str: string): string; + +export function reset(str: string): string; +export function bold(str: string): string; +export function dim(str: string): string; +export function italic(str: string): string; +export function underline(str: string): string; +export function inverse(str: string): string; +export function hidden(str: string): string; +export function strikethrough(str: string): string; + +export function rainbow(str: string): string; +export function zebra(str: string): string; +export function america(str: string): string; +export function trap(str: string): string; +export function random(str: string): string; +export function zalgo(str: string): string; diff --git a/build/node_modules/colors/safe.js b/build/node_modules/colors/safe.js new file mode 100644 index 00000000..a013d542 --- /dev/null +++ b/build/node_modules/colors/safe.js @@ -0,0 +1,10 @@ +// +// Remark: Requiring this file will use the "safe" colors API, +// which will not touch String.prototype. +// +// var colors = require('colors/safe'); +// colors.red("foo") +// +// +var colors = require('./lib/colors'); +module['exports'] = colors; diff --git a/build/node_modules/colors/themes/generic-logging.js b/build/node_modules/colors/themes/generic-logging.js new file mode 100644 index 00000000..63adfe4a --- /dev/null +++ b/build/node_modules/colors/themes/generic-logging.js @@ -0,0 +1,12 @@ +module['exports'] = { + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red', +}; diff --git a/build/node_modules/colorspace/LICENSE.md b/build/node_modules/colorspace/LICENSE.md new file mode 100644 index 00000000..9beaab11 --- /dev/null +++ b/build/node_modules/colorspace/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the 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. diff --git a/build/node_modules/colorspace/README.md b/build/node_modules/colorspace/README.md new file mode 100644 index 00000000..c26690f8 --- /dev/null +++ b/build/node_modules/colorspace/README.md @@ -0,0 +1,43 @@ +# colorspace + +Colorspace is a simple module which generates HEX color codes for namespaces. +The base color is decided by the first part of the namespace. All other parts of +the namespace alters the color tone. This way you can visually see which +namespaces belong together and which does not. + +## Installation + +The module is released in the public npm registry and can be installed by +running: + +``` +npm install --save colorspace +``` + +## Usage + +We assume that you've already required the module using the following code: + +```js +'use strict'; + +var colorspace = require('colorspace'); +``` + +The returned function accepts 2 arguments: + +1. `namespace` **string**, The namespace that needs to have a HEX color + generated. +2. `delimiter`, **string**, **optional**, Delimiter to find the different + sections of the namespace. Defaults to `:` + +#### Example + +```js +console.log(colorspace('color')) // #6b4b3a +console.log(colorspace('color:space')) // #796B67 +``` + +## License + +MIT diff --git a/build/node_modules/colorspace/index.js b/build/node_modules/colorspace/index.js new file mode 100644 index 00000000..cb56eb6d --- /dev/null +++ b/build/node_modules/colorspace/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var color = require('color') + , hex = require('text-hex'); + +/** + * Generate a color for a given name. But be reasonably smart about it by + * understanding name spaces and coloring each namespace a bit lighter so they + * still have the same base color as the root. + * + * @param {string} namespace The namespace + * @param {string} [delimiter] The delimiter + * @returns {string} color + */ +module.exports = function colorspace(namespace, delimiter) { + var split = namespace.split(delimiter || ':'); + var base = hex(split[0]); + + if (!split.length) return base; + + for (var i = 0, l = split.length - 1; i < l; i++) { + base = color(base) + .mix(color(hex(split[i + 1]))) + .saturate(1) + .hex(); + } + + return base; +}; diff --git a/build/node_modules/colorspace/package.json b/build/node_modules/colorspace/package.json new file mode 100644 index 00000000..5a18dbcc --- /dev/null +++ b/build/node_modules/colorspace/package.json @@ -0,0 +1,64 @@ +{ + "_from": "colorspace@1.1.x", + "_id": "colorspace@1.1.2", + "_inBundle": false, + "_integrity": "sha512-vt+OoIP2d76xLhjwbBaucYlNSpPsrJWPlBTtwCpQKIu6/CSMutyzX93O/Do0qzpH3YoHEes8YEFXyZ797rEhzQ==", + "_location": "/colorspace", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "colorspace@1.1.x", + "name": "colorspace", + "escapedName": "colorspace", + "rawSpec": "1.1.x", + "saveSpec": null, + "fetchSpec": "1.1.x" + }, + "_requiredBy": [ + "/@dabh/diagnostics" + ], + "_resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.2.tgz", + "_shasum": "e0128950d082b86a2168580796a0aa5d6c68d8c5", + "_spec": "colorspace@1.1.x", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/@dabh/diagnostics", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/3rd-Eden/colorspace/issues" + }, + "bundleDependencies": false, + "dependencies": { + "color": "3.0.x", + "text-hex": "1.0.x" + }, + "deprecated": false, + "description": "Generate HEX colors for a given namespace.", + "devDependencies": { + "assume": "2.1.x", + "mocha": "5.2.x", + "pre-commit": "1.2.x" + }, + "homepage": "https://github.com/3rd-Eden/colorspace", + "keywords": [ + "namespace", + "color", + "hex", + "colorize", + "name", + "space", + "colorspace" + ], + "license": "MIT", + "main": "index.js", + "name": "colorspace", + "repository": { + "type": "git", + "url": "git+https://github.com/3rd-Eden/colorspace.git" + }, + "scripts": { + "test": "mocha test.js" + }, + "version": "1.1.2" +} diff --git a/build/node_modules/colorspace/test.js b/build/node_modules/colorspace/test.js new file mode 100644 index 00000000..32f4d234 --- /dev/null +++ b/build/node_modules/colorspace/test.js @@ -0,0 +1,14 @@ +describe('colorspace', function () { + var colorspace = require('./'); + var assume = require('assume'); + + it('returns a consistent color for a given name', function () { + assume(colorspace('bigpipe')).equals('#20f95a'); + assume(colorspace('bigpipe')).equals('#20f95a'); + assume(colorspace('bigpipe')).equals('#20f95a'); + }); + + it('tones the color when namespaced by a : char', function () { + assume(colorspace('bigpipe:pagelet')).equals('#00FF2C'); + }); +}); diff --git a/build/node_modules/configparser/.circleci/config.yml b/build/node_modules/configparser/.circleci/config.yml new file mode 100644 index 00000000..d4ed4a92 --- /dev/null +++ b/build/node_modules/configparser/.circleci/config.yml @@ -0,0 +1,85 @@ +version: 2 + +defaults: &defaults + working_directory: ~/repo + docker: + - image: circleci/node:10.6.0 + +jobs: + test: + <<: *defaults + steps: + - checkout + - run: + name: Install dependencies + command: npm install + - run: + name: Run tests + command: npm test + - persist_to_workspace: + root: ~/repo + paths: . + deploy: + <<: *defaults + steps: + - attach_workspace: + at: ~/repo + - run: + name: Authenticate with registry + command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc + - run: + name: Publish to npm + command: npm publish + deploy-docs: + <<: *defaults + steps: + - attach_workspace: + at: ~/repo + - add_ssh_keys: + fingerprints: + - "68:18:c2:6e:1e:50:38:9c:fa:24:e2:3b:f6:ea:fe:6b" + - run: + name: Install dependencies + command: sudo npm install -g jsdoc gh-pages + - run: + name: Build docs + command: jsdoc -c jsdoc.json + - run: + name: Configure git + command: | + git config user.email "$GH_EMAIL" + git config user.name "$GH_NAME" + - run: + name: Deploy docs + command: gh-pages --dist docs/ --message "[skip ci] Updates" + +workflows: + version: 2 + test-deploy: + jobs: + - test: + filters: + tags: + only: /^v.*/ + branches: + ignore: /.*/ + - deploy: + requires: + - test + filters: + tags: + only: /^v.*/ + branches: + ignore: /.*/ + test-deploy-docs: + jobs: + - test: + filters: + branches: + only: master + - deploy-docs: + requires: + - test + filters: + branches: + only: master diff --git a/build/node_modules/configparser/package.json b/build/node_modules/configparser/package.json new file mode 100644 index 00000000..7596f58f --- /dev/null +++ b/build/node_modules/configparser/package.json @@ -0,0 +1,62 @@ +{ + "_from": "configparser@^0.3.9", + "_id": "configparser@0.3.9", + "_inBundle": false, + "_integrity": "sha512-ZlHt4SyiCfcQmFkt+2OfUQG6PC4GLyXthfBHvCH9I4ZtDxqMaAkfeEP+bkgePWgO3869+dRMVIcjklwfZmPDjg==", + "_location": "/configparser", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "configparser@^0.3.9", + "name": "configparser", + "escapedName": "configparser", + "rawSpec": "^0.3.9", + "saveSpec": null, + "fetchSpec": "^0.3.9" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/configparser/-/configparser-0.3.9.tgz", + "_shasum": "9c8219dd8682b3908a2a2069ae11d85635ab4d68", + "_spec": "configparser@^0.3.9", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build", + "author": { + "name": "Zach Perkitny" + }, + "bugs": { + "url": "https://github.com/ZachPerkitny/configparser/issues" + }, + "bundleDependencies": false, + "dependencies": { + "mkdirp": "^0.5.1" + }, + "deprecated": false, + "description": "A basic config parser language based off the Python ConfigParser module.", + "devDependencies": { + "chai": "^4.1.2", + "mocha": "^4.0.1" + }, + "homepage": "https://github.com/ZachPerkitny/configparser#readme", + "keywords": [ + "config", + "parser", + "configparser", + "config-parser", + "ini", + "node" + ], + "license": "ISC", + "main": "src/configparser.js", + "name": "configparser", + "repository": { + "type": "git", + "url": "git+https://github.com/ZachPerkitny/configparser.git" + }, + "scripts": { + "test": "mocha ./test/*.js" + }, + "types": "typings/configparser.d.ts", + "version": "0.3.9" +} diff --git a/build/node_modules/configparser/readme.md b/build/node_modules/configparser/readme.md new file mode 100644 index 00000000..d099218a --- /dev/null +++ b/build/node_modules/configparser/readme.md @@ -0,0 +1,59 @@ +### Config Parser [![CircleCI](https://circleci.com/gh/ZachPerkitny/configparser.svg?style=svg)](https://circleci.com/gh/ZachPerkitny/configparser) +A NodeJS module based off of Python's ConfigParser. It implements a basic configuration file +parser. The structure is very similar to the Windows INI file. + +#### Installation +`npm install configparser` + +### Documentation +See Full Documentation [Here](https://zachperkitny.github.io/configparser/) + +#### Example +##### Writing + +There are two methods available for writing the contents +of the config file to disk: [write](https://zachperkitny.github.io/configparser/ConfigParser.html#write) and [writeAsync](https://zachperkitny.github.io/configparser/ConfigParser.html#writeAsync). + +```js +const ConfigParser = require('configparser'); + +const config = new ConfigParser(); + +// Adding sections and adding keys +config.addSection('User'); +config.set('User', 'token', 'some value'); +config.set('User', 'exp', 'some value'); + +// With String Interpolation, %(key_name)s +config.addSection('MetaData'); +config.set('MetaData', 'path', '/home/%(dir_name)s/'); +config.set('MetaData', 'dir_name', 'me'); + +config.write('my-cfg-file.cfg'); +``` + +##### File +```ini +[User] +token=some value +exp=some value + +[MetaData] +path=/home/%(dir_name)s/ +dir_name=me +``` + +##### Reading + +There are two methods available for reading the contents +of the config file from disk: [read](https://zachperkitny.github.io/configparser/ConfigParser.html#read) and [readAsync](https://zachperkitny.github.io/configparser/ConfigParser.html#readAsync). + +```js +config.read('my-cfg-file.cfg'); +config.sections(); // ['User', 'MetaData'] +config.get('User', 'token'); // 'some value' +config.get('MetaData', 'path'); // '/home/me/' +``` + +### Questions and Issues +Use the [Github Issue Tracker](https://github.com/ZachPerkitny/configparser/issues) to report a bug, request a feature, or if you need any help. diff --git a/build/node_modules/configparser/src/configparser.js b/build/node_modules/configparser/src/configparser.js new file mode 100644 index 00000000..6745de62 --- /dev/null +++ b/build/node_modules/configparser/src/configparser.js @@ -0,0 +1,289 @@ +const util = require('util'); +const fs = require('fs'); +const path = require('path'); +const mkdirp = require('mkdirp'); +const errors = require('./errors'); +const interpolation = require('./interpolation'); + +/** + * Regular Expression to match section headers. + * @type {RegExp} + * @private + */ +const SECTION = new RegExp(/\s*\[([^\]]+)]/); + +/** + * Regular expression to match key, value pairs. + * @type {RegExp} + * @private + */ +const KEY = new RegExp(/\s*(.*?)\s*[=:]\s*(.*)/); + +/** + * Regular expression to match comments. Either starting with a + * semi-colon or a hash. + * @type {RegExp} + * @private + */ +const COMMENT = new RegExp(/^\s*[;#]/); + +// RL1.6 Line Boundaries (for unicode) +// ... it shall recognize not only CRLF, LF, CR, +// but also NEL, PS and LS. +const LINE_BOUNDARY = new RegExp(/\r\n|[\n\r\u0085\u2028\u2029]/g); + +const readFileAsync = util.promisify(fs.readFile); +const writeFileAsync = util.promisify(fs.writeFile); +const statAsync = util.promisify(fs.stat); +const mkdirAsync = util.promisify(mkdirp); + +/** + * @constructor + */ +function ConfigParser() { + this._sections = {}; +} + +/** + * Returns an array of the sections. + * @returns {Array} + */ +ConfigParser.prototype.sections = function() { + return Object.keys(this._sections); +}; + +/** + * Adds a section named section to the instance. If the section already + * exists, a DuplicateSectionError is thrown. + * @param {string} section - Section Name + */ +ConfigParser.prototype.addSection = function(section) { + if(this._sections.hasOwnProperty(section)){ + throw new errors.DuplicateSectionError(section) + } + this._sections[section] = {}; +}; + +/** + * Indicates whether the section is present in the configuration + * file. + * @param {string} section - Section Name + * @returns {boolean} + */ +ConfigParser.prototype.hasSection = function(section) { + return this._sections.hasOwnProperty(section); +}; + +/** + * Returns an array of all keys in the specified section. + * @param {string} section - Section Name + * @returns {Array} + */ +ConfigParser.prototype.keys = function(section) { + try { + return Object.keys(this._sections[section]); + } catch(err){ + throw new errors.NoSectionError(section); + } +}; + +/** + * Indicates whether the specified key is in the section. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @returns {boolean} + */ +ConfigParser.prototype.hasKey = function (section, key) { + return this._sections.hasOwnProperty(section) && + this._sections[section].hasOwnProperty(key); +}; + +/** + * Reads a file and parses the configuration data. + * @param {string|Buffer|int} file - Filename or File Descriptor + */ +ConfigParser.prototype.read = function(file) { + const lines = fs.readFileSync(file) + .toString('utf8') + .split(LINE_BOUNDARY); + parseLines.call(this, file, lines); +}; + +/** + * Reads a file asynchronously and parses the configuration data. + * @param {string|Buffer|int} file - Filename or File Descriptor + */ +ConfigParser.prototype.readAsync = async function(file) { + const lines = (await readFileAsync(file)) + .toString('utf8') + .split(LINE_BOUNDARY); + parseLines.call(this, file, lines); +} + +/** + * Gets the value for the key in the named section. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {boolean} [raw=false] - Whether or not to replace placeholders + * @returns {string|undefined} + */ +ConfigParser.prototype.get = function(section, key, raw) { + if(this._sections.hasOwnProperty(section)){ + if(raw){ + return this._sections[section][key]; + } else { + return interpolation.interpolate(this, section, key); + } + } + return undefined; +}; + +/** + * Coerces value to an integer of the specified radix. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {int} [radix=10] - An integer between 2 and 36 that represents the base of the string. + * @returns {number|undefined|NaN} + */ +ConfigParser.prototype.getInt = function(section, key, radix) { + if(this._sections.hasOwnProperty(section)){ + if(!radix) radix = 10; + return parseInt(this._sections[section][key], radix); + } + return undefined; +}; + +/** + * Coerces value to a float. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @returns {number|undefined|NaN} + */ +ConfigParser.prototype.getFloat = function(section, key) { + if(this._sections.hasOwnProperty(section)){ + return parseFloat(this._sections[section][key]); + } + return undefined; +}; + +/** + * Returns an object with every key, value pair for the named section. + * @param {string} section - Section Name + * @returns {Object} + */ +ConfigParser.prototype.items = function(section) { + return this._sections[section]; +}; + +/** + * Sets the given key to the specified value. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {*} value - New Key Value + */ +ConfigParser.prototype.set = function(section, key, value) { + if(this._sections.hasOwnProperty(section)){ + this._sections[section][key] = value; + } +}; + +/** + * Removes the property specified by key in the named section. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @returns {boolean} + */ +ConfigParser.prototype.removeKey = function(section, key) { + // delete operator returns true if the property doesn't not exist + if(this._sections.hasOwnProperty(section) && + this._sections[section].hasOwnProperty(key)){ + return delete this._sections[section][key]; + } + return false; +}; + +/** + * Removes the named section (and associated key, value pairs). + * @param {string} section - Section Name + * @returns {boolean} + */ +ConfigParser.prototype.removeSection = function(section) { + if(this._sections.hasOwnProperty(section)){ + return delete this._sections[section]; + } + return false; +}; + +/** + * Writes the representation of the config file to the + * specified file. Comments are not preserved. + * @param {string|Buffer|int} file - Filename or File Descriptor + * @param {bool} [createMissingDirs=false] - Whether to create the directories in the path if they don't exist + */ +ConfigParser.prototype.write = function(file, createMissingDirs = false) { + if (createMissingDirs) { + const dir = path.dirname(file); + mkdirp.sync(dir); + } + + fs.writeFileSync(file, getSectionsAsString.call(this)); +}; + +/** + * Writes the representation of the config file to the + * specified file asynchronously. Comments are not preserved. + * @param {string|Buffer|int} file - Filename or File Descriptor + * @param {bool} [createMissingDirs=false] - Whether to create the directories in the path if they don't exist + * @returns {Promise} + */ +ConfigParser.prototype.writeAsync = async function(file, createMissingDirs = false) { + if (createMissingDirs) { + const dir = path.dirname(file); + await mkdirAsync(dir); + } + + await writeFileAsync(file, getSectionsAsString.call(this)); +} + +function parseLines(file, lines) { + let curSec = null; + lines.forEach((line, lineNumber) => { + if(!line || line.match(COMMENT)) return; + let res = SECTION.exec(line); + if(res){ + const header = res[1]; + curSec = {}; + this._sections[header] = curSec; + } else if(!curSec) { + throw new errors.MissingSectionHeaderError(file, lineNumber, line); + } else { + res = KEY.exec(line); + if(res){ + const key = res[1]; + curSec[key] = res[2]; + } else { + throw new errors.ParseError(file, lineNumber, line); + } + } + }); +} + +function getSectionsAsString() { + let out = ''; + let section; + for(section in this._sections){ + if(!this._sections.hasOwnProperty(section)) continue; + out += ('[' + section + ']\n'); + const keys = this._sections[section]; + let key; + for(key in keys){ + if(!keys.hasOwnProperty(key)) continue; + let value = keys[key]; + out += (key + '=' + value + '\n'); + } + out += '\n'; + } + return out; +} + +module.exports = ConfigParser; diff --git a/build/node_modules/configparser/src/errors.js b/build/node_modules/configparser/src/errors.js new file mode 100644 index 00000000..d07d9f85 --- /dev/null +++ b/build/node_modules/configparser/src/errors.js @@ -0,0 +1,76 @@ +/** + * Error thrown when addSection is called with a section + * that already exists. + * @param {string} section - Section Name + * @constructor + */ +function DuplicateSectionError(section) { + this.name = 'DuplicateSectionError'; + this.message = section + ' already exists'; + Error.captureStackTrace(this, this.constructor); +} + +/** + * Error thrown when the section being accessed, does + * not exist. + * @param {string} section - Section Name + * @constructor + */ +function NoSectionError(section) { + this.name = this.constructor.name; + this.message = 'Section ' + section + ' does not exist.'; + Error.captureStackTrace(this, this.constructor); +} + +/** + * Error thrown when a file is being parsed. + * @param {string} filename - File name + * @param {int} lineNumber - Line Number + * @param {string} line - Contents of the line + * @constructor + */ +function ParseError(filename, lineNumber, line) { + this.name = this.constructor.name; + this.message = 'Source contains parsing errors.\nfile: ' + filename + + ' line: ' + lineNumber + '\n' + line; + Error.captureStackTrace(this, this.constructor); +} + +/** + * Error thrown when there are no section headers present + * in a file. + * @param {string} filename - File name + * @param {int} lineNumber - Line Number + * @param {string} line - Contents of the line + * @constructor + */ +function MissingSectionHeaderError(filename, lineNumber, line) { + this.name = this.constructor.name; + this.message = 'File contains no section headers.\nfile: ' + filename + + ' line: ' + lineNumber + '\n' + line; + Error.captureStackTrace(this, this.constructor); +} + +/** + * Error thrown when the interpolate function exceeds the maximum recursion + * depth. + * @param {string} section - Section Name + * @param {string} key - Key Name + * @param {string} value - Key Value + * @param {int} maxDepth - Maximum recursion depth + * @constructor + */ +function MaximumInterpolationDepthError(section, key, value, maxDepth) { + this.name = this.constructor.name; + this.message = 'Exceeded Maximum Recursion Depth (' + maxDepth + + ') for key ' + key + ' in section ' + section + '\nvalue: ' + value; + Error.captureStackTrace(this, this.constructor); +} + +module.exports = { + DuplicateSectionError, + NoSectionError, + ParseError, + MissingSectionHeaderError, + MaximumInterpolationDepthError +}; \ No newline at end of file diff --git a/build/node_modules/configparser/src/interpolation.js b/build/node_modules/configparser/src/interpolation.js new file mode 100644 index 00000000..6a3948e9 --- /dev/null +++ b/build/node_modules/configparser/src/interpolation.js @@ -0,0 +1,56 @@ +const errors = require('./errors'); + +/** + * Regular Expression to match placeholders. + * @type {RegExp} + * @private + */ +const PLACEHOLDER = new RegExp(/%\(([\w-]+)\)s/); + +/** + * Maximum recursion depth for parseValue + * @type {number} + */ +const MAXIMUM_INTERPOLATION_DEPTH = 50; + +/** + * Recursively parses a string and replaces the placeholder ( %(key)s ) + * with the value the key points to. + * @param {ParserConfig} parser - Parser Config Object + * @param {string} section - Section Name + * @param {string} key - Key Name + */ +function interpolate(parser, section, key) { + return interpolateRecurse(parser, section, key, 1); +} + +/** + * Interpolate Recurse + * @param parser + * @param section + * @param key + * @param depth + * @private + */ +function interpolateRecurse(parser, section, key, depth) { + let value = parser.get(section, key, true); + if(depth > MAXIMUM_INTERPOLATION_DEPTH){ + throw new errors.MaximumInterpolationDepthError(section, key, value, MAXIMUM_INTERPOLATION_DEPTH); + } + let res = PLACEHOLDER.exec(value); + while(res !== null){ + const placeholder = res[1]; + const rep = interpolateRecurse(parser, section, placeholder, depth + 1); + // replace %(key)s with the returned value next + value = value.substr(0, res.index) + rep + + value.substr(res.index + res[0].length); + // get next placeholder + res = PLACEHOLDER.exec(value); + } + return value; +} + +module.exports = { + interpolate, + MAXIMUM_INTERPOLATION_DEPTH +}; \ No newline at end of file diff --git a/build/node_modules/configparser/test/configparser.js b/build/node_modules/configparser/test/configparser.js new file mode 100644 index 00000000..a390f65e --- /dev/null +++ b/build/node_modules/configparser/test/configparser.js @@ -0,0 +1,83 @@ +const expect = require('chai').expect; +const ConfigParser = require('../src/configparser'); + +describe('ConfigParser object', function(){ + const config = new ConfigParser(); + config.read('test/data/file.ini'); + + it('should return all sections in the config file', function(){ + expect(config.sections()).to.deep.equal([ + 'section1', + 'section2', + 'USER', + 'im running out of ideas', + 'interpolation', + 'permissive_section:headers%!?', + 'more_complex_interpolation' + ]); + }); + + it('should indicate if a section is present in a config file', function(){ + expect(config.hasSection('section1')).to.equal(true); + expect(config.hasSection('section4')).to.equal(false); + }); + + it('should add a new section', function(){ + config.addSection('new-section'); + expect(config.hasSection('new-section')).to.equal(true); + }); + + it('should return every key in a section', function(){ + expect(config.keys('section1')).to.deep.equal(['key', 'other', 'idontknow']); + expect(config.keys('section2')).to.deep.equal(['value', 'key', 'woah', 'this']); + expect(config.keys('USER')).to.deep.equal(['username', 'password']); + expect(config.keys('permissive_section:headers%!?')).to.deep.equal(['hello', 'goodbye']); + expect(config.keys('im running out of ideas')).to.deep.equal(['anotherthing', 'otherthing']); + }); + + it('should indicate if a section has a key', function(){ + expect(config.hasKey('section1', 'idontknow')).to.equal(true); + expect(config.hasKey('section1', 'fakekey')).to.equal(false); + expect(config.hasKey('fake section', 'fakekey')).to.equal(false); + expect(config.hasKey('permissive_section:headers%!?', 'hello')).to.equal(true); + }); + + it('should get the value for a key in the named section', function(){ + expect(config.get('section1', 'key')).to.equal('value'); + expect(config.get('USER', 'username')).to.equal('user'); + }); + + it('should recursively replace placehoders', function(){ + expect(config.get('interpolation', 'greeting')).to.equal('hello zach, how are you?'); + expect(config.get('more_complex_interpolation', 'path')).to.equal('/home/nested/zach/documents/mytextfile.txt'); + }); + + it('should add or modify a key in the named section', function(){ + config.set('section1', 'key', 55); + config.set('section1', 'NewKey', 'hello'); + expect(config.get('section1', 'key')).to.equal(55); + expect(config.get('section1', 'NewKey')).to.equal('hello'); + }); + + it('should return the correct key, value pairs for each section', function(){ + expect(config.items('section1')).to.deep.equal({ + key: 55, + other: 'something else', + idontknow: 'more values!', + NewKey: 'hello' + }); + }); + + it('should remove a key from the named section', function(){ + expect(config.removeKey('fakesection', 'NewKey')).to.equal(false); + expect(config.removeKey('section1', 'not a real key')).to.equal(false); + expect(config.removeKey('section1', 'NewKey')).to.equal(true); + expect(config.get('section1', 'NewKey')).to.equal(undefined); + }); + + it('should remove a section', function(){ + expect(config.removeSection('fake-section')).to.equal(false); + expect(config.removeSection('new-section')).to.equal(true); + expect(config.hasSection('new-section')).to.equal(false); + }); +}); \ No newline at end of file diff --git a/build/node_modules/configparser/test/data/file.ini b/build/node_modules/configparser/test/data/file.ini new file mode 100644 index 00000000..6d2314c9 --- /dev/null +++ b/build/node_modules/configparser/test/data/file.ini @@ -0,0 +1,38 @@ +[section1] +key=value +other=something else +idontknow = more values! + +[section2] +value=value +key=value +woah=7 +this=5 + +[USER] +username=user +password=SUPERSECRETDONTLOOK + +[im running out of ideas] +anotherthing=thing +otherthing=what + +[interpolation] +greeting=hello %(name)s +name=zach, %(how)s +how=how %(are)s +are=are %(you)s +you=you%(question)s +question=? + +[permissive_section:headers%!?] +hello: hello +goodbye: goodbye + +[more_complex_interpolation] +path=/%(root)s/%(next_dir)s/%(file)s +root=home +next_dir=%(its_nested)s/zach/%(my_folder)s +its_nested=nested +my_folder=documents +file=mytextfile.txt \ No newline at end of file diff --git a/build/node_modules/configparser/typings/configparser.d.ts b/build/node_modules/configparser/typings/configparser.d.ts new file mode 100644 index 00000000..8bdec462 --- /dev/null +++ b/build/node_modules/configparser/typings/configparser.d.ts @@ -0,0 +1,24 @@ +type FileInputType = string | Buffer | number; + +declare module 'configparser' { + class ConfigParser { + sections(): string[]; + addSection(section: string): void; + hasSection(section: string): boolean; + keys(section: string): string[]; + hasKey(section: string, key: string): boolean; + read(file: FileInputType): void; + readAsync(file: FileInputType): void; + get(section: string, key: string, raw?: boolean): string | undefined; + getInt(section: string, key: string, radix?: number): number | undefined; + getFloat(section: string, key: string): number|undefined; + items(section: string): Record; + set(section: string, key: string, value: any): void; + removeKey(section: string, key: string): boolean; + removeSection(section: string): boolean; + write(file: FileInputType, createMissingDirs?: boolean): void; + writeAsync(file: FileInputType, createMissingDirs?: boolean): Promise; + } + + export default ConfigParser +} \ No newline at end of file diff --git a/build/node_modules/enabled/.travis.yml b/build/node_modules/enabled/.travis.yml new file mode 100644 index 00000000..6b89a86c --- /dev/null +++ b/build/node_modules/enabled/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "10" + - "9" + - "8" +after_script: + - "npm install coveralls@2.11.x && cat coverage/lcov.info | coveralls" +matrix: + fast_finish: true diff --git a/build/node_modules/enabled/LICENSE b/build/node_modules/enabled/LICENSE new file mode 100644 index 00000000..9beaab11 --- /dev/null +++ b/build/node_modules/enabled/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the 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. diff --git a/build/node_modules/enabled/README.md b/build/node_modules/enabled/README.md new file mode 100644 index 00000000..bed6de32 --- /dev/null +++ b/build/node_modules/enabled/README.md @@ -0,0 +1,68 @@ +# enabled + +[![Version npm][version]](http://browsenpm.org/package/enabled)[![Build Status][build]](https://travis-ci.org/3rd-Eden/enabled)[![Dependencies][david]](https://david-dm.org/3rd-Eden/enabled)[![Coverage Status][cover]](https://coveralls.io/r/3rd-Eden/enabled?branch=master) + +[version]: http://img.shields.io/npm/v/enabled.svg?style=flat-square +[build]: http://img.shields.io/travis/3rd-Eden/enabled/master.svg?style=flat-square +[david]: https://img.shields.io/david/3rd-Eden/enabled.svg?style=flat-square +[cover]: http://img.shields.io/coveralls/3rd-Eden/enabled/master.svg?style=flat-square + +Enabled is a small utility that can check if certain namespace are enabled by +environment variables which are automatically transformed to regular expressions +for matching. + +## Installation + +The module is release in the public npm registry and can be used in browsers and +servers as it uses plain ol ES3 to make the magic work. + +``` +npm install --save enabled +``` + +## Usage + +First of all make sure you've required the module using: + +```js +'use strict'; + +var enabled = require('enabled'); +``` + +The returned `enabled` function accepts 2 arguments. + +1. `name` **string**, The namespace that should match. +2. `pattern` **string**, The pattern that the name should satisfy + +It will return a boolean indication of a match. + +#### Examples + +```js +var flag = 'foo'; + +enabled('foo', flag); // true; +enabled('bar', flag); // false; + +// +// Use * for wild cards. +// +var wildcard = 'foob*'; + +enabled('foobar', wildcard); // true; +enabled('barfoo', wildcard); // false; + +// +// Use - to ignore. +// +var ignore = 'foobar,-shizzle,nizzle'; + +enabled('foobar', ignore); // true; +enabled('shizzle-my-nizzle', ignore); // false; +enabled('nizzle', ignore); // true; +``` + +## License + +[MIT](./LICENSE) diff --git a/build/node_modules/enabled/index.js b/build/node_modules/enabled/index.js new file mode 100644 index 00000000..69ee6509 --- /dev/null +++ b/build/node_modules/enabled/index.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * Checks if a given namespace is allowed by the given variable. + * + * @param {String} name namespace that should be included. + * @param {String} variable Value that needs to be tested. + * @returns {Boolean} Indication if namespace is enabled. + * @public + */ +module.exports = function enabled(name, variable) { + if (!variable) return false; + + var variables = variable.split(/[\s,]+/) + , i = 0; + + for (; i < variables.length; i++) { + variable = variables[i].replace('*', '.*?'); + + if ('-' === variable.charAt(0)) { + if ((new RegExp('^'+ variable.substr(1) +'$')).test(name)) { + return false; + } + + continue; + } + + if ((new RegExp('^'+ variable +'$')).test(name)) { + return true; + } + } + + return false; +}; diff --git a/build/node_modules/enabled/package.json b/build/node_modules/enabled/package.json new file mode 100644 index 00000000..80239296 --- /dev/null +++ b/build/node_modules/enabled/package.json @@ -0,0 +1,64 @@ +{ + "_from": "enabled@2.0.x", + "_id": "enabled@2.0.0", + "_inBundle": false, + "_integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==", + "_location": "/enabled", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "enabled@2.0.x", + "name": "enabled", + "escapedName": "enabled", + "rawSpec": "2.0.x", + "saveSpec": null, + "fetchSpec": "2.0.x" + }, + "_requiredBy": [ + "/@dabh/diagnostics" + ], + "_resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "_shasum": "f9dd92ec2d6f4bbc0d5d1e64e21d61cd4665e7c2", + "_spec": "enabled@2.0.x", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/@dabh/diagnostics", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/3rd-Eden/enabled/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Check if a certain debug flag is enabled.", + "devDependencies": { + "assume": "2.1.x", + "istanbul": "^0.4.5", + "mocha": "5.2.x", + "pre-commit": "1.2.x" + }, + "homepage": "https://github.com/3rd-Eden/enabled#readme", + "keywords": [ + "enabled", + "debug", + "diagnostics", + "flag", + "env", + "variable", + "localstorage" + ], + "license": "MIT", + "main": "index.js", + "name": "enabled", + "repository": { + "type": "git", + "url": "git://github.com/3rd-Eden/enabled.git" + }, + "scripts": { + "100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100", + "test": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- test.js", + "watch": "mocha --watch test.js" + }, + "version": "2.0.0" +} diff --git a/build/node_modules/enabled/test.js b/build/node_modules/enabled/test.js new file mode 100644 index 00000000..a160b71e --- /dev/null +++ b/build/node_modules/enabled/test.js @@ -0,0 +1,39 @@ +describe('enabled', function () { + 'use strict'; + + var assume = require('assume') + , enabled = require('./'); + + it('supports wildcards', function () { + var variable = 'b*'; + + assume(enabled('bigpipe', variable)).to.be.true(); + assume(enabled('bro-fist', variable)).to.be.true(); + assume(enabled('ro-fist', variable)).to.be.false(); + }); + + it('is disabled by default', function () { + assume(enabled('bigpipe', '')).to.be.false(); + assume(enabled('bigpipe', 'bigpipe')).to.be.true(); + }); + + it('can ignore loggers using a -', function () { + var variable = 'bigpipe,-primus,sack,-other'; + + assume(enabled('bigpipe', variable)).to.be.true(); + assume(enabled('sack', variable)).to.be.true(); + assume(enabled('primus', variable)).to.be.false(); + assume(enabled('other', variable)).to.be.false(); + assume(enabled('unknown', variable)).to.be.false(); + }); + + it('supports multiple ranges', function () { + var variable = 'bigpipe*,primus*'; + + assume(enabled('bigpipe:', variable)).to.be.true(); + assume(enabled('bigpipes', variable)).to.be.true(); + assume(enabled('primus:', variable)).to.be.true(); + assume(enabled('primush', variable)).to.be.true(); + assume(enabled('unknown', variable)).to.be.false(); + }); +}); diff --git a/build/node_modules/fast-safe-stringify/.travis.yml b/build/node_modules/fast-safe-stringify/.travis.yml new file mode 100644 index 00000000..2b06d253 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +sudo: false +node_js: +- '4' +- '6' +- '8' +- '9' +- '10' diff --git a/build/node_modules/fast-safe-stringify/CHANGELOG.md b/build/node_modules/fast-safe-stringify/CHANGELOG.md new file mode 100644 index 00000000..55f2d082 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +## v.2.0.0 + +Features + +- Added stable-stringify (see documentation) +- Support replacer +- Support spacer +- toJSON support without forceDecirc property +- Improved performance + +Breaking changes + +- Manipulating the input value in a `toJSON` function is not possible anymore in + all cases (see documentation) +- Dropped support for e.g. IE8 and Node.js < 4 diff --git a/build/node_modules/fast-safe-stringify/LICENSE b/build/node_modules/fast-safe-stringify/LICENSE new file mode 100644 index 00000000..d310c2d1 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Mark Clements +Copyright (c) 2017 David Mark Clements & Matteo Collina +Copyright (c) 2018 David Mark Clements, Matteo Collina & Ruben Bridgewater + +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. diff --git a/build/node_modules/fast-safe-stringify/benchmark.js b/build/node_modules/fast-safe-stringify/benchmark.js new file mode 100644 index 00000000..7ba5e9f5 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/benchmark.js @@ -0,0 +1,137 @@ +const Benchmark = require('benchmark') +const suite = new Benchmark.Suite() +const { inspect } = require('util') +const jsonStringifySafe = require('json-stringify-safe') +const fastSafeStringify = require('./') + +const array = new Array(10).fill(0).map((_, i) => i) +const obj = { foo: array } +const circ = JSON.parse(JSON.stringify(obj)) +circ.o = { obj: circ, array } +const circGetters = JSON.parse(JSON.stringify(obj)) +Object.assign(circGetters, { get o () { return { obj: circGetters, array } } }) + +const deep = require('./package.json') +deep.deep = JSON.parse(JSON.stringify(deep)) +deep.deep.deep = JSON.parse(JSON.stringify(deep)) +deep.deep.deep.deep = JSON.parse(JSON.stringify(deep)) +deep.array = array + +const deepCirc = JSON.parse(JSON.stringify(deep)) +deepCirc.deep.deep.deep.circ = deepCirc +deepCirc.deep.deep.circ = deepCirc +deepCirc.deep.circ = deepCirc +deepCirc.array = array + +const deepCircGetters = JSON.parse(JSON.stringify(deep)) +for (let i = 0; i < 10; i++) { + deepCircGetters[i.toString()] = { + deep: { + deep: { + get circ () { return deep.deep }, + deep: { get circ () { return deep.deep.deep } } + }, + get circ () { return deep } + }, + get array () { return array } + } +} + +const deepCircNonCongifurableGetters = JSON.parse(JSON.stringify(deep)) +Object.defineProperty(deepCircNonCongifurableGetters.deep.deep.deep, 'circ', { + get: () => deepCircNonCongifurableGetters, + enumerable: true, + configurable: false +}) +Object.defineProperty(deepCircNonCongifurableGetters.deep.deep, 'circ', { + get: () => deepCircNonCongifurableGetters, + enumerable: true, + configurable: false +}) +Object.defineProperty(deepCircNonCongifurableGetters.deep, 'circ', { + get: () => deepCircNonCongifurableGetters, + enumerable: true, + configurable: false +}) +Object.defineProperty(deepCircNonCongifurableGetters, 'array', { + get: () => array, + enumerable: true, + configurable: false +}) + +suite.add('util.inspect: simple object ', function () { + inspect(obj, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: circular ', function () { + inspect(circ, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: circular getters ', function () { + inspect(circGetters, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: deep ', function () { + inspect(deep, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: deep circular ', function () { + inspect(deepCirc, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: large deep circular getters ', function () { + inspect(deepCircGetters, { showHidden: false, depth: null }) +}) +suite.add('util.inspect: deep non-conf circular getters', function () { + inspect(deepCircNonCongifurableGetters, { showHidden: false, depth: null }) +}) + +suite.add('\njson-stringify-safe: simple object ', function () { + jsonStringifySafe(obj) +}) +suite.add('json-stringify-safe: circular ', function () { + jsonStringifySafe(circ) +}) +suite.add('json-stringify-safe: circular getters ', function () { + jsonStringifySafe(circGetters) +}) +suite.add('json-stringify-safe: deep ', function () { + jsonStringifySafe(deep) +}) +suite.add('json-stringify-safe: deep circular ', function () { + jsonStringifySafe(deepCirc) +}) +suite.add('json-stringify-safe: large deep circular getters ', function () { + jsonStringifySafe(deepCircGetters) +}) +suite.add('json-stringify-safe: deep non-conf circular getters', function () { + jsonStringifySafe(deepCircNonCongifurableGetters) +}) + +suite.add('\nfast-safe-stringify: simple object ', function () { + fastSafeStringify(obj) +}) +suite.add('fast-safe-stringify: circular ', function () { + fastSafeStringify(circ) +}) +suite.add('fast-safe-stringify: circular getters ', function () { + fastSafeStringify(circGetters) +}) +suite.add('fast-safe-stringify: deep ', function () { + fastSafeStringify(deep) +}) +suite.add('fast-safe-stringify: deep circular ', function () { + fastSafeStringify(deepCirc) +}) +suite.add('fast-safe-stringify: large deep circular getters ', function () { + fastSafeStringify(deepCircGetters) +}) +suite.add('fast-safe-stringify: deep non-conf circular getters', function () { + fastSafeStringify(deepCircNonCongifurableGetters) +}) + +// add listeners +suite.on('cycle', function (event) { + console.log(String(event.target)) +}) + +suite.on('complete', function () { + console.log('\nFastest is ' + this.filter('fastest').map('name')) +}) + +suite.run({ delay: 1, minSamples: 150 }) diff --git a/build/node_modules/fast-safe-stringify/index.d.ts b/build/node_modules/fast-safe-stringify/index.d.ts new file mode 100644 index 00000000..56f68653 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/index.d.ts @@ -0,0 +1,8 @@ +declare function stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; + +declare namespace stringify { + export function stable(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; + export function stableStringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; +} + +export default stringify; diff --git a/build/node_modules/fast-safe-stringify/index.js b/build/node_modules/fast-safe-stringify/index.js new file mode 100644 index 00000000..670698d6 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/index.js @@ -0,0 +1,161 @@ +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var arr = [] +var replacerStack = [] + +// Regular stringify +function stringify (obj, replacer, spacer) { + decirc(obj, '', [], undefined) + var res + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + return res +} +function decirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, stack, val) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, stack, val) + } + } + stack.pop() + } +} + +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} + +function deterministicStringify (obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj + var res + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + return res +} + +function deterministicDecirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + if (typeof val.toJSON === 'function') { + return + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, stack, val) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, stack, val) + tmp[key] = val[key] + } + if (parent !== undefined) { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } +} + +// wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] +function replaceGetterValues (replacer) { + replacer = replacer !== undefined ? replacer : function (k, v) { return v } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = '[Circular]' + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) + } +} diff --git a/build/node_modules/fast-safe-stringify/package.json b/build/node_modules/fast-safe-stringify/package.json new file mode 100644 index 00000000..d285d4de --- /dev/null +++ b/build/node_modules/fast-safe-stringify/package.json @@ -0,0 +1,87 @@ +{ + "_from": "fast-safe-stringify@^2.0.4", + "_id": "fast-safe-stringify@2.0.7", + "_inBundle": false, + "_integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==", + "_location": "/fast-safe-stringify", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "fast-safe-stringify@^2.0.4", + "name": "fast-safe-stringify", + "escapedName": "fast-safe-stringify", + "rawSpec": "^2.0.4", + "saveSpec": null, + "fetchSpec": "^2.0.4" + }, + "_requiredBy": [ + "/logform" + ], + "_resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz", + "_shasum": "124aa885899261f68aedb42a7c080de9da608743", + "_spec": "fast-safe-stringify@^2.0.4", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/logform", + "author": { + "name": "David Mark Clements" + }, + "bugs": { + "url": "https://github.com/davidmarkclements/fast-safe-stringify/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Ruben Bridgewater" + }, + { + "name": "Matteo Collina" + }, + { + "name": "Ben Gourley" + }, + { + "name": "Gabriel Lesperance" + }, + { + "name": "Alex Liu" + }, + { + "name": "Christoph Walcher" + }, + { + "name": "Nicholas Young" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Safely and quickly serialize JavaScript objects", + "devDependencies": { + "benchmark": "^2.1.4", + "clone": "^2.1.0", + "json-stringify-safe": "^5.0.1", + "standard": "^11.0.0", + "tap": "^12.0.0" + }, + "homepage": "https://github.com/davidmarkclements/fast-safe-stringify#readme", + "keywords": [ + "stable", + "stringify", + "JSON", + "JSON.stringify", + "safe", + "serialize" + ], + "license": "MIT", + "main": "index.js", + "name": "fast-safe-stringify", + "repository": { + "type": "git", + "url": "git+https://github.com/davidmarkclements/fast-safe-stringify.git" + }, + "scripts": { + "benchmark": "node benchmark.js", + "test": "standard && tap --no-esm test.js test-stable.js" + }, + "typings": "index", + "version": "2.0.7" +} diff --git a/build/node_modules/fast-safe-stringify/readme.md b/build/node_modules/fast-safe-stringify/readme.md new file mode 100644 index 00000000..51ed1fb1 --- /dev/null +++ b/build/node_modules/fast-safe-stringify/readme.md @@ -0,0 +1,154 @@ +# fast-safe-stringify + +Safe and fast serialization alternative to [JSON.stringify][]. + +Gracefully handles circular structures instead of throwing. + +Provides a deterministic ("stable") version as well that will also gracefully +handle circular structures. See the example below for further information. + +## Usage + +The same as [JSON.stringify][]. + +`stringify(value[, replacer[, space]])` + +```js +const safeStringify = require('fast-safe-stringify') +const o = { a: 1 } +o.o = o + +console.log(safeStringify(o)) +// '{"a":1,"o":"[Circular]"}' +console.log(JSON.stringify(o)) +// TypeError: Converting circular structure to JSON + +function replacer(key, value) { + console.log('Key:', JSON.stringify(key), 'Value:', JSON.stringify(value)) + // Remove the circular structure + if (value === '[Circular]') { + return + } + return value +} +const serialized = safeStringify(o, replacer, 2) +// Key: "" Value: {"a":1,"o":"[Circular]"} +// Key: "a" Value: 1 +// Key: "o" Value: "[Circular]" +console.log(serialized) +// { +// "a": 1 +// } +``` + +Using the deterministic version also works the same: + +```js +const safeStringify = require('fast-safe-stringify') +const o = { b: 1, a: 0 } +o.o = o + +console.log(safeStringify(o)) +// '{"b":1,"a":0,"o":"[Circular]"}' +console.log(safeStringify.stableStringify(o)) +// '{"a":0,"b":1,"o":"[Circular]"}' +console.log(JSON.stringify(o)) +// TypeError: Converting circular structure to JSON +``` + +A faster and side-effect free implementation is available in the +[safe-stable-stringify][] module. However it is still considered experimental +due to a new and more complex implementation. + +## Differences to JSON.stringify + +In general the behavior is identical to [JSON.stringify][]. The [`replacer`][] +and [`space`][] options are also available. + +A few exceptions exist to [JSON.stringify][] while using [`toJSON`][] or +[`replacer`][]: + +### Regular safe stringify + +- Manipulating a circular structure of the passed in value in a `toJSON` or the + `replacer` is not possible! It is possible for any other value and property. + +- In case a circular structure is detected and the [`replacer`][] is used it + will receive the string `[Circular]` as the argument instead of the circular + object itself. + +### Deterministic ("stable") safe stringify + +- Manipulating the input object either in a [`toJSON`][] or the [`replacer`][] + function will not have any effect on the output. The output entirely relies on + the shape the input value had at the point passed to the stringify function! + +- In case a circular structure is detected and the [`replacer`][] is used it + will receive the string `[Circular]` as the argument instead of the circular + object itself. + +A side effect free variation without these limitations can be found as well +([`safe-stable-stringify`][]). It is also faster than the current +implementation. It is still considered experimental due to a new and more +complex implementation. + +## Benchmarks + +Although not JSON, the Node.js `util.inspect` method can be used for similar +purposes (e.g. logging) and also handles circular references. + +Here we compare `fast-safe-stringify` with some alternatives: +(Lenovo T450s with a i7-5600U CPU using Node.js 8.9.4) + +```md +fast-safe-stringify: simple object x 1,121,497 ops/sec ±0.75% (97 runs sampled) +fast-safe-stringify: circular x 560,126 ops/sec ±0.64% (96 runs sampled) +fast-safe-stringify: deep x 32,472 ops/sec ±0.57% (95 runs sampled) +fast-safe-stringify: deep circular x 32,513 ops/sec ±0.80% (92 runs sampled) + +util.inspect: simple object x 272,837 ops/sec ±1.48% (90 runs sampled) +util.inspect: circular x 116,896 ops/sec ±1.19% (95 runs sampled) +util.inspect: deep x 19,382 ops/sec ±0.66% (92 runs sampled) +util.inspect: deep circular x 18,717 ops/sec ±0.63% (96 runs sampled) + +json-stringify-safe: simple object x 233,621 ops/sec ±0.97% (94 runs sampled) +json-stringify-safe: circular x 110,409 ops/sec ±1.85% (95 runs sampled) +json-stringify-safe: deep x 8,705 ops/sec ±0.87% (96 runs sampled) +json-stringify-safe: deep circular x 8,336 ops/sec ±2.20% (93 runs sampled) +``` + +For stable stringify comparisons, see the performance benchmarks in the +[`safe-stable-stringify`][] readme. + +## Protip + +Whether `fast-safe-stringify` or alternatives are used: if the use case +consists of deeply nested objects without circular references the following +pattern will give best results. +Shallow or one level nested objects on the other hand will slow down with it. +It is entirely dependant on the use case. + +```js +const stringify = require('fast-safe-stringify') + +function tryJSONStringify (obj) { + try { return JSON.stringify(obj) } catch (_) {} +} + +const serializedString = tryJSONStringify(deep) || stringify(deep) +``` + +## Acknowledgements + +Sponsored by [nearForm](http://nearform.com) + +## License + +MIT + +[`replacer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter +[`safe-stable-stringify`]: https://github.com/BridgeAR/safe-stable-stringify +[`space`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20space%20argument +[`toJSON`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior +[benchmark]: https://github.com/epoberezkin/fast-json-stable-stringify/blob/67f688f7441010cfef91a6147280cc501701e83b/benchmark +[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify diff --git a/build/node_modules/fast-safe-stringify/test-stable.js b/build/node_modules/fast-safe-stringify/test-stable.js new file mode 100644 index 00000000..93d8bc4b --- /dev/null +++ b/build/node_modules/fast-safe-stringify/test-stable.js @@ -0,0 +1,311 @@ +const test = require('tap').test +const fss = require('./').stable +const clone = require('clone') +const s = JSON.stringify + +test('circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.circle = fixture + const expected = s( + { circle: '[Circular]', name: 'Tywin Lannister' } + ) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('circular getter reference to root', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + + const expected = s( + { circle: '[Circular]', name: 'Tywin Lannister' } + ) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.id = { circle: fixture } + const expected = s( + { id: { circle: '[Circular]' }, name: 'Tywin Lannister' } + ) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('child circular reference', function (assert) { + const fixture = { name: 'Tywin Lannister', child: { name: 'Tyrion Lannister' } } + fixture.child.dinklage = fixture.child + const expected = s({ + child: { + dinklage: '[Circular]', name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested child circular reference', function (assert) { + const fixture = { name: 'Tywin Lannister', child: { name: 'Tyrion Lannister' } } + fixture.child.actor = { dinklage: fixture.child } + const expected = s({ + child: { + actor: { dinklage: '[Circular]' }, name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('circular objects in an array', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.hand = [fixture, fixture] + const expected = s({ + hand: ['[Circular]', '[Circular]'], name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested circular references in an array', function (assert) { + const fixture = { + name: 'Tywin Lannister', + offspring: [{ name: 'Tyrion Lannister' }, { name: 'Cersei Lannister' }] + } + fixture.offspring[0].dinklage = fixture.offspring[0] + fixture.offspring[1].headey = fixture.offspring[1] + + const expected = s({ + name: 'Tywin Lannister', + offspring: [ + { dinklage: '[Circular]', name: 'Tyrion Lannister' }, + { headey: '[Circular]', name: 'Cersei Lannister' } + ] + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('circular arrays', function (assert) { + const fixture = [] + fixture.push(fixture, fixture) + const expected = s(['[Circular]', '[Circular]']) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested circular arrays', function (assert) { + const fixture = [] + fixture.push( + { name: 'Jon Snow', bastards: fixture }, + { name: 'Ramsay Bolton', bastards: fixture } + ) + const expected = s([ + { bastards: '[Circular]', name: 'Jon Snow' }, + { bastards: '[Circular]', name: 'Ramsay Bolton' } + ]) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('repeated non-circular references in objects', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = { + motherOfDragons: daenerys, + queenOfMeereen: daenerys + } + const expected = s(fixture) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('repeated non-circular references in arrays', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = [daenerys, daenerys] + const expected = s(fixture) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('double child circular reference', function (assert) { + // create circular reference + const child = { name: 'Tyrion Lannister' } + child.dinklage = child + + // include it twice in the fixture + const fixture = { name: 'Tywin Lannister', childA: child, childB: child } + const cloned = clone(fixture) + const expected = s({ + childA: { + dinklage: '[Circular]', name: 'Tyrion Lannister' + }, + childB: { + dinklage: '[Circular]', name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister' + }) + const actual = fss(fixture) + assert.is(actual, expected) + + // check if the fixture has not been modified + assert.deepEqual(fixture, cloned) + assert.end() +}) + +test('child circular reference with toJSON', function (assert) { + // Create a test object that has an overriden `toJSON` property + TestObject.prototype.toJSON = function () { return { special: 'case' } } + function TestObject (content) {} + + // Creating a simple circular object structure + const parentObject = {} + parentObject.childObject = new TestObject() + parentObject.childObject.parentObject = parentObject + + // Creating a simple circular object structure + const otherParentObject = new TestObject() + otherParentObject.otherChildObject = {} + otherParentObject.otherChildObject.otherParentObject = otherParentObject + + // Making sure our original tests work + assert.deepEqual(parentObject.childObject.parentObject, parentObject) + assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject) + + // Should both be idempotent + assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}') + assert.equal(fss(otherParentObject), '{"special":"case"}') + + // Therefore the following assertion should be `true` + assert.deepEqual(parentObject.childObject.parentObject, parentObject) + assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject) + + assert.end() +}) + +test('null object', function (assert) { + const expected = s(null) + const actual = fss(null) + assert.is(actual, expected) + assert.end() +}) + +test('null property', function (assert) { + const expected = s({ f: null }) + const actual = fss({ f: null }) + assert.is(actual, expected) + assert.end() +}) + +test('nested child circular reference in toJSON', function (assert) { + var circle = { some: 'data' } + circle.circle = circle + var a = { + b: { + toJSON: function () { + a.b = 2 + return '[Redacted]' + } + }, + baz: { + circle, + toJSON: function () { + a.baz = circle + return '[Redacted]' + } + } + } + var o = { + a, + bar: a + } + + const expected = s({ + a: { + b: '[Redacted]', + baz: '[Redacted]' + }, + bar: { + // TODO: This is a known limitation of the current implementation. + // The ideal result would be: + // + // b: 2, + // baz: { + // circle: '[Circular]', + // some: 'data' + // } + // + b: '[Redacted]', + baz: '[Redacted]' + } + }) + const actual = fss(o) + assert.is(actual, expected) + assert.end() +}) + +test('circular getters are restored when stringified', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + fss(fixture) + + assert.is(fixture.circle, fixture) + assert.end() +}) + +test('non-configurable circular getters use a replacer instead of markers', function (assert) { + const fixture = { name: 'Tywin Lannister' } + Object.defineProperty(fixture, 'circle', { + configurable: false, + get: function () { return fixture }, + enumerable: true + }) + + fss(fixture) + + assert.is(fixture.circle, fixture) + assert.end() +}) + +test('getter child circular reference', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + get dinklage () { return fixture.child } + }, + get self () { return fixture } + } + + const expected = s({ + child: { + dinklage: '[Circular]', name: 'Tyrion Lannister' + }, + name: 'Tywin Lannister', + self: '[Circular]' + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) diff --git a/build/node_modules/fast-safe-stringify/test.js b/build/node_modules/fast-safe-stringify/test.js new file mode 100644 index 00000000..7da5821c --- /dev/null +++ b/build/node_modules/fast-safe-stringify/test.js @@ -0,0 +1,304 @@ +const test = require('tap').test +const fss = require('./') +const clone = require('clone') +const s = JSON.stringify + +test('circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.circle = fixture + const expected = s( + { name: 'Tywin Lannister', circle: '[Circular]' } + ) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('circular getter reference to root', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + const expected = s( + { name: 'Tywin Lannister', circle: '[Circular]' } + ) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested circular reference to root', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.id = { circle: fixture } + const expected = s( + { name: 'Tywin Lannister', id: { circle: '[Circular]' } } + ) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('child circular reference', function (assert) { + const fixture = { name: 'Tywin Lannister', child: { name: 'Tyrion Lannister' } } + fixture.child.dinklage = fixture.child + const expected = s({ + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', dinklage: '[Circular]' + } + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested child circular reference', function (assert) { + const fixture = { name: 'Tywin Lannister', child: { name: 'Tyrion Lannister' } } + fixture.child.actor = { dinklage: fixture.child } + const expected = s({ + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', actor: { dinklage: '[Circular]' } + } + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('circular objects in an array', function (assert) { + const fixture = { name: 'Tywin Lannister' } + fixture.hand = [fixture, fixture] + const expected = s({ + name: 'Tywin Lannister', hand: ['[Circular]', '[Circular]'] + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested circular references in an array', function (assert) { + const fixture = { + name: 'Tywin Lannister', + offspring: [{ name: 'Tyrion Lannister' }, { name: 'Cersei Lannister' }] + } + fixture.offspring[0].dinklage = fixture.offspring[0] + fixture.offspring[1].headey = fixture.offspring[1] + + const expected = s({ + name: 'Tywin Lannister', + offspring: [ + { name: 'Tyrion Lannister', dinklage: '[Circular]' }, + { name: 'Cersei Lannister', headey: '[Circular]' } + ] + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('circular arrays', function (assert) { + const fixture = [] + fixture.push(fixture, fixture) + const expected = s(['[Circular]', '[Circular]']) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('nested circular arrays', function (assert) { + const fixture = [] + fixture.push( + { name: 'Jon Snow', bastards: fixture }, + { name: 'Ramsay Bolton', bastards: fixture } + ) + const expected = s([ + { name: 'Jon Snow', bastards: '[Circular]' }, + { name: 'Ramsay Bolton', bastards: '[Circular]' } + ]) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('repeated non-circular references in objects', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = { + motherOfDragons: daenerys, + queenOfMeereen: daenerys + } + const expected = s(fixture) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('repeated non-circular references in arrays', function (assert) { + const daenerys = { name: 'Daenerys Targaryen' } + const fixture = [daenerys, daenerys] + const expected = s(fixture) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) + +test('double child circular reference', function (assert) { + // create circular reference + const child = { name: 'Tyrion Lannister' } + child.dinklage = child + + // include it twice in the fixture + const fixture = { name: 'Tywin Lannister', childA: child, childB: child } + const cloned = clone(fixture) + const expected = s({ + name: 'Tywin Lannister', + childA: { + name: 'Tyrion Lannister', dinklage: '[Circular]' + }, + childB: { + name: 'Tyrion Lannister', dinklage: '[Circular]' + } + }) + const actual = fss(fixture) + assert.is(actual, expected) + + // check if the fixture has not been modified + assert.deepEqual(fixture, cloned) + assert.end() +}) + +test('child circular reference with toJSON', function (assert) { + // Create a test object that has an overriden `toJSON` property + TestObject.prototype.toJSON = function () { return { special: 'case' } } + function TestObject (content) {} + + // Creating a simple circular object structure + const parentObject = {} + parentObject.childObject = new TestObject() + parentObject.childObject.parentObject = parentObject + + // Creating a simple circular object structure + const otherParentObject = new TestObject() + otherParentObject.otherChildObject = {} + otherParentObject.otherChildObject.otherParentObject = otherParentObject + + // Making sure our original tests work + assert.deepEqual(parentObject.childObject.parentObject, parentObject) + assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject) + + // Should both be idempotent + assert.equal(fss(parentObject), '{"childObject":{"special":"case"}}') + assert.equal(fss(otherParentObject), '{"special":"case"}') + + // Therefore the following assertion should be `true` + assert.deepEqual(parentObject.childObject.parentObject, parentObject) + assert.deepEqual(otherParentObject.otherChildObject.otherParentObject, otherParentObject) + + assert.end() +}) + +test('null object', function (assert) { + const expected = s(null) + const actual = fss(null) + assert.is(actual, expected) + assert.end() +}) + +test('null property', function (assert) { + const expected = s({ f: null }) + const actual = fss({ f: null }) + assert.is(actual, expected) + assert.end() +}) + +test('nested child circular reference in toJSON', function (assert) { + const circle = { some: 'data' } + circle.circle = circle + const a = { + b: { + toJSON: function () { + a.b = 2 + return '[Redacted]' + } + }, + baz: { + circle, + toJSON: function () { + a.baz = circle + return '[Redacted]' + } + } + } + const o = { + a, + bar: a + } + + const expected = s({ + a: { + b: '[Redacted]', + baz: '[Redacted]' + }, + bar: { + b: 2, + baz: { + some: 'data', + circle: '[Circular]' + } + } + }) + const actual = fss(o) + assert.is(actual, expected) + assert.end() +}) + +test('circular getters are restored when stringified', function (assert) { + const fixture = { + name: 'Tywin Lannister', + get circle () { + return fixture + } + } + fss(fixture) + + assert.is(fixture.circle, fixture) + assert.end() +}) + +test('non-configurable circular getters use a replacer instead of markers', function (assert) { + const fixture = { name: 'Tywin Lannister' } + Object.defineProperty(fixture, 'circle', { + configurable: false, + get: function () { return fixture }, + enumerable: true + }) + + fss(fixture) + + assert.is(fixture.circle, fixture) + assert.end() +}) + +test('getter child circular reference are replaced instead of marked', function (assert) { + const fixture = { + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', + get dinklage () { return fixture.child } + }, + get self () { return fixture } + } + + const expected = s({ + name: 'Tywin Lannister', + child: { + name: 'Tyrion Lannister', dinklage: '[Circular]' + }, + self: '[Circular]' + }) + const actual = fss(fixture) + assert.is(actual, expected) + assert.end() +}) diff --git a/build/node_modules/fecha/CHANGELOG.md b/build/node_modules/fecha/CHANGELOG.md new file mode 100644 index 00000000..18dc0db9 --- /dev/null +++ b/build/node_modules/fecha/CHANGELOG.md @@ -0,0 +1,71 @@ +### 4.2.1 +- Fixed missing source map +- Fixed security y18n + +### 4.2.0 +Added isoDate and isoDateTime masks + +### 4.1.0 +Added Z format/parse and fixed Peru timezone issue +- Added `Z` format token. See readme for more info. Big thanks to @fer22f for writing the code. +- Fixed a strange issue when Peru changed timezones in 1990. See #78 + +## 4.0.0 +**Major Features and Breaking changes in this version** + +#### Improvements +- *Valid date parsing* - By default fecha will check validity of dates. Previously `2019-55-01` or `2019-01-42` would parse correctly, since Javascript can handle it. Now invalid dates will return `null` instead +- *ES Module and Tree Shaking Support* - You can now import fecha `parse` or `format` independently +```js +import {format, parse} from 'fecha'; + +format(...); +parse(...) +``` + +#### Breaking changes +- `parseDate` may return `null` when previously returned a `Date`. See improvements above, but invalid dates will return `null` now +- Change to how to set masks and i18n +Previously +```js +import fecha from 'fecha'; + +fecha.i18n = { ... } +fecha.masks.myMask = 'DD , MM, YYYY' +``` + +New +```js +import {parse, format, setGlobalDateI18n, setGlobalDateMasks} from 'fecha'; + +setGlobalDateI18n({ + // ... +}) +setGlobalDateMasks({ + myMask: 'DD , MM, YYYY' +}); +``` + +### 3.0.3 +- Fixed bug when using brackets when parsing dates +### 3.0.2 +- Fixed issue where src files are not included correctly in npm + +### 3.0.0 +- Moved to ES modules +- Changed invalid date from `false` to `null` + +### 2.3.3 +Fixed bug with year 999 not having leading zero + +### 2.3.2 +Added typescript definitions to NPM + +### 2.3.0 +Added strict version of date parser that returns null on invalid dates (may use strict version in v3) + +### 2.2.0 +Fixed a bug when parsing Do format dates + +## 2.0.0 +Fecha now throws errors on invalid dates in `fecha.format` and is stricter about what dates it accepts. Dates must pass `Object.prototype.toString.call(dateObj) !== '[object Date]'`. diff --git a/build/node_modules/fecha/LICENSE b/build/node_modules/fecha/LICENSE new file mode 100644 index 00000000..cc9084b0 --- /dev/null +++ b/build/node_modules/fecha/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Taylor Hakes + +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. + diff --git a/build/node_modules/fecha/README.md b/build/node_modules/fecha/README.md new file mode 100644 index 00000000..b128a5a8 --- /dev/null +++ b/build/node_modules/fecha/README.md @@ -0,0 +1,320 @@ +# fecha [![Build Status](https://travis-ci.org/taylorhakes/fecha.svg?branch=master)](https://travis-ci.org/taylorhakes/fecha) + +Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. + +### NPM +``` +npm install fecha --save +``` +### Yarn +``` +yarn add fecha +``` + +### Fecha vs Moment + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FechaMoment
Size (Min. and Gzipped)2.1KBs13.1KBs
Date Parsing
Date Formatting
Date Manipulation
I18n Support
+ +## Use it + +#### Formatting +`format` accepts a Date object (or timestamp) and a string format and returns a formatted string. See below for +available format tokens. + +Note: `format` will throw an error when passed invalid parameters +```js +import { format } from 'fecha'; + +type format = (date: Date, format?: string, i18n?: I18nSettings) => str; + +// Custom formats +format(new Date(2015, 10, 20), 'dddd MMMM Do, YYYY'); // 'Friday November 20th, 2015' +format(new Date(1998, 5, 3, 15, 23, 10, 350), 'YYYY-MM-DD hh:mm:ss.SSS A'); // '1998-06-03 03:23:10.350 PM' + +// Named masks +format(new Date(2015, 10, 20), 'isoDate'); // '2015-11-20' +format(new Date(2015, 10, 20), 'mediumDate'); // 'Nov 20, 2015' +format(new Date(2015, 10, 20, 3, 2, 1), 'isoDateTime'); // '2015-11-20T03:02:01-05:00' +format(new Date(2015, 2, 10, 5, 30, 20), 'shortTime'); // '05:30' + +// Literals +format(new Date(2001, 2, 5, 6, 7, 2, 5), '[on] MM-DD-YYYY [at] HH:mm'); // 'on 03-05-2001 at 06:07' +``` + +#### Parsing +`parse` accepts a Date string and a string format and returns a Date object. See below for available format tokens. + +*NOTE*: `parse` will throw an error when passed invalid string format or missing format. You MUST specify a format. +```js +import { parse } from 'fecha'; + +type parse = (dateStr: string, format: string, i18n?: I18nSettingsOptional) => Date|null; + +// Custom formats +parse('February 3rd, 2014', 'MMMM Do, YYYY'); // new Date(2014, 1, 3) +parse('10-12-10 14:11:12', 'YY-MM-DD HH:mm:ss'); // new Date(2010, 11, 10, 14, 11, 12) + +// Named masks +parse('5/3/98', 'shortDate'); // new Date(1998, 4, 3) +parse('November 4, 2005', 'longDate'); // new Date(2005, 10, 4) +parse('2015-11-20T03:02:01-05:00', 'isoDateTime'); // new Date(2015, 10, 20, 3, 2, 1) + +// Override i18n +parse('4 de octubre de 1983', 'M de MMMM de YYYY', { + monthNames: [ + 'enero', + 'febrero', + 'marzo', + 'abril', + 'mayo', + 'junio', + 'julio', + 'agosto', + 'septiembre', + 'octubre', + 'noviembre', + 'diciembre' + ] +}); // new Date(1983, 9, 4) +``` + +#### i18n Support +```js +import {setGlobalDateI18n} from 'fecha'; + +/* +Default I18n Settings +{ + dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'], + dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + amPm: ['am', 'pm'], + // D is the day of the month, function returns something like... 3rd or 11th + DoFn(dayOfMonth) { + return dayOfMonth + [ 'th', 'st', 'nd', 'rd' ][ dayOfMonth % 10 > 3 ? 0 : (dayOfMonth - dayOfMonth % 10 !== 10) * dayOfMonth % 10 ]; + } +} +*/ + +setGlobalDateI18n({ + dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'], + dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + amPm: ['am', 'pm'], + // D is the day of the month, function returns something like... 3rd or 11th + DoFn: function (D) { + return D + [ 'th', 'st', 'nd', 'rd' ][ D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10 ]; + } +}); + +``` + +#### Custom Named Masks +```js +import { format, setGlobalDateMasks } from 'fecha'; +/* +Default global masks +{ + default: 'ddd MMM DD YYYY HH:mm:ss', + shortDate: 'M/D/YY', + mediumDate: 'MMM D, YYYY', + longDate: 'MMMM D, YYYY', + fullDate: 'dddd, MMMM D, YYYY', + shortTime: 'HH:mm', + mediumTime: 'HH:mm:ss', + longTime: 'HH:mm:ss.SSS' +} +*/ + +// Create a new mask +setGlobalDateMasks({ + myMask: 'HH:mm:ss YY/MM/DD'; +}); + +// Use it +format(new Date(2014, 5, 6, 14, 10, 45), 'myMask'); // '14:10:45 14/06/06' +``` + +### Formatting Tokens + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TokenOutput
MonthM1 2 ... 11 12
MM01 02 ... 11 12
MMMJan Feb ... Nov Dec
MMMMJanuary February ... November December
Day of MonthD1 2 ... 30 31
Do1st 2nd ... 30th 31st
DD01 02 ... 30 31
Day of Weekd0 1 ... 5 6
dddSun Mon ... Fri Sat
ddddSunday Monday ... Friday Saturday
YearYY70 71 ... 29 30
YYYY1970 1971 ... 2029 2030
AM/PMAAM PM
aam pm
HourH0 1 ... 22 23
HH00 01 ... 22 23
h1 2 ... 11 12
hh01 02 ... 11 12
Minutem0 1 ... 58 59
mm00 01 ... 58 59
Seconds0 1 ... 58 59
ss00 01 ... 58 59
Fractional SecondS0 1 ... 8 9
SS0 1 ... 98 99
SSS0 1 ... 998 999
TimezoneZ + -07:00 -06:00 ... +06:00 +07:00 +
ZZ + -0700 -0600 ... +0600 +0700 +
diff --git a/build/node_modules/fecha/dist/fecha.min.js b/build/node_modules/fecha/dist/fecha.min.js new file mode 100644 index 00000000..a8496ccc --- /dev/null +++ b/build/node_modules/fecha/dist/fecha.min.js @@ -0,0 +1,2 @@ +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.fecha={})}(this,function(t){"use strict";var n=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,e="[^\\s]+",r=/\[([^]*?)\]/gm;function o(t,n){for(var e=[],r=0,o=t.length;r-1?r:null}};function a(t){for(var n=[],e=1;e3?0:(t-t%10!=10?1:0)*t%10]}},m=a({},f),c=function(t){return m=a(m,t)},l=function(t){return t.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},h=function(t,n){for(void 0===n&&(n=2),t=String(t);t.length0?"-":"+")+h(100*Math.floor(Math.abs(n)/60)+Math.abs(n)%60,4)},Z:function(t){var n=t.getTimezoneOffset();return(n>0?"-":"+")+h(Math.floor(Math.abs(n)/60),2)+":"+h(Math.abs(n)%60,2)}},M=function(t){return+t-1},D=[null,"[1-9]\\d?"],Y=[null,e],p=["isPm",e,function(t,n){var e=t.toLowerCase();return e===n.amPm[0]?0:e===n.amPm[1]?1:null}],y=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(t){var n=(t+"").match(/([+-]|\d\d)/gi);if(n){var e=60*+n[1]+parseInt(n[2],10);return"+"===n[0]?e:-e}return 0}],S={D:["day","[1-9]\\d?"],DD:["day","\\d\\d"],Do:["day","[1-9]\\d?"+e,function(t){return parseInt(t,10)}],M:["month","[1-9]\\d?",M],MM:["month","\\d\\d",M],YY:["year","\\d\\d",function(t){var n=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+t>68?n-1:n)+t)}],h:["hour","[1-9]\\d?",void 0,"isPm"],hh:["hour","\\d\\d",void 0,"isPm"],H:["hour","[1-9]\\d?"],HH:["hour","\\d\\d"],m:["minute","[1-9]\\d?"],mm:["minute","\\d\\d"],s:["second","[1-9]\\d?"],ss:["second","\\d\\d"],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(t){return 100*+t}],SS:["millisecond","\\d\\d",function(t){return 10*+t}],SSS:["millisecond","\\d{3}"],d:D,dd:D,ddd:Y,dddd:Y,MMM:["month",e,u("monthNamesShort")],MMMM:["month",e,u("monthNames")],a:p,A:p,ZZ:y,Z:y},v={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},H=function(t){return a(v,t)},b=function(t,e,o){if(void 0===e&&(e=v.default),void 0===o&&(o={}),"number"==typeof t&&(t=new Date(t)),"[object Date]"!==Object.prototype.toString.call(t)||isNaN(t.getTime()))throw new Error("Invalid Date pass to format");var u=[];e=(e=v[e]||e).replace(r,function(t,n){return u.push(n),"@@@"});var i=a(a({},m),o);return(e=e.replace(n,function(n){return g[n](t,i)})).replace(/@@@/g,function(){return u.shift()})};function w(t,e,o){if(void 0===o&&(o={}),"string"!=typeof e)throw new Error("Invalid format in fecha parse");if(e=v[e]||e,t.length>1e3)return null;var u={year:(new Date).getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},i=[],d=[],s=e.replace(r,function(t,n){return d.push(l(n)),"@@@"}),f={},c={};s=l(s).replace(n,function(t){var n=S[t],e=n[0],r=n[1],o=n[3];if(f[e])throw new Error("Invalid format. "+e+" specified twice in format");return f[e]=!0,o&&(c[o]=!0),i.push(n),"("+r+")"}),Object.keys(c).forEach(function(t){if(!f[t])throw new Error("Invalid format. "+t+" is required in specified format")}),s=s.replace(/@@@/g,function(){return d.shift()});var h=t.match(new RegExp(s,"i"));if(!h)return null;for(var g=a(a({},m),o),M=1;M;\n\nexport type Days = [string, string, string, string, string, string, string];\nexport type Months = [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string\n];\n\nfunction shorten(arr: T, sLen: number): string[] {\n const newArr: string[] = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\n\nconst monthUpdate = (\n arrName: \"monthNames\" | \"monthNamesShort\" | \"dayNames\" | \"dayNamesShort\"\n) => (v: string, i18n: I18nSettings): number | null => {\n const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());\n const index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n};\n\nexport function assign(a: A): A;\nexport function assign(a: A, b: B): A & B;\nexport function assign(a: A, b: B, c: C): A & B & C;\nexport function assign(a: A, b: B, c: C, d: D): A & B & C & D;\nexport function assign(origObj: any, ...args: any[]): any {\n for (const obj of args) {\n for (const key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\n\nconst dayNames: Days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nconst monthNames: Months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\n\nconst monthNamesShort: Months = shorten(monthNames, 3) as Months;\nconst dayNamesShort: Days = shorten(dayNames, 3) as Days;\n\nconst defaultI18n: I18nSettings = {\n dayNamesShort,\n dayNames,\n monthNamesShort,\n monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn(dayOfMonth: number) {\n return (\n dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][\n dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10\n ]\n );\n }\n};\nlet globalI18n = assign({}, defaultI18n);\nconst setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>\n (globalI18n = assign(globalI18n, i18n));\n\nconst regexEscape = (str: string): string =>\n str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n\nconst pad = (val: string | number, len = 2): string => {\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\n\nconst formatFlags: Record<\n string,\n (dateObj: Date, i18n: I18nSettings) => string\n> = {\n D: (dateObj: Date): string => String(dateObj.getDate()),\n DD: (dateObj: Date): string => pad(dateObj.getDate()),\n Do: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.DoFn(dateObj.getDate()),\n d: (dateObj: Date): string => String(dateObj.getDay()),\n dd: (dateObj: Date): string => pad(dateObj.getDay()),\n ddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNamesShort[dateObj.getDay()],\n dddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNames[dateObj.getDay()],\n M: (dateObj: Date): string => String(dateObj.getMonth() + 1),\n MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),\n MMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNamesShort[dateObj.getMonth()],\n MMMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNames[dateObj.getMonth()],\n YY: (dateObj: Date): string =>\n pad(String(dateObj.getFullYear()), 4).substr(2),\n YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),\n h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),\n hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),\n H: (dateObj: Date): string => String(dateObj.getHours()),\n HH: (dateObj: Date): string => pad(dateObj.getHours()),\n m: (dateObj: Date): string => String(dateObj.getMinutes()),\n mm: (dateObj: Date): string => pad(dateObj.getMinutes()),\n s: (dateObj: Date): string => String(dateObj.getSeconds()),\n ss: (dateObj: Date): string => pad(dateObj.getSeconds()),\n S: (dateObj: Date): string =>\n String(Math.round(dateObj.getMilliseconds() / 100)),\n SS: (dateObj: Date): string =>\n pad(Math.round(dateObj.getMilliseconds() / 10), 2),\n SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),\n a: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],\n A: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase(),\n ZZ(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)\n );\n },\n Z(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2)\n );\n }\n};\n\ntype ParseInfo = [\n keyof DateInfo,\n string,\n ((v: string, i18n: I18nSettings) => number | null)?,\n string?\n];\nconst monthParse = (v: string): number => +v - 1;\nconst emptyDigits: ParseInfo = [null, twoDigitsOptional];\nconst emptyWord: ParseInfo = [null, word];\nconst amPm: ParseInfo = [\n \"isPm\",\n word,\n (v: string, i18n: I18nSettings): number | null => {\n const val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n } else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nconst timezoneOffset: ParseInfo = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n (v: string): number | null => {\n const parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n\n if (parts) {\n const minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n\n return 0;\n }\n];\nconst parseFlags: Record = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n (v: string): number => {\n const now = new Date();\n const cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", (v: string): number => +v * 100],\n SS: [\"millisecond\", twoDigits, (v: string): number => +v * 10],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n\n// Some common format strings\nconst globalMasks: { [key: string]: string } = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nconst setGlobalDateMasks = (masks: {\n [key: string]: string;\n}): { [key: string]: string } => assign(globalMasks, masks);\n\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nconst format = (\n dateObj: Date,\n mask: string = globalMasks[\"default\"],\n i18n: I18nSettingsOptional = {}\n): string => {\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n\n if (\n Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())\n ) {\n throw new Error(\"Invalid Date pass to format\");\n }\n\n mask = globalMasks[mask] || mask;\n\n const literals: string[] = [];\n\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n // Apply formatting rules\n mask = mask.replace(token, $0 =>\n formatFlags[$0](dateObj, combinedI18nSettings)\n );\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, () => literals.shift());\n};\n\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(\n dateStr: string,\n format: string,\n i18n: I18nSettingsOptional = {}\n): Date | null {\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n\n // Default to the beginning of the year.\n const today = new Date();\n const dateInfo: DateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n const parseInfo: ParseInfo[] = [];\n const literals: string[] = [];\n\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n let newFormat = format.replace(literal, ($0, $1) => {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n const specifiedFields: { [field: string]: boolean } = {};\n const requiredFields: { [field: string]: boolean } = {};\n\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, $0 => {\n const info = parseFlags[$0];\n const [field, regex, , requiredField] = info;\n\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(`Invalid format. ${field} specified twice in format`);\n }\n\n specifiedFields[field] = true;\n\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(field => {\n if (!specifiedFields[field]) {\n throw new Error(\n `Invalid format. ${field} is required in specified format`\n );\n }\n });\n\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, () => literals.shift());\n\n // Check if the date string matches the format. If it doesn't return null\n const matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n\n // For each match, call the parser function for that date part\n for (let i = 1; i < matches.length; i++) {\n const [field, , parser] = parseInfo[i - 1];\n const value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n\n dateInfo[field] = value;\n }\n\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n\n const dateWithoutTZ: Date = new Date(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute,\n dateInfo.second,\n dateInfo.millisecond\n );\n\n const validateFields: [\n \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\",\n \"getMonth\" | \"getDate\" | \"getHours\" | \"getMinutes\" | \"getSeconds\"\n ][] = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (let i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (\n specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()\n ) {\n return null;\n }\n }\n\n if (dateInfo.timezoneOffset == null) {\n return dateWithoutTZ;\n }\n\n return new Date(\n Date.UTC(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute - dateInfo.timezoneOffset,\n dateInfo.second,\n dateInfo.millisecond\n )\n );\n}\nexport default {\n format,\n parse,\n defaultI18n,\n setGlobalDateI18n,\n setGlobalDateMasks\n};\nexport { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n"],"names":["token","word","literal","shorten","arr","sLen","newArr","i","len","length","push","substr","monthUpdate","arrName","v","i18n","index","map","toLowerCase","indexOf","assign","origObj","_i","args","args_1","_a","obj","key","dayNames","monthNames","monthNamesShort","defaultI18n","dayNamesShort","amPm","DoFn","dayOfMonth","globalI18n","setGlobalDateI18n","regexEscape","str","replace","pad","val","String","formatFlags","D","dateObj","getDate","DD","Do","d","getDay","dd","ddd","dddd","M","getMonth","MM","MMM","MMMM","YY","getFullYear","YYYY","h","getHours","hh","H","HH","m","getMinutes","mm","s","getSeconds","ss","S","Math","round","getMilliseconds","SS","SSS","a","A","toUpperCase","ZZ","offset","getTimezoneOffset","floor","abs","Z","monthParse","emptyDigits","emptyWord","timezoneOffset","parts","match","minutes","parseInt","parseFlags","cent","Date","undefined","globalMasks","default","shortDate","mediumDate","longDate","fullDate","isoDate","isoDateTime","shortTime","mediumTime","longTime","setGlobalDateMasks","masks","format","mask","Object","prototype","toString","call","isNaN","getTime","Error","literals","$0","$1","combinedI18nSettings","shift","parse","dateStr","dateInfo","year","month","day","hour","minute","second","millisecond","isPm","parseInfo","newFormat","specifiedFields","requiredFields","info","field","regex","requiredField","keys","forEach","matches","RegExp","parser","value","dateWithoutTZ","validateFields","UTC"],"mappings":"wLAAA,IAAMA,EAAQ,6EAKRC,EAAO,UACPC,EAAU,gBAyChB,SAASC,EAA4BC,EAAQC,GAE3C,IADA,IAAMC,KACGC,EAAI,EAAGC,EAAMJ,EAAIK,OAAQF,EAAIC,EAAKD,IACzCD,EAAOI,KAAKN,EAAIG,GAAGI,OAAO,EAAGN,IAE/B,OAAOC,EAGT,IAAMM,EAAc,SAClBC,GACG,OAAA,SAACC,EAAWC,GACf,IACMC,EADeD,EAAKF,GAASI,IAAI,SAAAH,GAAK,OAAAA,EAAEI,gBACnBC,QAAQL,EAAEI,eACrC,OAAIF,GAAS,EACJA,EAEF,gBAOOI,EAAOC,OAAc,aAAAC,mBAAAA,IAAAC,oBACnC,IAAkB,QAAAC,IAAAC,WAAAA,IAAM,CAAnB,IAAMC,OACT,IAAK,IAAMC,KAAOD,EAEhBL,EAAQM,GAAOD,EAAIC,GAGvB,OAAON,EAGT,IAAMO,GACJ,SACA,SACA,UACA,YACA,WACA,SACA,YAEIC,GACJ,UACA,WACA,QACA,QACA,MACA,OACA,OACA,SACA,YACA,UACA,WACA,YAGIC,EAA0B3B,EAAQ0B,EAAY,GAG9CE,GACJC,cAH0B7B,EAAQyB,EAAU,GAI5CA,WACAE,kBACAD,aACAI,MAAO,KAAM,MACbC,KAAA,SAAKC,GACH,OACEA,GACC,KAAM,KAAM,KAAM,MACjBA,EAAa,GAAK,EACd,GACEA,EAAcA,EAAa,IAAQ,GAAK,EAAI,GAAKA,EAAc,MAKzEC,EAAahB,KAAWW,GACtBM,EAAoB,SAACtB,GACzB,OAACqB,EAAahB,EAAOgB,EAAYrB,IAE7BuB,EAAc,SAACC,GACnB,OAAAA,EAAIC,QAAQ,oBAAqB,SAE7BC,EAAM,SAACC,EAAsBlC,GAEjC,iBAFiCA,KACjCkC,EAAMC,OAAOD,GACNA,EAAIjC,OAASD,GAClBkC,EAAM,IAAMA,EAEd,OAAOA,GAGHE,GAIJC,EAAG,SAACC,GAA0B,OAAAH,OAAOG,EAAQC,YAC7CC,GAAI,SAACF,GAA0B,OAAAL,EAAIK,EAAQC,YAC3CE,GAAI,SAACH,EAAe/B,GAClB,OAAAA,EAAKmB,KAAKY,EAAQC,YACpBG,EAAG,SAACJ,GAA0B,OAAAH,OAAOG,EAAQK,WAC7CC,GAAI,SAACN,GAA0B,OAAAL,EAAIK,EAAQK,WAC3CE,IAAK,SAACP,EAAe/B,GACnB,OAAAA,EAAKiB,cAAcc,EAAQK,WAC7BG,KAAM,SAACR,EAAe/B,GACpB,OAAAA,EAAKa,SAASkB,EAAQK,WACxBI,EAAG,SAACT,GAA0B,OAAAH,OAAOG,EAAQU,WAAa,IAC1DC,GAAI,SAACX,GAA0B,OAAAL,EAAIK,EAAQU,WAAa,IACxDE,IAAK,SAACZ,EAAe/B,GACnB,OAAAA,EAAKe,gBAAgBgB,EAAQU,aAC/BG,KAAM,SAACb,EAAe/B,GACpB,OAAAA,EAAKc,WAAWiB,EAAQU,aAC1BI,GAAI,SAACd,GACH,OAAAL,EAAIE,OAAOG,EAAQe,eAAgB,GAAGlD,OAAO,IAC/CmD,KAAM,SAAChB,GAA0B,OAAAL,EAAIK,EAAQe,cAAe,IAC5DE,EAAG,SAACjB,GAA0B,OAAAH,OAAOG,EAAQkB,WAAa,IAAM,KAChEC,GAAI,SAACnB,GAA0B,OAAAL,EAAIK,EAAQkB,WAAa,IAAM,KAC9DE,EAAG,SAACpB,GAA0B,OAAAH,OAAOG,EAAQkB,aAC7CG,GAAI,SAACrB,GAA0B,OAAAL,EAAIK,EAAQkB,aAC3CI,EAAG,SAACtB,GAA0B,OAAAH,OAAOG,EAAQuB,eAC7CC,GAAI,SAACxB,GAA0B,OAAAL,EAAIK,EAAQuB,eAC3CE,EAAG,SAACzB,GAA0B,OAAAH,OAAOG,EAAQ0B,eAC7CC,GAAI,SAAC3B,GAA0B,OAAAL,EAAIK,EAAQ0B,eAC3CE,EAAG,SAAC5B,GACF,OAAAH,OAAOgC,KAAKC,MAAM9B,EAAQ+B,kBAAoB,OAChDC,GAAI,SAAChC,GACH,OAAAL,EAAIkC,KAAKC,MAAM9B,EAAQ+B,kBAAoB,IAAK,IAClDE,IAAK,SAACjC,GAA0B,OAAAL,EAAIK,EAAQ+B,kBAAmB,IAC/DG,EAAG,SAAClC,EAAe/B,GACjB,OAAA+B,EAAQkB,WAAa,GAAKjD,EAAKkB,KAAK,GAAKlB,EAAKkB,KAAK,IACrDgD,EAAG,SAACnC,EAAe/B,GACjB,OAAA+B,EAAQkB,WAAa,GACjBjD,EAAKkB,KAAK,GAAGiD,cACbnE,EAAKkB,KAAK,GAAGiD,eACnBC,GAAA,SAAGrC,GACD,IAAMsC,EAAStC,EAAQuC,oBACvB,OACGD,EAAS,EAAI,IAAM,KACpB3C,EAAwC,IAApCkC,KAAKW,MAAMX,KAAKY,IAAIH,GAAU,IAAaT,KAAKY,IAAIH,GAAU,GAAK,IAG3EI,EAAA,SAAE1C,GACA,IAAMsC,EAAStC,EAAQuC,oBACvB,OACGD,EAAS,EAAI,IAAM,KACpB3C,EAAIkC,KAAKW,MAAMX,KAAKY,IAAIH,GAAU,IAAK,GACvC,IACA3C,EAAIkC,KAAKY,IAAIH,GAAU,GAAI,KAW3BK,EAAa,SAAC3E,GAAsB,OAACA,EAAI,GACzC4E,GAA0B,KA7MN,aA8MpBC,GAAwB,KAAM1F,GAC9BgC,GACJ,OACAhC,EACA,SAACa,EAAWC,GACV,IAAM2B,EAAM5B,EAAEI,cACd,OAAIwB,IAAQ3B,EAAKkB,KAAK,GACb,EACES,IAAQ3B,EAAKkB,KAAK,GACpB,EAEF,OAGL2D,GACJ,iBACA,4CACA,SAAC9E,GACC,IAAM+E,GAAS/E,EAAI,IAAIgF,MAAM,iBAE7B,GAAID,EAAO,CACT,IAAME,EAAsB,IAAXF,EAAM,GAAUG,SAASH,EAAM,GAAI,IACpD,MAAoB,MAAbA,EAAM,GAAaE,GAAWA,EAGvC,OAAO,IAGLE,GACJpD,GAAI,MA3OoB,aA4OxBG,IAAK,MA3OW,UA4OhBC,IAAK,MA7OmB,YA6OQhD,EAAM,SAACa,GAAsB,OAAAkF,SAASlF,EAAG,MACzEyC,GAAI,QA9OoB,YA8OQkC,GAChChC,IAAK,QA9OW,SA8OSgC,GACzB7B,IACE,OAhPc,SAkPd,SAAC9C,GACC,IACMoF,IAAS,IADH,IAAIC,MACQtC,eAAelD,OAAO,EAAG,GACjD,QAAS,KAAOG,EAAI,GAAKoF,EAAO,EAAIA,GAAQpF,KAGhDiD,GAAI,OAzPoB,iBAyPOqC,EAAW,QAC1CnC,IAAK,OAzPW,cAyPQmC,EAAW,QACnClC,GAAI,OA3PoB,aA4PxBC,IAAK,OA3PW,UA4PhBC,GAAI,SA7PoB,aA8PxBE,IAAK,SA7PW,UA8PhBC,GAAI,SA/PoB,aAgQxBE,IAAK,SA/PW,UAgQhBX,MAAO,OA9PU,UA+PjBY,GAAI,cAAe,MAAO,SAAC5D,GAAsB,OAAK,KAAJA,IAClDgE,IAAK,cAlQW,SAkQe,SAAChE,GAAsB,OAAK,IAAJA,IACvDiE,KAAM,cAlQY,UAmQlB7B,EAAGwC,EACHtC,GAAIsC,EACJrC,IAAKsC,EACLrC,KAAMqC,EACNjC,KAAM,QAASzD,EAAMW,EAAY,oBACjC+C,MAAO,QAAS1D,EAAMW,EAAY,eAClCoE,EAAG/C,EACHgD,EAAGhD,EACHkD,GAAIS,EACJJ,EAAGI,GAICS,GACJC,QAAS,2BACTC,UAAW,SACXC,WAAY,cACZC,SAAU,eACVC,SAAU,qBACVC,QAAS,aACTC,YAAa,uBACbC,UAAW,QACXC,WAAY,WACZC,SAAU,gBAENC,EAAqB,SAACC,GAEK,OAAA7F,EAAOiF,EAAaY,IAS/CC,EAAS,SACbpE,EACAqE,EACApG,GAMA,gBAPAoG,EAAed,EAAqB,sBACpCtF,MAEuB,iBAAZ+B,IACTA,EAAU,IAAIqD,KAAKrD,IAIyB,kBAA5CsE,OAAOC,UAAUC,SAASC,KAAKzE,IAC/B0E,MAAM1E,EAAQ2E,WAEd,MAAM,IAAIC,MAAM,+BAKlB,IAAMC,KAGNR,GALAA,EAAOd,EAAYc,IAASA,GAKhB3E,QAAQtC,EAAS,SAAS0H,EAAIC,GAExC,OADAF,EAASjH,KAAKmH,GACP,QAGT,IAAMC,EAAqC1G,EACzCA,KAAWgB,GACXrB,GAOF,OAJAoG,EAAOA,EAAK3E,QAAQxC,EAAO,SAAA4H,GACzB,OAAAhF,EAAYgF,GAAI9E,EAASgF,MAGftF,QAAQ,OAAQ,WAAM,OAAAmF,EAASI,WAW7C,SAASC,EACPC,EACAf,EACAnG,GAEA,gBAFAA,MAEsB,iBAAXmG,EACT,MAAM,IAAIQ,MAAM,iCAQlB,GAJAR,EAASb,EAAYa,IAAWA,EAI5Be,EAAQxH,OAAS,IACnB,OAAO,KAIT,IACMyH,GACJC,MAFY,IAAIhC,MAEJtC,cACZuE,MAAO,EACPC,IAAK,EACLC,KAAM,EACNC,OAAQ,EACRC,OAAQ,EACRC,YAAa,EACbC,KAAM,KACN9C,eAAgB,MAEZ+C,KACAhB,KAGFiB,EAAY1B,EAAO1E,QAAQtC,EAAS,SAAC0H,EAAIC,GAE3C,OADAF,EAASjH,KAAK4B,EAAYuF,IACnB,QAEHgB,KACAC,KAGNF,EAAYtG,EAAYsG,GAAWpG,QAAQxC,EAAO,SAAA4H,GAChD,IAAMmB,EAAO9C,EAAW2B,GACjBoB,EAAiCD,KAA1BE,EAA0BF,KAAjBG,EAAiBH,KAGxC,GAAIF,EAAgBG,GAClB,MAAM,IAAItB,MAAM,mBAAmBsB,gCAWrC,OARAH,EAAgBG,IAAS,EAGrBE,IACFJ,EAAeI,IAAiB,GAGlCP,EAAUjI,KAAKqI,GACR,IAAME,EAAQ,MAIvB7B,OAAO+B,KAAKL,GAAgBM,QAAQ,SAAAJ,GAClC,IAAKH,EAAgBG,GACnB,MAAM,IAAItB,MACR,mBAAmBsB,wCAMzBJ,EAAYA,EAAUpG,QAAQ,OAAQ,WAAM,OAAAmF,EAASI,UAGrD,IAAMsB,EAAUpB,EAAQnC,MAAM,IAAIwD,OAAOV,EAAW,MACpD,IAAKS,EACH,OAAO,KAST,IANA,IAAMvB,EAAqC1G,EACzCA,KAAWgB,GACXrB,GAIOR,EAAI,EAAGA,EAAI8I,EAAQ5I,OAAQF,IAAK,CACjC,IAAAkB,EAAoBkH,EAAUpI,EAAI,GAAjCyI,OAASO,OACVC,EAAQD,EACVA,EAAOF,EAAQ9I,GAAIuH,IAClBuB,EAAQ9I,GAGb,GAAa,MAATiJ,EACF,OAAO,KAGTtB,EAASc,GAASQ,EAGE,IAAlBtB,EAASQ,MAA+B,MAAjBR,EAASI,MAAmC,KAAlBJ,EAASI,KAC5DJ,EAASI,MAAQJ,EAASI,KAAO,GACN,IAAlBJ,EAASQ,MAAiC,KAAlBR,EAASI,OAC1CJ,EAASI,KAAO,GAuBlB,IApBA,IAAMmB,EAAsB,IAAItD,KAC9B+B,EAASC,KACTD,EAASE,MACTF,EAASG,IACTH,EAASI,KACTJ,EAASK,OACTL,EAASM,OACTN,EAASO,aAGLiB,IAIH,QAAS,aACT,MAAO,YACP,OAAQ,aACR,SAAU,eACV,SAAU,eAEGlJ,GAAPD,EAAI,EAASmJ,EAAejJ,QAAQF,EAAIC,EAAKD,IAGpD,GACEsI,EAAgBa,EAAenJ,GAAG,KAClC2H,EAASwB,EAAenJ,GAAG,MAAQkJ,EAAcC,EAAenJ,GAAG,MAEnE,OAAO,KAIX,OAA+B,MAA3B2H,EAAStC,eACJ6D,EAGF,IAAItD,KACTA,KAAKwD,IACHzB,EAASC,KACTD,EAASE,MACTF,EAASG,IACTH,EAASI,KACTJ,EAASK,OAASL,EAAStC,eAC3BsC,EAASM,OACTN,EAASO,qBAKbvB,SACAc,QACAjG,cACAM,oBACA2E"} \ No newline at end of file diff --git a/build/node_modules/fecha/lib/fecha.d.ts b/build/node_modules/fecha/lib/fecha.d.ts new file mode 100644 index 00000000..47404a05 --- /dev/null +++ b/build/node_modules/fecha/lib/fecha.d.ts @@ -0,0 +1,52 @@ +export declare type I18nSettings = { + amPm: [string, string]; + dayNames: Days; + dayNamesShort: Days; + monthNames: Months; + monthNamesShort: Months; + DoFn(dayOfMonth: number): string; +}; +export declare type I18nSettingsOptional = Partial; +export declare type Days = [string, string, string, string, string, string, string]; +export declare type Months = [string, string, string, string, string, string, string, string, string, string, string, string]; +export declare function assign(a: A): A; +export declare function assign(a: A, b: B): A & B; +export declare function assign(a: A, b: B, c: C): A & B & C; +export declare function assign(a: A, b: B, c: C, d: D): A & B & C & D; +declare const defaultI18n: I18nSettings; +declare const setGlobalDateI18n: (i18n: I18nSettingsOptional) => I18nSettings; +declare const setGlobalDateMasks: (masks: { + [key: string]: string; +}) => { + [key: string]: string; +}; +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +declare const format: (dateObj: Date, mask?: string, i18n?: I18nSettingsOptional) => string; +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +declare function parse(dateStr: string, format: string, i18n?: I18nSettingsOptional): Date | null; +declare const _default: { + format: (dateObj: Date, mask?: string, i18n?: Partial) => string; + parse: typeof parse; + defaultI18n: I18nSettings; + setGlobalDateI18n: (i18n: Partial) => I18nSettings; + setGlobalDateMasks: (masks: { + [key: string]: string; + }) => { + [key: string]: string; + }; +}; +export default _default; +export { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; diff --git a/build/node_modules/fecha/lib/fecha.js b/build/node_modules/fecha/lib/fecha.js new file mode 100644 index 00000000..eeb806e4 --- /dev/null +++ b/build/node_modules/fecha/lib/fecha.js @@ -0,0 +1,386 @@ +var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; +var twoDigitsOptional = "[1-9]\\d?"; +var twoDigits = "\\d\\d"; +var threeDigits = "\\d{3}"; +var fourDigits = "\\d{4}"; +var word = "[^\\s]+"; +var literal = /\[([^]*?)\]/gm; +function shorten(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; +} +var monthUpdate = function (arrName) { return function (v, i18n) { + var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); }); + var index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; +}; }; +function assign(origObj) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var obj = args_1[_a]; + for (var key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; +} +var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" +]; +var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; +var monthNamesShort = shorten(monthNames, 3); +var dayNamesShort = shorten(dayNames, 3); +var defaultI18n = { + dayNamesShort: dayNamesShort, + dayNames: dayNames, + monthNamesShort: monthNamesShort, + monthNames: monthNames, + amPm: ["am", "pm"], + DoFn: function (dayOfMonth) { + return (dayOfMonth + + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]); + } +}; +var globalI18n = assign({}, defaultI18n); +var setGlobalDateI18n = function (i18n) { + return (globalI18n = assign(globalI18n, i18n)); +}; +var regexEscape = function (str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); +}; +var pad = function (val, len) { + if (len === void 0) { len = 2; } + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; +}; +var formatFlags = { + D: function (dateObj) { return String(dateObj.getDate()); }, + DD: function (dateObj) { return pad(dateObj.getDate()); }, + Do: function (dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function (dateObj) { return String(dateObj.getDay()); }, + dd: function (dateObj) { return pad(dateObj.getDay()); }, + ddd: function (dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function (dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function (dateObj) { return String(dateObj.getMonth() + 1); }, + MM: function (dateObj) { return pad(dateObj.getMonth() + 1); }, + MMM: function (dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function (dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function (dateObj) { + return pad(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); }, + h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); }, + hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); }, + H: function (dateObj) { return String(dateObj.getHours()); }, + HH: function (dateObj) { return pad(dateObj.getHours()); }, + m: function (dateObj) { return String(dateObj.getMinutes()); }, + mm: function (dateObj) { return pad(dateObj.getMinutes()); }, + s: function (dateObj) { return String(dateObj.getSeconds()); }, + ss: function (dateObj) { return pad(dateObj.getSeconds()); }, + S: function (dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function (dateObj) { + return pad(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); }, + a: function (dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function (dateObj, i18n) { + return dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(); + }, + ZZ: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)); + }, + Z: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2)); + } +}; +var monthParse = function (v) { return +v - 1; }; +var emptyDigits = [null, twoDigitsOptional]; +var emptyWord = [null, word]; +var amPm = [ + "isPm", + word, + function (v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } + else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } +]; +var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function (v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } +]; +var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function (v) { + var now = new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function (v) { return +v * 100; }], + SS: ["millisecond", twoDigits, function (v) { return +v * 10; }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset +}; +// Some common format strings +var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; +var setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); }; +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +var format = function (dateObj, mask, i18n) { + if (mask === void 0) { mask = globalMasks["default"]; } + if (i18n === void 0) { i18n = {}; } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function ($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // Apply formatting rules + mask = mask.replace(token, function ($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, function () { return literals.shift(); }); +}; +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +function parse(dateStr, format, i18n) { + if (i18n === void 0) { i18n = {}; } + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + // Default to the beginning of the year. + var today = new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + var newFormat = format.replace(literal, function ($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, function ($0) { + var info = parseFlags[$0]; + var field = info[0], regex = info[1], requiredField = info[3]; + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error("Invalid format. " + field + " specified twice in format"); + } + specifiedFields[field] = true; + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + parseInfo.push(info); + return "(" + regex + ")"; + }); + // Check all the required fields are present + Object.keys(requiredFields).forEach(function (field) { + if (!specifiedFields[field]) { + throw new Error("Invalid format. " + field + " is required in specified format"); + } + }); + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); }); + // Check if the date string matches the format. If it doesn't return null + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // For each match, call the parser function for that date part + for (var i = 1; i < matches.length; i++) { + var _a = parseInfo[i - 1], field = _a[0], parser = _a[2]; + var value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + dateInfo[field] = value; + } + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } + else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + var dateWithoutTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if (specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()) { + return null; + } + } + if (dateInfo.timezoneOffset == null) { + return dateWithoutTZ; + } + return new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); +} +var fecha = { + format: format, + parse: parse, + defaultI18n: defaultI18n, + setGlobalDateI18n: setGlobalDateI18n, + setGlobalDateMasks: setGlobalDateMasks +}; + +export default fecha; +export { assign, format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; +//# sourceMappingURL=fecha.js.map diff --git a/build/node_modules/fecha/lib/fecha.js.map b/build/node_modules/fecha/lib/fecha.js.map new file mode 100644 index 00000000..0461f5d2 --- /dev/null +++ b/build/node_modules/fecha/lib/fecha.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fecha.js","sources":["../src/fecha.ts"],"sourcesContent":["const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\\1?|[aA]|\"[^\"]*\"|'[^']*'/g;\nconst twoDigitsOptional = \"[1-9]\\\\d?\";\nconst twoDigits = \"\\\\d\\\\d\";\nconst threeDigits = \"\\\\d{3}\";\nconst fourDigits = \"\\\\d{4}\";\nconst word = \"[^\\\\s]+\";\nconst literal = /\\[([^]*?)\\]/gm;\n\ntype DateInfo = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n millisecond: number;\n isPm: number | null;\n timezoneOffset: number | null;\n};\n\nexport type I18nSettings = {\n amPm: [string, string];\n dayNames: Days;\n dayNamesShort: Days;\n monthNames: Months;\n monthNamesShort: Months;\n DoFn(dayOfMonth: number): string;\n};\n\nexport type I18nSettingsOptional = Partial;\n\nexport type Days = [string, string, string, string, string, string, string];\nexport type Months = [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string\n];\n\nfunction shorten(arr: T, sLen: number): string[] {\n const newArr: string[] = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\n\nconst monthUpdate = (\n arrName: \"monthNames\" | \"monthNamesShort\" | \"dayNames\" | \"dayNamesShort\"\n) => (v: string, i18n: I18nSettings): number | null => {\n const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());\n const index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n};\n\nexport function assign(a: A): A;\nexport function assign(a: A, b: B): A & B;\nexport function assign(a: A, b: B, c: C): A & B & C;\nexport function assign(a: A, b: B, c: C, d: D): A & B & C & D;\nexport function assign(origObj: any, ...args: any[]): any {\n for (const obj of args) {\n for (const key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\n\nconst dayNames: Days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nconst monthNames: Months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\n\nconst monthNamesShort: Months = shorten(monthNames, 3) as Months;\nconst dayNamesShort: Days = shorten(dayNames, 3) as Days;\n\nconst defaultI18n: I18nSettings = {\n dayNamesShort,\n dayNames,\n monthNamesShort,\n monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn(dayOfMonth: number) {\n return (\n dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][\n dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10\n ]\n );\n }\n};\nlet globalI18n = assign({}, defaultI18n);\nconst setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>\n (globalI18n = assign(globalI18n, i18n));\n\nconst regexEscape = (str: string): string =>\n str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n\nconst pad = (val: string | number, len = 2): string => {\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\n\nconst formatFlags: Record<\n string,\n (dateObj: Date, i18n: I18nSettings) => string\n> = {\n D: (dateObj: Date): string => String(dateObj.getDate()),\n DD: (dateObj: Date): string => pad(dateObj.getDate()),\n Do: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.DoFn(dateObj.getDate()),\n d: (dateObj: Date): string => String(dateObj.getDay()),\n dd: (dateObj: Date): string => pad(dateObj.getDay()),\n ddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNamesShort[dateObj.getDay()],\n dddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNames[dateObj.getDay()],\n M: (dateObj: Date): string => String(dateObj.getMonth() + 1),\n MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),\n MMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNamesShort[dateObj.getMonth()],\n MMMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNames[dateObj.getMonth()],\n YY: (dateObj: Date): string =>\n pad(String(dateObj.getFullYear()), 4).substr(2),\n YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),\n h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),\n hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),\n H: (dateObj: Date): string => String(dateObj.getHours()),\n HH: (dateObj: Date): string => pad(dateObj.getHours()),\n m: (dateObj: Date): string => String(dateObj.getMinutes()),\n mm: (dateObj: Date): string => pad(dateObj.getMinutes()),\n s: (dateObj: Date): string => String(dateObj.getSeconds()),\n ss: (dateObj: Date): string => pad(dateObj.getSeconds()),\n S: (dateObj: Date): string =>\n String(Math.round(dateObj.getMilliseconds() / 100)),\n SS: (dateObj: Date): string =>\n pad(Math.round(dateObj.getMilliseconds() / 10), 2),\n SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),\n a: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],\n A: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase(),\n ZZ(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)\n );\n },\n Z(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2)\n );\n }\n};\n\ntype ParseInfo = [\n keyof DateInfo,\n string,\n ((v: string, i18n: I18nSettings) => number | null)?,\n string?\n];\nconst monthParse = (v: string): number => +v - 1;\nconst emptyDigits: ParseInfo = [null, twoDigitsOptional];\nconst emptyWord: ParseInfo = [null, word];\nconst amPm: ParseInfo = [\n \"isPm\",\n word,\n (v: string, i18n: I18nSettings): number | null => {\n const val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n } else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nconst timezoneOffset: ParseInfo = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n (v: string): number | null => {\n const parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n\n if (parts) {\n const minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n\n return 0;\n }\n];\nconst parseFlags: Record = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n (v: string): number => {\n const now = new Date();\n const cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", (v: string): number => +v * 100],\n SS: [\"millisecond\", twoDigits, (v: string): number => +v * 10],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n\n// Some common format strings\nconst globalMasks: { [key: string]: string } = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nconst setGlobalDateMasks = (masks: {\n [key: string]: string;\n}): { [key: string]: string } => assign(globalMasks, masks);\n\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nconst format = (\n dateObj: Date,\n mask: string = globalMasks[\"default\"],\n i18n: I18nSettingsOptional = {}\n): string => {\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n\n if (\n Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())\n ) {\n throw new Error(\"Invalid Date pass to format\");\n }\n\n mask = globalMasks[mask] || mask;\n\n const literals: string[] = [];\n\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n // Apply formatting rules\n mask = mask.replace(token, $0 =>\n formatFlags[$0](dateObj, combinedI18nSettings)\n );\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, () => literals.shift());\n};\n\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(\n dateStr: string,\n format: string,\n i18n: I18nSettingsOptional = {}\n): Date | null {\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n\n // Default to the beginning of the year.\n const today = new Date();\n const dateInfo: DateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n const parseInfo: ParseInfo[] = [];\n const literals: string[] = [];\n\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n let newFormat = format.replace(literal, ($0, $1) => {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n const specifiedFields: { [field: string]: boolean } = {};\n const requiredFields: { [field: string]: boolean } = {};\n\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, $0 => {\n const info = parseFlags[$0];\n const [field, regex, , requiredField] = info;\n\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(`Invalid format. ${field} specified twice in format`);\n }\n\n specifiedFields[field] = true;\n\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(field => {\n if (!specifiedFields[field]) {\n throw new Error(\n `Invalid format. ${field} is required in specified format`\n );\n }\n });\n\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, () => literals.shift());\n\n // Check if the date string matches the format. If it doesn't return null\n const matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n\n // For each match, call the parser function for that date part\n for (let i = 1; i < matches.length; i++) {\n const [field, , parser] = parseInfo[i - 1];\n const value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n\n dateInfo[field] = value;\n }\n\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n\n const dateWithoutTZ: Date = new Date(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute,\n dateInfo.second,\n dateInfo.millisecond\n );\n\n const validateFields: [\n \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\",\n \"getMonth\" | \"getDate\" | \"getHours\" | \"getMinutes\" | \"getSeconds\"\n ][] = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (let i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (\n specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()\n ) {\n return null;\n }\n }\n\n if (dateInfo.timezoneOffset == null) {\n return dateWithoutTZ;\n }\n\n return new Date(\n Date.UTC(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute - dateInfo.timezoneOffset,\n dateInfo.second,\n dateInfo.millisecond\n )\n );\n}\nexport default {\n format,\n parse,\n defaultI18n,\n setGlobalDateI18n,\n setGlobalDateMasks\n};\nexport { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n"],"names":[],"mappings":"AAAA,IAAM,KAAK,GAAG,4EAA4E,CAAC;AAC3F,IAAM,iBAAiB,GAAG,WAAW,CAAC;AACtC,IAAM,SAAS,GAAG,QAAQ,CAAC;AAC3B,IAAM,WAAW,GAAG,QAAQ,CAAC;AAC7B,IAAM,UAAU,GAAG,QAAQ,CAAC;AAC5B,IAAM,IAAI,GAAG,SAAS,CAAC;AACvB,IAAM,OAAO,GAAG,eAAe,CAAC;AAyChC,SAAS,OAAO,CAAqB,GAAM,EAAE,IAAY;IACvD,IAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC9C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;KACrC;IACD,OAAO,MAAM,CAAC;CACf;AAED,IAAM,WAAW,GAAG,UAClB,OAAwE,IACrE,OAAA,UAAC,CAAS,EAAE,IAAkB;IACjC,IAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE,GAAA,CAAC,CAAC;IAC7D,IAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;IACpD,IAAI,KAAK,GAAG,CAAC,CAAC,EAAE;QACd,OAAO,KAAK,CAAC;KACd;IACD,OAAO,IAAI,CAAC;CACb,GAAA,CAAC;AAMF,SAAgB,MAAM,CAAC,OAAY;IAAE,cAAc;SAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;QAAd,6BAAc;;IACjD,KAAkB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE;QAAnB,IAAM,GAAG,aAAA;QACZ,KAAK,IAAM,GAAG,IAAI,GAAG,EAAE;;YAErB,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;SACzB;KACF;IACD,OAAO,OAAO,CAAC;CAChB;AAED,IAAM,QAAQ,GAAS;IACrB,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,WAAW;IACX,UAAU;IACV,QAAQ;IACR,UAAU;CACX,CAAC;AACF,IAAM,UAAU,GAAW;IACzB,SAAS;IACT,UAAU;IACV,OAAO;IACP,OAAO;IACP,KAAK;IACL,MAAM;IACN,MAAM;IACN,QAAQ;IACR,WAAW;IACX,SAAS;IACT,UAAU;IACV,UAAU;CACX,CAAC;AAEF,IAAM,eAAe,GAAW,OAAO,CAAC,UAAU,EAAE,CAAC,CAAW,CAAC;AACjE,IAAM,aAAa,GAAS,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAS,CAAC;AAEzD,IAAM,WAAW,GAAiB;IAChC,aAAa,eAAA;IACb,QAAQ,UAAA;IACR,eAAe,iBAAA;IACf,UAAU,YAAA;IACV,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IAClB,IAAI,EAAJ,UAAK,UAAkB;QACrB,QACE,UAAU;YACV,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CACtB,UAAU,GAAG,EAAE,GAAG,CAAC;kBACf,CAAC;kBACD,CAAC,CAAC,UAAU,IAAI,UAAU,GAAG,EAAE,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,UAAU,IAAI,EAAE,CACxE,EACD;KACH;CACF,CAAC;AACF,IAAI,UAAU,GAAG,MAAM,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC;AACzC,IAAM,iBAAiB,GAAG,UAAC,IAA0B;IACnD,QAAC,UAAU,GAAG,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC;CAAC,CAAC;AAE1C,IAAM,WAAW,GAAG,UAAC,GAAW;IAC9B,OAAA,GAAG,CAAC,OAAO,CAAC,mBAAmB,EAAE,MAAM,CAAC;CAAA,CAAC;AAE3C,IAAM,GAAG,GAAG,UAAC,GAAoB,EAAE,GAAO;IAAP,oBAAA,EAAA,OAAO;IACxC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IAClB,OAAO,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;QACvB,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;KACjB;IACD,OAAO,GAAG,CAAC;CACZ,CAAC;AAEF,IAAM,WAAW,GAGb;IACF,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,GAAA;IACvD,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,GAAA;IACrD,EAAE,EAAE,UAAC,OAAa,EAAE,IAAkB;QACpC,OAAA,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;KAAA;IAC9B,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,GAAA;IACtD,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,GAAA;IACpD,GAAG,EAAE,UAAC,OAAa,EAAE,IAAkB;QACrC,OAAA,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;KAAA;IACtC,IAAI,EAAE,UAAC,OAAa,EAAE,IAAkB;QACtC,OAAA,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;KAAA;IACjC,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,GAAA;IAC5D,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,GAAA;IAC1D,GAAG,EAAE,UAAC,OAAa,EAAE,IAAkB;QACrC,OAAA,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;KAAA;IAC1C,IAAI,EAAE,UAAC,OAAa,EAAE,IAAkB;QACtC,OAAA,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;KAAA;IACrC,EAAE,EAAE,UAAC,OAAa;QAChB,OAAA,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;KAAA;IACjD,IAAI,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,GAAA;IAC9D,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,GAAA;IACnE,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,GAAA;IACjE,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAA;IACxD,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAA;IACtD,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;IAC1D,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;IACxD,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;IAC1D,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;IACxD,CAAC,EAAE,UAAC,OAAa;QACf,OAAA,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,GAAG,CAAC,CAAC;KAAA;IACrD,EAAE,EAAE,UAAC,OAAa;QAChB,OAAA,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;KAAA;IACpD,GAAG,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,GAAA;IACjE,CAAC,EAAE,UAAC,OAAa,EAAE,IAAkB;QACnC,OAAA,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;KAAA;IACvD,CAAC,EAAE,UAAC,OAAa,EAAE,IAAkB;QACnC,OAAA,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE;cACnB,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE;cAC1B,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE;KAAA;IAChC,EAAE,EAAF,UAAG,OAAa;QACd,IAAM,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;QAC3C,QACE,CAAC,MAAM,GAAG,CAAC,GAAG,GAAG,GAAG,GAAG;YACvB,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC,EACzE;KACH;IACD,CAAC,EAAD,UAAE,OAAa;QACb,IAAM,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;QAC3C,QACE,CAAC,MAAM,GAAG,CAAC,GAAG,GAAG,GAAG,GAAG;YACvB,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACzC,GAAG;YACH,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAC7B;KACH;CACF,CAAC;AAQF,IAAM,UAAU,GAAG,UAAC,CAAS,IAAa,OAAA,CAAC,CAAC,GAAG,CAAC,GAAA,CAAC;AACjD,IAAM,WAAW,GAAc,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;AACzD,IAAM,SAAS,GAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC1C,IAAM,IAAI,GAAc;IACtB,MAAM;IACN,IAAI;IACJ,UAAC,CAAS,EAAE,IAAkB;QAC5B,IAAM,GAAG,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;QAC5B,IAAI,GAAG,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;YACxB,OAAO,CAAC,CAAC;SACV;aAAM,IAAI,GAAG,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;YAC/B,OAAO,CAAC,CAAC;SACV;QACD,OAAO,IAAI,CAAC;KACb;CACF,CAAC;AACF,IAAM,cAAc,GAAc;IAChC,gBAAgB;IAChB,2CAA2C;IAC3C,UAAC,CAAS;QACR,IAAM,KAAK,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,KAAK,CAAC,eAAe,CAAC,CAAC;QAE9C,IAAI,KAAK,EAAE;YACT,IAAM,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACxD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,GAAG,OAAO,GAAG,CAAC,OAAO,CAAC;SAC9C;QAED,OAAO,CAAC,CAAC;KACV;CACF,CAAC;AACF,IAAM,UAAU,GAA8B;IAC5C,CAAC,EAAE,CAAC,KAAK,EAAE,iBAAiB,CAAC;IAC7B,EAAE,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC;IACtB,EAAE,EAAE,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,EAAE,UAAC,CAAS,IAAa,OAAA,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,GAAA,CAAC;IAC7E,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,EAAE,UAAU,CAAC;IAC3C,EAAE,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC;IACpC,EAAE,EAAE;QACF,MAAM;QACN,SAAS;QACT,UAAC,CAAS;YACR,IAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAM,IAAI,GAAG,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,WAAW,EAAE,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YACpD,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;SAChD;KACF;IACD,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,CAAC;IACjD,EAAE,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC;IAC1C,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAC9B,EAAE,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC;IACvB,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,CAAC;IAChC,EAAE,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACzB,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,CAAC;IAChC,EAAE,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;IACzB,IAAI,EAAE,CAAC,MAAM,EAAE,UAAU,CAAC;IAC1B,CAAC,EAAE,CAAC,aAAa,EAAE,KAAK,EAAE,UAAC,CAAS,IAAa,OAAA,CAAC,CAAC,GAAG,GAAG,GAAA,CAAC;IAC1D,EAAE,EAAE,CAAC,aAAa,EAAE,SAAS,EAAE,UAAC,CAAS,IAAa,OAAA,CAAC,CAAC,GAAG,EAAE,GAAA,CAAC;IAC9D,GAAG,EAAE,CAAC,aAAa,EAAE,WAAW,CAAC;IACjC,CAAC,EAAE,WAAW;IACd,EAAE,EAAE,WAAW;IACf,GAAG,EAAE,SAAS;IACd,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,WAAW,CAAC,iBAAiB,CAAC,CAAC;IACpD,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IAChD,CAAC,EAAE,IAAI;IACP,CAAC,EAAE,IAAI;IACP,EAAE,EAAE,cAAc;IAClB,CAAC,EAAE,cAAc;CAClB,CAAC;;AAGF,IAAM,WAAW,GAA8B;IAC7C,OAAO,EAAE,0BAA0B;IACnC,SAAS,EAAE,QAAQ;IACnB,UAAU,EAAE,aAAa;IACzB,QAAQ,EAAE,cAAc;IACxB,QAAQ,EAAE,oBAAoB;IAC9B,OAAO,EAAE,YAAY;IACrB,WAAW,EAAE,sBAAsB;IACnC,SAAS,EAAE,OAAO;IAClB,UAAU,EAAE,UAAU;IACtB,QAAQ,EAAE,cAAc;CACzB,CAAC;AACF,IAAM,kBAAkB,GAAG,UAAC,KAE3B,IAAgC,OAAA,MAAM,CAAC,WAAW,EAAE,KAAK,CAAC,GAAA,CAAC;;;;;;;;AAS5D,IAAM,MAAM,GAAG,UACb,OAAa,EACb,IAAqC,EACrC,IAA+B;IAD/B,qBAAA,EAAA,OAAe,WAAW,CAAC,SAAS,CAAC;IACrC,qBAAA,EAAA,SAA+B;IAE/B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,OAAO,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC;KAC7B;IAED,IACE,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,eAAe;QAC3D,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EACxB;QACA,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;KAChD;IAED,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;IAEjC,IAAM,QAAQ,GAAa,EAAE,CAAC;;IAG9B,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,UAAS,EAAE,EAAE,EAAE;QAC1C,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAClB,OAAO,KAAK,CAAC;KACd,CAAC,CAAC;IAEH,IAAM,oBAAoB,GAAiB,MAAM,CAC/C,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,EACtB,IAAI,CACL,CAAC;;IAEF,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,UAAA,EAAE;QAC3B,OAAA,WAAW,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,oBAAoB,CAAC;KAAA,CAC/C,CAAC;;IAEF,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,cAAM,OAAA,QAAQ,CAAC,KAAK,EAAE,GAAA,CAAC,CAAC;CACrD,CAAC;;;;;;;;;AAUF,SAAS,KAAK,CACZ,OAAe,EACf,MAAc,EACd,IAA+B;IAA/B,qBAAA,EAAA,SAA+B;IAE/B,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC9B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;KAClD;;IAGD,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC;;;IAIvC,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,EAAE;QACzB,OAAO,IAAI,CAAC;KACb;;IAGD,IAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC;IACzB,IAAM,QAAQ,GAAa;QACzB,IAAI,EAAE,KAAK,CAAC,WAAW,EAAE;QACzB,KAAK,EAAE,CAAC;QACR,GAAG,EAAE,CAAC;QACN,IAAI,EAAE,CAAC;QACP,MAAM,EAAE,CAAC;QACT,MAAM,EAAE,CAAC;QACT,WAAW,EAAE,CAAC;QACd,IAAI,EAAE,IAAI;QACV,cAAc,EAAE,IAAI;KACrB,CAAC;IACF,IAAM,SAAS,GAAgB,EAAE,CAAC;IAClC,IAAM,QAAQ,GAAa,EAAE,CAAC;;IAG9B,IAAI,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,UAAC,EAAE,EAAE,EAAE;QAC7C,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/B,OAAO,KAAK,CAAC;KACd,CAAC,CAAC;IACH,IAAM,eAAe,GAAiC,EAAE,CAAC;IACzD,IAAM,cAAc,GAAiC,EAAE,CAAC;;IAGxD,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,UAAA,EAAE;QAClD,IAAM,IAAI,GAAG,UAAU,CAAC,EAAE,CAAC,CAAC;QACrB,IAAA,KAAK,GAA4B,IAAI,GAAhC,EAAE,KAAK,GAAqB,IAAI,GAAzB,EAAI,aAAa,GAAI,IAAI,GAAR,CAAS;;QAG7C,IAAI,eAAe,CAAC,KAAK,CAAC,EAAE;YAC1B,MAAM,IAAI,KAAK,CAAC,qBAAmB,KAAK,+BAA4B,CAAC,CAAC;SACvE;QAED,eAAe,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;;QAG9B,IAAI,aAAa,EAAE;YACjB,cAAc,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC;SACtC;QAED,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,OAAO,GAAG,GAAG,KAAK,GAAG,GAAG,CAAC;KAC1B,CAAC,CAAC;;IAGH,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,UAAA,KAAK;QACvC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE;YAC3B,MAAM,IAAI,KAAK,CACb,qBAAmB,KAAK,qCAAkC,CAC3D,CAAC;SACH;KACF,CAAC,CAAC;;IAGH,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,cAAM,OAAA,QAAQ,CAAC,KAAK,EAAE,GAAA,CAAC,CAAC;;IAG9D,IAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC;IAC1D,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,IAAI,CAAC;KACb;IAED,IAAM,oBAAoB,GAAiB,MAAM,CAC/C,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,EACtB,IAAI,CACL,CAAC;;IAGF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACjC,IAAA,KAAoB,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,EAAnC,KAAK,QAAA,EAAI,MAAM,QAAoB,CAAC;QAC3C,IAAM,KAAK,GAAG,MAAM;cAChB,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,oBAAoB,CAAC;cACxC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;;QAGhB,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,OAAO,IAAI,CAAC;SACb;QAED,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;KACzB;IAED,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC,IAAI,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,EAAE,EAAE;QACzE,QAAQ,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC;KACrC;SAAM,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,EAAE,EAAE;QACvD,QAAQ,CAAC,IAAI,GAAG,CAAC,CAAC;KACnB;IAED,IAAM,aAAa,GAAS,IAAI,IAAI,CAClC,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,KAAK,EACd,QAAQ,CAAC,GAAG,EACZ,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,WAAW,CACrB,CAAC;IAEF,IAAM,cAAc,GAGd;QACJ,CAAC,OAAO,EAAE,UAAU,CAAC;QACrB,CAAC,KAAK,EAAE,SAAS,CAAC;QAClB,CAAC,MAAM,EAAE,UAAU,CAAC;QACpB,CAAC,QAAQ,EAAE,YAAY,CAAC;QACxB,CAAC,QAAQ,EAAE,YAAY,CAAC;KACzB,CAAC;IACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;;;QAGzD,IACE,eAAe,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACrC,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EACxE;YACA,OAAO,IAAI,CAAC;SACb;KACF;IAED,IAAI,QAAQ,CAAC,cAAc,IAAI,IAAI,EAAE;QACnC,OAAO,aAAa,CAAC;KACtB;IAED,OAAO,IAAI,IAAI,CACb,IAAI,CAAC,GAAG,CACN,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,KAAK,EACd,QAAQ,CAAC,GAAG,EACZ,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,cAAc,EACzC,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,WAAW,CACrB,CACF,CAAC;CACH;AACD,YAAe;IACb,MAAM,QAAA;IACN,KAAK,OAAA;IACL,WAAW,aAAA;IACX,iBAAiB,mBAAA;IACjB,kBAAkB,oBAAA;CACnB,CAAC;;;;;"} \ No newline at end of file diff --git a/build/node_modules/fecha/lib/fecha.umd.js b/build/node_modules/fecha/lib/fecha.umd.js new file mode 100644 index 00000000..ca3d1cfa --- /dev/null +++ b/build/node_modules/fecha/lib/fecha.umd.js @@ -0,0 +1,401 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.fecha = {}))); +}(this, (function (exports) { 'use strict'; + + var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; + var twoDigitsOptional = "[1-9]\\d?"; + var twoDigits = "\\d\\d"; + var threeDigits = "\\d{3}"; + var fourDigits = "\\d{4}"; + var word = "[^\\s]+"; + var literal = /\[([^]*?)\]/gm; + function shorten(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; + } + var monthUpdate = function (arrName) { return function (v, i18n) { + var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); }); + var index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; + }; }; + function assign(origObj) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var obj = args_1[_a]; + for (var key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; + } + var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ]; + var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ]; + var monthNamesShort = shorten(monthNames, 3); + var dayNamesShort = shorten(dayNames, 3); + var defaultI18n = { + dayNamesShort: dayNamesShort, + dayNames: dayNames, + monthNamesShort: monthNamesShort, + monthNames: monthNames, + amPm: ["am", "pm"], + DoFn: function (dayOfMonth) { + return (dayOfMonth + + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]); + } + }; + var globalI18n = assign({}, defaultI18n); + var setGlobalDateI18n = function (i18n) { + return (globalI18n = assign(globalI18n, i18n)); + }; + var regexEscape = function (str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); + }; + var pad = function (val, len) { + if (len === void 0) { len = 2; } + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; + }; + var formatFlags = { + D: function (dateObj) { return String(dateObj.getDate()); }, + DD: function (dateObj) { return pad(dateObj.getDate()); }, + Do: function (dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function (dateObj) { return String(dateObj.getDay()); }, + dd: function (dateObj) { return pad(dateObj.getDay()); }, + ddd: function (dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function (dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function (dateObj) { return String(dateObj.getMonth() + 1); }, + MM: function (dateObj) { return pad(dateObj.getMonth() + 1); }, + MMM: function (dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function (dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function (dateObj) { + return pad(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); }, + h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); }, + hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); }, + H: function (dateObj) { return String(dateObj.getHours()); }, + HH: function (dateObj) { return pad(dateObj.getHours()); }, + m: function (dateObj) { return String(dateObj.getMinutes()); }, + mm: function (dateObj) { return pad(dateObj.getMinutes()); }, + s: function (dateObj) { return String(dateObj.getSeconds()); }, + ss: function (dateObj) { return pad(dateObj.getSeconds()); }, + S: function (dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function (dateObj) { + return pad(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); }, + a: function (dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function (dateObj, i18n) { + return dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(); + }, + ZZ: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)); + }, + Z: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2)); + } + }; + var monthParse = function (v) { return +v - 1; }; + var emptyDigits = [null, twoDigitsOptional]; + var emptyWord = [null, word]; + var amPm = [ + "isPm", + word, + function (v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } + else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } + ]; + var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function (v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } + ]; + var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function (v) { + var now = new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function (v) { return +v * 100; }], + SS: ["millisecond", twoDigits, function (v) { return +v * 10; }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset + }; + // Some common format strings + var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" + }; + var setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); }; + /*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ + var format = function (dateObj, mask, i18n) { + if (mask === void 0) { mask = globalMasks["default"]; } + if (i18n === void 0) { i18n = {}; } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function ($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // Apply formatting rules + mask = mask.replace(token, function ($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, function () { return literals.shift(); }); + }; + /** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ + function parse(dateStr, format, i18n) { + if (i18n === void 0) { i18n = {}; } + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + // Default to the beginning of the year. + var today = new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + var newFormat = format.replace(literal, function ($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, function ($0) { + var info = parseFlags[$0]; + var field = info[0], regex = info[1], requiredField = info[3]; + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error("Invalid format. " + field + " specified twice in format"); + } + specifiedFields[field] = true; + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + parseInfo.push(info); + return "(" + regex + ")"; + }); + // Check all the required fields are present + Object.keys(requiredFields).forEach(function (field) { + if (!specifiedFields[field]) { + throw new Error("Invalid format. " + field + " is required in specified format"); + } + }); + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); }); + // Check if the date string matches the format. If it doesn't return null + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // For each match, call the parser function for that date part + for (var i = 1; i < matches.length; i++) { + var _a = parseInfo[i - 1], field = _a[0], parser = _a[2]; + var value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + dateInfo[field] = value; + } + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } + else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + var dateWithoutTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if (specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()) { + return null; + } + } + if (dateInfo.timezoneOffset == null) { + return dateWithoutTZ; + } + return new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); + } + var fecha = { + format: format, + parse: parse, + defaultI18n: defaultI18n, + setGlobalDateI18n: setGlobalDateI18n, + setGlobalDateMasks: setGlobalDateMasks + }; + + exports.assign = assign; + exports.default = fecha; + exports.format = format; + exports.parse = parse; + exports.defaultI18n = defaultI18n; + exports.setGlobalDateI18n = setGlobalDateI18n; + exports.setGlobalDateMasks = setGlobalDateMasks; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=fecha.umd.js.map diff --git a/build/node_modules/fecha/lib/fecha.umd.js.map b/build/node_modules/fecha/lib/fecha.umd.js.map new file mode 100644 index 00000000..04984276 --- /dev/null +++ b/build/node_modules/fecha/lib/fecha.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fecha.umd.js","sources":["../src/fecha.ts"],"sourcesContent":["const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\\1?|[aA]|\"[^\"]*\"|'[^']*'/g;\nconst twoDigitsOptional = \"[1-9]\\\\d?\";\nconst twoDigits = \"\\\\d\\\\d\";\nconst threeDigits = \"\\\\d{3}\";\nconst fourDigits = \"\\\\d{4}\";\nconst word = \"[^\\\\s]+\";\nconst literal = /\\[([^]*?)\\]/gm;\n\ntype DateInfo = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n millisecond: number;\n isPm: number | null;\n timezoneOffset: number | null;\n};\n\nexport type I18nSettings = {\n amPm: [string, string];\n dayNames: Days;\n dayNamesShort: Days;\n monthNames: Months;\n monthNamesShort: Months;\n DoFn(dayOfMonth: number): string;\n};\n\nexport type I18nSettingsOptional = Partial;\n\nexport type Days = [string, string, string, string, string, string, string];\nexport type Months = [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n string\n];\n\nfunction shorten(arr: T, sLen: number): string[] {\n const newArr: string[] = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\n\nconst monthUpdate = (\n arrName: \"monthNames\" | \"monthNamesShort\" | \"dayNames\" | \"dayNamesShort\"\n) => (v: string, i18n: I18nSettings): number | null => {\n const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase());\n const index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n};\n\nexport function assign(a: A): A;\nexport function assign(a: A, b: B): A & B;\nexport function assign(a: A, b: B, c: C): A & B & C;\nexport function assign(a: A, b: B, c: C, d: D): A & B & C & D;\nexport function assign(origObj: any, ...args: any[]): any {\n for (const obj of args) {\n for (const key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\n\nconst dayNames: Days = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nconst monthNames: Months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\n\nconst monthNamesShort: Months = shorten(monthNames, 3) as Months;\nconst dayNamesShort: Days = shorten(dayNames, 3) as Days;\n\nconst defaultI18n: I18nSettings = {\n dayNamesShort,\n dayNames,\n monthNamesShort,\n monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn(dayOfMonth: number) {\n return (\n dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][\n dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10\n ]\n );\n }\n};\nlet globalI18n = assign({}, defaultI18n);\nconst setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings =>\n (globalI18n = assign(globalI18n, i18n));\n\nconst regexEscape = (str: string): string =>\n str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n\nconst pad = (val: string | number, len = 2): string => {\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\n\nconst formatFlags: Record<\n string,\n (dateObj: Date, i18n: I18nSettings) => string\n> = {\n D: (dateObj: Date): string => String(dateObj.getDate()),\n DD: (dateObj: Date): string => pad(dateObj.getDate()),\n Do: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.DoFn(dateObj.getDate()),\n d: (dateObj: Date): string => String(dateObj.getDay()),\n dd: (dateObj: Date): string => pad(dateObj.getDay()),\n ddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNamesShort[dateObj.getDay()],\n dddd: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.dayNames[dateObj.getDay()],\n M: (dateObj: Date): string => String(dateObj.getMonth() + 1),\n MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1),\n MMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNamesShort[dateObj.getMonth()],\n MMMM: (dateObj: Date, i18n: I18nSettings): string =>\n i18n.monthNames[dateObj.getMonth()],\n YY: (dateObj: Date): string =>\n pad(String(dateObj.getFullYear()), 4).substr(2),\n YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4),\n h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12),\n hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12),\n H: (dateObj: Date): string => String(dateObj.getHours()),\n HH: (dateObj: Date): string => pad(dateObj.getHours()),\n m: (dateObj: Date): string => String(dateObj.getMinutes()),\n mm: (dateObj: Date): string => pad(dateObj.getMinutes()),\n s: (dateObj: Date): string => String(dateObj.getSeconds()),\n ss: (dateObj: Date): string => pad(dateObj.getSeconds()),\n S: (dateObj: Date): string =>\n String(Math.round(dateObj.getMilliseconds() / 100)),\n SS: (dateObj: Date): string =>\n pad(Math.round(dateObj.getMilliseconds() / 10), 2),\n SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3),\n a: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1],\n A: (dateObj: Date, i18n: I18nSettings): string =>\n dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase(),\n ZZ(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)\n );\n },\n Z(dateObj: Date): string {\n const offset = dateObj.getTimezoneOffset();\n return (\n (offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2)\n );\n }\n};\n\ntype ParseInfo = [\n keyof DateInfo,\n string,\n ((v: string, i18n: I18nSettings) => number | null)?,\n string?\n];\nconst monthParse = (v: string): number => +v - 1;\nconst emptyDigits: ParseInfo = [null, twoDigitsOptional];\nconst emptyWord: ParseInfo = [null, word];\nconst amPm: ParseInfo = [\n \"isPm\",\n word,\n (v: string, i18n: I18nSettings): number | null => {\n const val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n } else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nconst timezoneOffset: ParseInfo = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n (v: string): number | null => {\n const parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n\n if (parts) {\n const minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n\n return 0;\n }\n];\nconst parseFlags: Record = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n (v: string): number => {\n const now = new Date();\n const cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", (v: string): number => +v * 100],\n SS: [\"millisecond\", twoDigits, (v: string): number => +v * 10],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n\n// Some common format strings\nconst globalMasks: { [key: string]: string } = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nconst setGlobalDateMasks = (masks: {\n [key: string]: string;\n}): { [key: string]: string } => assign(globalMasks, masks);\n\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nconst format = (\n dateObj: Date,\n mask: string = globalMasks[\"default\"],\n i18n: I18nSettingsOptional = {}\n): string => {\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n\n if (\n Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())\n ) {\n throw new Error(\"Invalid Date pass to format\");\n }\n\n mask = globalMasks[mask] || mask;\n\n const literals: string[] = [];\n\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n // Apply formatting rules\n mask = mask.replace(token, $0 =>\n formatFlags[$0](dateObj, combinedI18nSettings)\n );\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, () => literals.shift());\n};\n\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(\n dateStr: string,\n format: string,\n i18n: I18nSettingsOptional = {}\n): Date | null {\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n\n // Default to the beginning of the year.\n const today = new Date();\n const dateInfo: DateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n const parseInfo: ParseInfo[] = [];\n const literals: string[] = [];\n\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n let newFormat = format.replace(literal, ($0, $1) => {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n const specifiedFields: { [field: string]: boolean } = {};\n const requiredFields: { [field: string]: boolean } = {};\n\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, $0 => {\n const info = parseFlags[$0];\n const [field, regex, , requiredField] = info;\n\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(`Invalid format. ${field} specified twice in format`);\n }\n\n specifiedFields[field] = true;\n\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(field => {\n if (!specifiedFields[field]) {\n throw new Error(\n `Invalid format. ${field} is required in specified format`\n );\n }\n });\n\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, () => literals.shift());\n\n // Check if the date string matches the format. If it doesn't return null\n const matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n\n const combinedI18nSettings: I18nSettings = assign(\n assign({}, globalI18n),\n i18n\n );\n\n // For each match, call the parser function for that date part\n for (let i = 1; i < matches.length; i++) {\n const [field, , parser] = parseInfo[i - 1];\n const value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n\n dateInfo[field] = value;\n }\n\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n\n const dateWithoutTZ: Date = new Date(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute,\n dateInfo.second,\n dateInfo.millisecond\n );\n\n const validateFields: [\n \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\",\n \"getMonth\" | \"getDate\" | \"getHours\" | \"getMinutes\" | \"getSeconds\"\n ][] = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (let i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (\n specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()\n ) {\n return null;\n }\n }\n\n if (dateInfo.timezoneOffset == null) {\n return dateWithoutTZ;\n }\n\n return new Date(\n Date.UTC(\n dateInfo.year,\n dateInfo.month,\n dateInfo.day,\n dateInfo.hour,\n dateInfo.minute - dateInfo.timezoneOffset,\n dateInfo.second,\n dateInfo.millisecond\n )\n );\n}\nexport default {\n format,\n parse,\n defaultI18n,\n setGlobalDateI18n,\n setGlobalDateMasks\n};\nexport { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n"],"names":[],"mappings":";;;;;;EAAA,IAAM,KAAK,GAAG,4EAA4E,CAAC;EAC3F,IAAM,iBAAiB,GAAG,WAAW,CAAC;EACtC,IAAM,SAAS,GAAG,QAAQ,CAAC;EAC3B,IAAM,WAAW,GAAG,QAAQ,CAAC;EAC7B,IAAM,UAAU,GAAG,QAAQ,CAAC;EAC5B,IAAM,IAAI,GAAG,SAAS,CAAC;EACvB,IAAM,OAAO,GAAG,eAAe,CAAC;EAyChC,SAAS,OAAO,CAAqB,GAAM,EAAE,IAAY;MACvD,IAAM,MAAM,GAAa,EAAE,CAAC;MAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;UAC9C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;OACrC;MACD,OAAO,MAAM,CAAC;EAChB,CAAC;EAED,IAAM,WAAW,GAAG,UAClB,OAAwE,IACrE,OAAA,UAAC,CAAS,EAAE,IAAkB;MACjC,IAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE,GAAA,CAAC,CAAC;MAC7D,IAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;MACpD,IAAI,KAAK,GAAG,CAAC,CAAC,EAAE;UACd,OAAO,KAAK,CAAC;OACd;MACD,OAAO,IAAI,CAAC;EACd,CAAC,GAAA,CAAC;AAMF,WAAgB,MAAM,CAAC,OAAY;MAAE,cAAc;WAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;UAAd,6BAAc;;MACjD,KAAkB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE;UAAnB,IAAM,GAAG,aAAA;UACZ,KAAK,IAAM,GAAG,IAAI,GAAG,EAAE;;cAErB,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;WACzB;OACF;MACD,OAAO,OAAO,CAAC;EACjB,CAAC;EAED,IAAM,QAAQ,GAAS;MACrB,QAAQ;MACR,QAAQ;MACR,SAAS;MACT,WAAW;MACX,UAAU;MACV,QAAQ;MACR,UAAU;GACX,CAAC;EACF,IAAM,UAAU,GAAW;MACzB,SAAS;MACT,UAAU;MACV,OAAO;MACP,OAAO;MACP,KAAK;MACL,MAAM;MACN,MAAM;MACN,QAAQ;MACR,WAAW;MACX,SAAS;MACT,UAAU;MACV,UAAU;GACX,CAAC;EAEF,IAAM,eAAe,GAAW,OAAO,CAAC,UAAU,EAAE,CAAC,CAAW,CAAC;EACjE,IAAM,aAAa,GAAS,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAS,CAAC;AAEzD,MAAM,WAAW,GAAiB;MAChC,aAAa,eAAA;MACb,QAAQ,UAAA;MACR,eAAe,iBAAA;MACf,UAAU,YAAA;MACV,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;MAClB,IAAI,EAAJ,UAAK,UAAkB;UACrB,QACE,UAAU;cACV,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CACtB,UAAU,GAAG,EAAE,GAAG,CAAC;oBACf,CAAC;oBACD,CAAC,CAAC,UAAU,IAAI,UAAU,GAAG,EAAE,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,UAAU,IAAI,EAAE,CACxE,EACD;OACH;GACF,CAAC;EACF,IAAI,UAAU,GAAG,MAAM,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC;AACzC,MAAM,iBAAiB,GAAG,UAAC,IAA0B;MACnD,QAAC,UAAU,GAAG,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC;EAAtC,CAAuC,CAAC;EAE1C,IAAM,WAAW,GAAG,UAAC,GAAW;MAC9B,OAAA,GAAG,CAAC,OAAO,CAAC,mBAAmB,EAAE,MAAM,CAAC;EAAxC,CAAwC,CAAC;EAE3C,IAAM,GAAG,GAAG,UAAC,GAAoB,EAAE,GAAO;MAAP,oBAAA,EAAA,OAAO;MACxC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;MAClB,OAAO,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;UACvB,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;OACjB;MACD,OAAO,GAAG,CAAC;EACb,CAAC,CAAC;EAEF,IAAM,WAAW,GAGb;MACF,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,GAAA;MACvD,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,GAAA;MACrD,EAAE,EAAE,UAAC,OAAa,EAAE,IAAkB;UACpC,OAAA,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;OAAA;MAC9B,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,GAAA;MACtD,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,GAAA;MACpD,GAAG,EAAE,UAAC,OAAa,EAAE,IAAkB;UACrC,OAAA,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;OAAA;MACtC,IAAI,EAAE,UAAC,OAAa,EAAE,IAAkB;UACtC,OAAA,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;OAAA;MACjC,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,GAAA;MAC5D,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,GAAA;MAC1D,GAAG,EAAE,UAAC,OAAa,EAAE,IAAkB;UACrC,OAAA,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;OAAA;MAC1C,IAAI,EAAE,UAAC,OAAa,EAAE,IAAkB;UACtC,OAAA,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;OAAA;MACrC,EAAE,EAAE,UAAC,OAAa;UAChB,OAAA,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;OAAA;MACjD,IAAI,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,GAAA;MAC9D,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,GAAA;MACnE,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,GAAA;MACjE,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAA;MACxD,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAA;MACtD,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;MAC1D,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;MACxD,CAAC,EAAE,UAAC,OAAa,IAAa,OAAA,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;MAC1D,EAAE,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,GAAA;MACxD,CAAC,EAAE,UAAC,OAAa;UACf,OAAA,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,GAAG,CAAC,CAAC;OAAA;MACrD,EAAE,EAAE,UAAC,OAAa;UAChB,OAAA,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;OAAA;MACpD,GAAG,EAAE,UAAC,OAAa,IAAa,OAAA,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,GAAA;MACjE,CAAC,EAAE,UAAC,OAAa,EAAE,IAAkB;UACnC,OAAA,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;OAAA;MACvD,CAAC,EAAE,UAAC,OAAa,EAAE,IAAkB;UACnC,OAAA,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE;gBACnB,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE;gBAC1B,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE;OAAA;MAChC,EAAE,EAAF,UAAG,OAAa;UACd,IAAM,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;UAC3C,QACE,CAAC,MAAM,GAAG,CAAC,GAAG,GAAG,GAAG,GAAG;cACvB,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC,EACzE;OACH;MACD,CAAC,EAAD,UAAE,OAAa;UACb,IAAM,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;UAC3C,QACE,CAAC,MAAM,GAAG,CAAC,GAAG,GAAG,GAAG,GAAG;cACvB,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;cACzC,GAAG;cACH,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAC7B;OACH;GACF,CAAC;EAQF,IAAM,UAAU,GAAG,UAAC,CAAS,IAAa,OAAA,CAAC,CAAC,GAAG,CAAC,GAAA,CAAC;EACjD,IAAM,WAAW,GAAc,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;EACzD,IAAM,SAAS,GAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;EAC1C,IAAM,IAAI,GAAc;MACtB,MAAM;MACN,IAAI;MACJ,UAAC,CAAS,EAAE,IAAkB;UAC5B,IAAM,GAAG,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;UAC5B,IAAI,GAAG,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;cACxB,OAAO,CAAC,CAAC;WACV;eAAM,IAAI,GAAG,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;cAC/B,OAAO,CAAC,CAAC;WACV;UACD,OAAO,IAAI,CAAC;OACb;GACF,CAAC;EACF,IAAM,cAAc,GAAc;MAChC,gBAAgB;MAChB,2CAA2C;MAC3C,UAAC,CAAS;UACR,IAAM,KAAK,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,KAAK,CAAC,eAAe,CAAC,CAAC;UAE9C,IAAI,KAAK,EAAE;cACT,IAAM,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;cACxD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,GAAG,OAAO,GAAG,CAAC,OAAO,CAAC;WAC9C;UAED,OAAO,CAAC,CAAC;OACV;GACF,CAAC;EACF,IAAM,UAAU,GAA8B;MAC5C,CAAC,EAAE,CAAC,KAAK,EAAE,iBAAiB,CAAC;MAC7B,EAAE,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC;MACtB,EAAE,EAAE,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,EAAE,UAAC,CAAS,IAAa,OAAA,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,GAAA,CAAC;MAC7E,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,EAAE,UAAU,CAAC;MAC3C,EAAE,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC;MACpC,EAAE,EAAE;UACF,MAAM;UACN,SAAS;UACT,UAAC,CAAS;cACR,IAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;cACvB,IAAM,IAAI,GAAG,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,WAAW,EAAE,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;cACpD,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;WAChD;OACF;MACD,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,CAAC;MACjD,EAAE,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC;MAC1C,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,CAAC;MAC9B,EAAE,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC;MACvB,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,CAAC;MAChC,EAAE,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;MACzB,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,CAAC;MAChC,EAAE,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;MACzB,IAAI,EAAE,CAAC,MAAM,EAAE,UAAU,CAAC;MAC1B,CAAC,EAAE,CAAC,aAAa,EAAE,KAAK,EAAE,UAAC,CAAS,IAAa,OAAA,CAAC,CAAC,GAAG,GAAG,GAAA,CAAC;MAC1D,EAAE,EAAE,CAAC,aAAa,EAAE,SAAS,EAAE,UAAC,CAAS,IAAa,OAAA,CAAC,CAAC,GAAG,EAAE,GAAA,CAAC;MAC9D,GAAG,EAAE,CAAC,aAAa,EAAE,WAAW,CAAC;MACjC,CAAC,EAAE,WAAW;MACd,EAAE,EAAE,WAAW;MACf,GAAG,EAAE,SAAS;MACd,IAAI,EAAE,SAAS;MACf,GAAG,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,WAAW,CAAC,iBAAiB,CAAC,CAAC;MACpD,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;MAChD,CAAC,EAAE,IAAI;MACP,CAAC,EAAE,IAAI;MACP,EAAE,EAAE,cAAc;MAClB,CAAC,EAAE,cAAc;GAClB,CAAC;EAEF;EACA,IAAM,WAAW,GAA8B;MAC7C,OAAO,EAAE,0BAA0B;MACnC,SAAS,EAAE,QAAQ;MACnB,UAAU,EAAE,aAAa;MACzB,QAAQ,EAAE,cAAc;MACxB,QAAQ,EAAE,oBAAoB;MAC9B,OAAO,EAAE,YAAY;MACrB,WAAW,EAAE,sBAAsB;MACnC,SAAS,EAAE,OAAO;MAClB,UAAU,EAAE,UAAU;MACtB,QAAQ,EAAE,cAAc;GACzB,CAAC;AACF,MAAM,kBAAkB,GAAG,UAAC,KAE3B,IAAgC,OAAA,MAAM,CAAC,WAAW,EAAE,KAAK,CAAC,GAAA,CAAC;EAE5D;;;;;;;AAOA,MAAM,MAAM,GAAG,UACb,OAAa,EACb,IAAqC,EACrC,IAA+B;MAD/B,qBAAA,EAAA,OAAe,WAAW,CAAC,SAAS,CAAC;MACrC,qBAAA,EAAA,SAA+B;MAE/B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;UAC/B,OAAO,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC;OAC7B;MAED,IACE,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,eAAe;UAC3D,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EACxB;UACA,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;OAChD;MAED,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;MAEjC,IAAM,QAAQ,GAAa,EAAE,CAAC;;MAG9B,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,UAAS,EAAE,EAAE,EAAE;UAC1C,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;UAClB,OAAO,KAAK,CAAC;OACd,CAAC,CAAC;MAEH,IAAM,oBAAoB,GAAiB,MAAM,CAC/C,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,EACtB,IAAI,CACL,CAAC;;MAEF,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,UAAA,EAAE;UAC3B,OAAA,WAAW,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,oBAAoB,CAAC;OAAA,CAC/C,CAAC;;MAEF,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,cAAM,OAAA,QAAQ,CAAC,KAAK,EAAE,GAAA,CAAC,CAAC;EACtD,CAAC,CAAC;EAEF;;;;;;;;EAQA,SAAS,KAAK,CACZ,OAAe,EACf,MAAc,EACd,IAA+B;MAA/B,qBAAA,EAAA,SAA+B;MAE/B,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;UAC9B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;OAClD;;MAGD,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC;;;MAIvC,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,EAAE;UACzB,OAAO,IAAI,CAAC;OACb;;MAGD,IAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC;MACzB,IAAM,QAAQ,GAAa;UACzB,IAAI,EAAE,KAAK,CAAC,WAAW,EAAE;UACzB,KAAK,EAAE,CAAC;UACR,GAAG,EAAE,CAAC;UACN,IAAI,EAAE,CAAC;UACP,MAAM,EAAE,CAAC;UACT,MAAM,EAAE,CAAC;UACT,WAAW,EAAE,CAAC;UACd,IAAI,EAAE,IAAI;UACV,cAAc,EAAE,IAAI;OACrB,CAAC;MACF,IAAM,SAAS,GAAgB,EAAE,CAAC;MAClC,IAAM,QAAQ,GAAa,EAAE,CAAC;;MAG9B,IAAI,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,UAAC,EAAE,EAAE,EAAE;UAC7C,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;UAC/B,OAAO,KAAK,CAAC;OACd,CAAC,CAAC;MACH,IAAM,eAAe,GAAiC,EAAE,CAAC;MACzD,IAAM,cAAc,GAAiC,EAAE,CAAC;;MAGxD,SAAS,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,UAAA,EAAE;UAClD,IAAM,IAAI,GAAG,UAAU,CAAC,EAAE,CAAC,CAAC;UACrB,IAAA,KAAK,GAA4B,IAAI,GAAhC,EAAE,KAAK,GAAqB,IAAI,GAAzB,EAAI,aAAa,GAAI,IAAI,GAAR,CAAS;;UAG7C,IAAI,eAAe,CAAC,KAAK,CAAC,EAAE;cAC1B,MAAM,IAAI,KAAK,CAAC,qBAAmB,KAAK,+BAA4B,CAAC,CAAC;WACvE;UAED,eAAe,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;;UAG9B,IAAI,aAAa,EAAE;cACjB,cAAc,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC;WACtC;UAED,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;UACrB,OAAO,GAAG,GAAG,KAAK,GAAG,GAAG,CAAC;OAC1B,CAAC,CAAC;;MAGH,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,UAAA,KAAK;UACvC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE;cAC3B,MAAM,IAAI,KAAK,CACb,qBAAmB,KAAK,qCAAkC,CAC3D,CAAC;WACH;OACF,CAAC,CAAC;;MAGH,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,cAAM,OAAA,QAAQ,CAAC,KAAK,EAAE,GAAA,CAAC,CAAC;;MAG9D,IAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC;MAC1D,IAAI,CAAC,OAAO,EAAE;UACZ,OAAO,IAAI,CAAC;OACb;MAED,IAAM,oBAAoB,GAAiB,MAAM,CAC/C,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,EACtB,IAAI,CACL,CAAC;;MAGF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;UACjC,IAAA,KAAoB,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,EAAnC,KAAK,QAAA,EAAI,MAAM,QAAoB,CAAC;UAC3C,IAAM,KAAK,GAAG,MAAM;gBAChB,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,oBAAoB,CAAC;gBACxC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;;UAGhB,IAAI,KAAK,IAAI,IAAI,EAAE;cACjB,OAAO,IAAI,CAAC;WACb;UAED,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;OACzB;MAED,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC,IAAI,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,EAAE,EAAE;UACzE,QAAQ,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC;OACrC;WAAM,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,KAAK,EAAE,EAAE;UACvD,QAAQ,CAAC,IAAI,GAAG,CAAC,CAAC;OACnB;MAED,IAAM,aAAa,GAAS,IAAI,IAAI,CAClC,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,KAAK,EACd,QAAQ,CAAC,GAAG,EACZ,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,WAAW,CACrB,CAAC;MAEF,IAAM,cAAc,GAGd;UACJ,CAAC,OAAO,EAAE,UAAU,CAAC;UACrB,CAAC,KAAK,EAAE,SAAS,CAAC;UAClB,CAAC,MAAM,EAAE,UAAU,CAAC;UACpB,CAAC,QAAQ,EAAE,YAAY,CAAC;UACxB,CAAC,QAAQ,EAAE,YAAY,CAAC;OACzB,CAAC;MACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;;;UAGzD,IACE,eAAe,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;cACrC,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EACxE;cACA,OAAO,IAAI,CAAC;WACb;OACF;MAED,IAAI,QAAQ,CAAC,cAAc,IAAI,IAAI,EAAE;UACnC,OAAO,aAAa,CAAC;OACtB;MAED,OAAO,IAAI,IAAI,CACb,IAAI,CAAC,GAAG,CACN,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,KAAK,EACd,QAAQ,CAAC,GAAG,EACZ,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,cAAc,EACzC,QAAQ,CAAC,MAAM,EACf,QAAQ,CAAC,WAAW,CACrB,CACF,CAAC;EACJ,CAAC;AACD,cAAe;MACb,MAAM,QAAA;MACN,KAAK,OAAA;MACL,WAAW,aAAA;MACX,iBAAiB,mBAAA;MACjB,kBAAkB,oBAAA;GACnB,CAAC;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/build/node_modules/fecha/package.json b/build/node_modules/fecha/package.json new file mode 100644 index 00000000..d59b2f5a --- /dev/null +++ b/build/node_modules/fecha/package.json @@ -0,0 +1,82 @@ +{ + "_from": "fecha@^4.2.0", + "_id": "fecha@4.2.1", + "_inBundle": false, + "_integrity": "sha512-MMMQ0ludy/nBs1/o0zVOiKTpG7qMbonKUzjJgQFEuvq6INZ1OraKPRAWkBq5vlKLOUMpmNYG1JoN3oDPUQ9m3Q==", + "_location": "/fecha", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "fecha@^4.2.0", + "name": "fecha", + "escapedName": "fecha", + "rawSpec": "^4.2.0", + "saveSpec": null, + "fetchSpec": "^4.2.0" + }, + "_requiredBy": [ + "/logform" + ], + "_resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.1.tgz", + "_shasum": "0a83ad8f86ef62a091e22bb5a039cd03d23eecce", + "_spec": "fecha@^4.2.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/logform", + "author": { + "name": "Taylor Hakes" + }, + "bugs": { + "url": "https://github.com/taylorhakes/fecha/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Date formatting and parsing", + "devDependencies": { + "@istanbuljs/nyc-config-typescript": "^1.0.1", + "@typescript-eslint/eslint-plugin": "^2.14.0", + "@typescript-eslint/parser": "^2.14.0", + "eslint": "^7.23.0", + "eslint-config-prettier": "^8.1.0", + "nyc": "^15.0.0", + "painless": "^0.9.7", + "prettier": "1.19.1", + "rollup": "^0.59.0", + "rollup-plugin-sourcemaps": "^0.5.0", + "rollup-plugin-typescript": "^1.0.1", + "rollup-plugin-uglify": "^3.0.0", + "source-map-support": "^0.5.16", + "ts-node": "^8.5.4", + "tslib": "^1.10.0", + "typescript": "^3.7.4" + }, + "files": [ + "lib", + "dist", + "src" + ], + "homepage": "https://github.com/taylorhakes/fecha", + "keywords": [ + "date", + "parse", + "moment", + "format", + "fecha", + "formatting" + ], + "license": "MIT", + "main": "lib/fecha.umd.js", + "module": "lib/fecha.js", + "name": "fecha", + "repository": { + "type": "git", + "url": "git+https://taylorhakes@github.com/taylorhakes/fecha.git" + }, + "scripts": { + "build": "NODE_ENV=production rollup -c --sourcemap && tsc", + "format": "prettier --write *.js src/*.ts", + "test": "prettier --check *.js src/*.ts && eslint --ext .ts src && npm run build && nyc --cache --reporter=text ts-node test.js", + "test-only": "ts-node test.js" + }, + "types": "lib/fecha.d.ts", + "version": "4.2.1" +} diff --git a/build/node_modules/fecha/src/fecha.ts b/build/node_modules/fecha/src/fecha.ts new file mode 100644 index 00000000..e2c2f21e --- /dev/null +++ b/build/node_modules/fecha/src/fecha.ts @@ -0,0 +1,506 @@ +const token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; +const twoDigitsOptional = "[1-9]\\d?"; +const twoDigits = "\\d\\d"; +const threeDigits = "\\d{3}"; +const fourDigits = "\\d{4}"; +const word = "[^\\s]+"; +const literal = /\[([^]*?)\]/gm; + +type DateInfo = { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + millisecond: number; + isPm: number | null; + timezoneOffset: number | null; +}; + +export type I18nSettings = { + amPm: [string, string]; + dayNames: Days; + dayNamesShort: Days; + monthNames: Months; + monthNamesShort: Months; + DoFn(dayOfMonth: number): string; +}; + +export type I18nSettingsOptional = Partial; + +export type Days = [string, string, string, string, string, string, string]; +export type Months = [ + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string +]; + +function shorten(arr: T, sLen: number): string[] { + const newArr: string[] = []; + for (let i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; +} + +const monthUpdate = ( + arrName: "monthNames" | "monthNamesShort" | "dayNames" | "dayNamesShort" +) => (v: string, i18n: I18nSettings): number | null => { + const lowerCaseArr = i18n[arrName].map(v => v.toLowerCase()); + const index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; +}; + +export function assign(a: A): A; +export function assign(a: A, b: B): A & B; +export function assign(a: A, b: B, c: C): A & B & C; +export function assign(a: A, b: B, c: C, d: D): A & B & C & D; +export function assign(origObj: any, ...args: any[]): any { + for (const obj of args) { + for (const key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; +} + +const dayNames: Days = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" +]; +const monthNames: Months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; + +const monthNamesShort: Months = shorten(monthNames, 3) as Months; +const dayNamesShort: Days = shorten(dayNames, 3) as Days; + +const defaultI18n: I18nSettings = { + dayNamesShort, + dayNames, + monthNamesShort, + monthNames, + amPm: ["am", "pm"], + DoFn(dayOfMonth: number) { + return ( + dayOfMonth + + ["th", "st", "nd", "rd"][ + dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10 + ] + ); + } +}; +let globalI18n = assign({}, defaultI18n); +const setGlobalDateI18n = (i18n: I18nSettingsOptional): I18nSettings => + (globalI18n = assign(globalI18n, i18n)); + +const regexEscape = (str: string): string => + str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); + +const pad = (val: string | number, len = 2): string => { + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; +}; + +const formatFlags: Record< + string, + (dateObj: Date, i18n: I18nSettings) => string +> = { + D: (dateObj: Date): string => String(dateObj.getDate()), + DD: (dateObj: Date): string => pad(dateObj.getDate()), + Do: (dateObj: Date, i18n: I18nSettings): string => + i18n.DoFn(dateObj.getDate()), + d: (dateObj: Date): string => String(dateObj.getDay()), + dd: (dateObj: Date): string => pad(dateObj.getDay()), + ddd: (dateObj: Date, i18n: I18nSettings): string => + i18n.dayNamesShort[dateObj.getDay()], + dddd: (dateObj: Date, i18n: I18nSettings): string => + i18n.dayNames[dateObj.getDay()], + M: (dateObj: Date): string => String(dateObj.getMonth() + 1), + MM: (dateObj: Date): string => pad(dateObj.getMonth() + 1), + MMM: (dateObj: Date, i18n: I18nSettings): string => + i18n.monthNamesShort[dateObj.getMonth()], + MMMM: (dateObj: Date, i18n: I18nSettings): string => + i18n.monthNames[dateObj.getMonth()], + YY: (dateObj: Date): string => + pad(String(dateObj.getFullYear()), 4).substr(2), + YYYY: (dateObj: Date): string => pad(dateObj.getFullYear(), 4), + h: (dateObj: Date): string => String(dateObj.getHours() % 12 || 12), + hh: (dateObj: Date): string => pad(dateObj.getHours() % 12 || 12), + H: (dateObj: Date): string => String(dateObj.getHours()), + HH: (dateObj: Date): string => pad(dateObj.getHours()), + m: (dateObj: Date): string => String(dateObj.getMinutes()), + mm: (dateObj: Date): string => pad(dateObj.getMinutes()), + s: (dateObj: Date): string => String(dateObj.getSeconds()), + ss: (dateObj: Date): string => pad(dateObj.getSeconds()), + S: (dateObj: Date): string => + String(Math.round(dateObj.getMilliseconds() / 100)), + SS: (dateObj: Date): string => + pad(Math.round(dateObj.getMilliseconds() / 10), 2), + SSS: (dateObj: Date): string => pad(dateObj.getMilliseconds(), 3), + a: (dateObj: Date, i18n: I18nSettings): string => + dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1], + A: (dateObj: Date, i18n: I18nSettings): string => + dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(), + ZZ(dateObj: Date): string { + const offset = dateObj.getTimezoneOffset(); + return ( + (offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4) + ); + }, + Z(dateObj: Date): string { + const offset = dateObj.getTimezoneOffset(); + return ( + (offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2) + ); + } +}; + +type ParseInfo = [ + keyof DateInfo, + string, + ((v: string, i18n: I18nSettings) => number | null)?, + string? +]; +const monthParse = (v: string): number => +v - 1; +const emptyDigits: ParseInfo = [null, twoDigitsOptional]; +const emptyWord: ParseInfo = [null, word]; +const amPm: ParseInfo = [ + "isPm", + word, + (v: string, i18n: I18nSettings): number | null => { + const val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } +]; +const timezoneOffset: ParseInfo = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + (v: string): number | null => { + const parts = (v + "").match(/([+-]|\d\d)/gi); + + if (parts) { + const minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + + return 0; + } +]; +const parseFlags: Record = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, (v: string): number => parseInt(v, 10)], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + (v: string): number => { + const now = new Date(); + const cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", (v: string): number => +v * 100], + SS: ["millisecond", twoDigits, (v: string): number => +v * 10], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset +}; + +// Some common format strings +const globalMasks: { [key: string]: string } = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; +const setGlobalDateMasks = (masks: { + [key: string]: string; +}): { [key: string]: string } => assign(globalMasks, masks); + +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +const format = ( + dateObj: Date, + mask: string = globalMasks["default"], + i18n: I18nSettingsOptional = {} +): string => { + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + + if ( + Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime()) + ) { + throw new Error("Invalid Date pass to format"); + } + + mask = globalMasks[mask] || mask; + + const literals: string[] = []; + + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function($0, $1) { + literals.push($1); + return "@@@"; + }); + + const combinedI18nSettings: I18nSettings = assign( + assign({}, globalI18n), + i18n + ); + // Apply formatting rules + mask = mask.replace(token, $0 => + formatFlags[$0](dateObj, combinedI18nSettings) + ); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, () => literals.shift()); +}; + +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +function parse( + dateStr: string, + format: string, + i18n: I18nSettingsOptional = {} +): Date | null { + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + + // Default to the beginning of the year. + const today = new Date(); + const dateInfo: DateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + const parseInfo: ParseInfo[] = []; + const literals: string[] = []; + + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + let newFormat = format.replace(literal, ($0, $1) => { + literals.push(regexEscape($1)); + return "@@@"; + }); + const specifiedFields: { [field: string]: boolean } = {}; + const requiredFields: { [field: string]: boolean } = {}; + + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, $0 => { + const info = parseFlags[$0]; + const [field, regex, , requiredField] = info; + + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error(`Invalid format. ${field} specified twice in format`); + } + + specifiedFields[field] = true; + + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + + parseInfo.push(info); + return "(" + regex + ")"; + }); + + // Check all the required fields are present + Object.keys(requiredFields).forEach(field => { + if (!specifiedFields[field]) { + throw new Error( + `Invalid format. ${field} is required in specified format` + ); + } + }); + + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, () => literals.shift()); + + // Check if the date string matches the format. If it doesn't return null + const matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + + const combinedI18nSettings: I18nSettings = assign( + assign({}, globalI18n), + i18n + ); + + // For each match, call the parser function for that date part + for (let i = 1; i < matches.length; i++) { + const [field, , parser] = parseInfo[i - 1]; + const value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + + dateInfo[field] = value; + } + + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + + const dateWithoutTZ: Date = new Date( + dateInfo.year, + dateInfo.month, + dateInfo.day, + dateInfo.hour, + dateInfo.minute, + dateInfo.second, + dateInfo.millisecond + ); + + const validateFields: [ + "month" | "day" | "hour" | "minute" | "second", + "getMonth" | "getDate" | "getHours" | "getMinutes" | "getSeconds" + ][] = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (let i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if ( + specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]() + ) { + return null; + } + } + + if (dateInfo.timezoneOffset == null) { + return dateWithoutTZ; + } + + return new Date( + Date.UTC( + dateInfo.year, + dateInfo.month, + dateInfo.day, + dateInfo.hour, + dateInfo.minute - dateInfo.timezoneOffset, + dateInfo.second, + dateInfo.millisecond + ) + ); +} +export default { + format, + parse, + defaultI18n, + setGlobalDateI18n, + setGlobalDateMasks +}; +export { format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks }; diff --git a/build/node_modules/fn.name/.gitattributes b/build/node_modules/fn.name/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/build/node_modules/fn.name/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/build/node_modules/fn.name/.travis.yml b/build/node_modules/fn.name/.travis.yml new file mode 100644 index 00000000..dec03398 --- /dev/null +++ b/build/node_modules/fn.name/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - "10" + - "8" + - "6" + - "4" +script: + - "npm run test-travis" +after_script: + - "npm install coveralls@2.11.x && cat coverage/lcov.info | coveralls" diff --git a/build/node_modules/fn.name/LICENSE b/build/node_modules/fn.name/LICENSE new file mode 100644 index 00000000..b68d272b --- /dev/null +++ b/build/node_modules/fn.name/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Arnout Kazemier, Martijn Swaagman, the 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. + diff --git a/build/node_modules/fn.name/README.md b/build/node_modules/fn.name/README.md new file mode 100644 index 00000000..1b199ea8 --- /dev/null +++ b/build/node_modules/fn.name/README.md @@ -0,0 +1,42 @@ +# fn.name + +[![Version npm][version]](http://npm.im/fn.name)[![Build Status][build]](https://travis-ci.org/3rd-Eden/fn.name)[![Dependencies][david]](https://david-dm.org/3rd-Eden/fn.name)[![Coverage Status][cover]](https://coveralls.io/r/3rd-Eden/fn.name?branch=master) + +[version]: http://img.shields.io/npm/v/fn.name.svg?style=flat-square +[build]: http://img.shields.io/travis/3rd-Eden/fn.name/master.svg?style=flat-square +[david]: https://img.shields.io/david/3rd-Eden/fn.name.svg?style=flat-square +[cover]: http://img.shields.io/coveralls/3rd-Eden/fn.name/master.svg?style=flat-square + +Extract the name of a given function. Nothing more than that. + +## Installation + +This module is compatible with Browserify and Node.js and can be installed +using: + +``` +npm install --save fn.name +``` + +## Usage + +Using this module is super simple, it exposes the function directly on the +exports so it can be required as followed: + +```js +'use strict'; + +var name = require('fn.name'); +``` + +Now that we have the `name` function we can pass it functions: + +```js +console.log(name(function foo() {})) // foo +``` + +And that's it folks! + +## License + +MIT diff --git a/build/node_modules/fn.name/index.js b/build/node_modules/fn.name/index.js new file mode 100644 index 00000000..0fb0f596 --- /dev/null +++ b/build/node_modules/fn.name/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var toString = Object.prototype.toString; + +/** + * Extract names from functions. + * + * @param {Function} fn The function who's name we need to extract. + * @returns {String} The name of the function. + * @public + */ +module.exports = function name(fn) { + if ('string' === typeof fn.displayName && fn.constructor.name) { + return fn.displayName; + } else if ('string' === typeof fn.name && fn.name) { + return fn.name; + } + + // + // Check to see if the constructor has a name. + // + if ( + 'object' === typeof fn + && fn.constructor + && 'string' === typeof fn.constructor.name + ) return fn.constructor.name; + + // + // toString the given function and attempt to parse it out of it, or determine + // the class. + // + var named = fn.toString() + , type = toString.call(fn).slice(8, -1); + + if ('Function' === type) { + named = named.substring(named.indexOf('(') + 1, named.indexOf(')')); + } else { + named = type; + } + + return named || 'anonymous'; +}; diff --git a/build/node_modules/fn.name/package.json b/build/node_modules/fn.name/package.json new file mode 100644 index 00000000..cafc2569 --- /dev/null +++ b/build/node_modules/fn.name/package.json @@ -0,0 +1,64 @@ +{ + "_from": "fn.name@1.x.x", + "_id": "fn.name@1.1.0", + "_inBundle": false, + "_integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==", + "_location": "/fn.name", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "fn.name@1.x.x", + "name": "fn.name", + "escapedName": "fn.name", + "rawSpec": "1.x.x", + "saveSpec": null, + "fetchSpec": "1.x.x" + }, + "_requiredBy": [ + "/one-time" + ], + "_resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "_shasum": "26cad8017967aea8731bc42961d04a3d5988accc", + "_spec": "fn.name@1.x.x", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/one-time", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/3rd-Eden/fn.name/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Extract names from functions", + "devDependencies": { + "assume": "2.x.x", + "istanbul": "0.3.x", + "mocha": "5.x.x", + "pre-commit": "1.x.x" + }, + "homepage": "https://github.com/3rd-Eden/fn.name", + "keywords": [ + "fn.name", + "function.name", + "name", + "function", + "extract", + "parse", + "names" + ], + "license": "MIT", + "main": "index.js", + "name": "fn.name", + "repository": { + "type": "git", + "url": "git+https://github.com/3rd-Eden/fn.name.git" + }, + "scripts": { + "coverage": "istanbul cover ./node_modules/.bin/_mocha -- test.js", + "test": "mocha test.js", + "test-travis": "istanbul cover node_modules/.bin/_mocha --report lcovonly -- test.js", + "watch": "mocha --watch test.js" + }, + "version": "1.1.0" +} diff --git a/build/node_modules/fn.name/test.js b/build/node_modules/fn.name/test.js new file mode 100644 index 00000000..b7d8f443 --- /dev/null +++ b/build/node_modules/fn.name/test.js @@ -0,0 +1,73 @@ +describe('fn.name', function () { + 'use strict'; + + var assume = require('assume') + , name = require('./'); + + it('is exported as a function', function () { + assume(name).is.a('function'); + }); + + it('can extract the name from a function declaration', function () { + function foobar() {} + + assume(name(foobar)).equals('foobar'); + }); + + it('can extract the name from a function expression', function () { + var a = function bar() {}; + + assume(name(a)).equals('bar'); + }); + + it('can be overriden using displayName', function () { + var a = function bar() {}; + a.displayName = 'bro'; + + assume(name(a)).equals('bro'); + }); + + it('works with constructed instances', function () { + function Bar(){} + + var foo = new Bar(); + + assume(name(foo)).equals('Bar'); + }); + + it('works with anonymous', function () { + assume(name(function () {})).equals('anonymous'); + }); + + it('returns the className if we were not given a function', function () { + assume(name('string')).equals('String'); + }); + + // + // Test if the env supports async functions, if so add a test to ensure + // that we will work with async functions. + // + var asyncfn = true; + try { new Function('return async function hello() {}')(); } + catch (e) { asyncfn = false; } + + if (asyncfn) it('detects the name of async functions', function () { + var fn = new Function('return async function hello() {}')(); + + assume(name(fn)).equals('hello'); + }); + + // + // Test that this env supports generators, if so add a test to ensure that + // we will work with generators. + // + var generators = true; + try { new Function('return function* generator() {}')(); } + catch (e) { generator = false; } + + if (generators) it('detecs the name of a generator', function () { + var fn = new Function('return function* hello() {}')(); + + assume(name(fn)).equals('hello'); + }); +}); diff --git a/build/node_modules/inherits/package.json b/build/node_modules/inherits/package.json index df371c35..099cfed4 100644 --- a/build/node_modules/inherits/package.json +++ b/build/node_modules/inherits/package.json @@ -40,7 +40,8 @@ "/readable-stream", "/ripemd160", "/sha.js", - "/util" + "/util", + "/winston/readable-stream" ], "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", diff --git a/build/node_modules/is-arrayish/LICENSE b/build/node_modules/is-arrayish/LICENSE new file mode 100644 index 00000000..0a5f461a --- /dev/null +++ b/build/node_modules/is-arrayish/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 JD Ballard + +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. diff --git a/build/node_modules/is-arrayish/README.md b/build/node_modules/is-arrayish/README.md new file mode 100644 index 00000000..7d360724 --- /dev/null +++ b/build/node_modules/is-arrayish/README.md @@ -0,0 +1,16 @@ +# node-is-arrayish [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-is-arrayish.svg?style=flat-square)](https://travis-ci.org/Qix-/node-is-arrayish) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-is-arrayish.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-is-arrayish) +> Determines if an object can be used like an Array + +## Example +```javascript +var isArrayish = require('is-arrayish'); + +isArrayish([]); // true +isArrayish({__proto__: []}); // true +isArrayish({}); // false +isArrayish({length:10}); // false +``` + +## License +Licensed under the [MIT License](http://opensource.org/licenses/MIT). +You can find a copy of it in [LICENSE](LICENSE). diff --git a/build/node_modules/is-arrayish/index.js b/build/node_modules/is-arrayish/index.js new file mode 100644 index 00000000..729ca40c --- /dev/null +++ b/build/node_modules/is-arrayish/index.js @@ -0,0 +1,9 @@ +module.exports = function isArrayish(obj) { + if (!obj || typeof obj === 'string') { + return false; + } + + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && (obj.splice instanceof Function || + (Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String'))); +}; diff --git a/build/node_modules/is-arrayish/package.json b/build/node_modules/is-arrayish/package.json new file mode 100644 index 00000000..980e3cee --- /dev/null +++ b/build/node_modules/is-arrayish/package.json @@ -0,0 +1,77 @@ +{ + "_from": "is-arrayish@^0.3.1", + "_id": "is-arrayish@0.3.2", + "_inBundle": false, + "_integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==", + "_location": "/is-arrayish", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-arrayish@^0.3.1", + "name": "is-arrayish", + "escapedName": "is-arrayish", + "rawSpec": "^0.3.1", + "saveSpec": null, + "fetchSpec": "^0.3.1" + }, + "_requiredBy": [ + "/simple-swizzle" + ], + "_resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "_shasum": "4574a2ae56f7ab206896fb431eaeed066fdf8f03", + "_spec": "is-arrayish@^0.3.1", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/simple-swizzle", + "author": { + "name": "Qix", + "url": "http://github.com/qix-" + }, + "bugs": { + "url": "https://github.com/qix-/node-is-arrayish/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Determines if an object can be used as an array", + "devDependencies": { + "@zeit/eslint-config-node": "^0.3.0", + "@zeit/git-hooks": "^0.1.4", + "coffeescript": "^2.3.1", + "coveralls": "^3.0.1", + "eslint": "^4.19.1", + "istanbul": "^0.4.5", + "mocha": "^5.2.0", + "should": "^13.2.1" + }, + "eslintConfig": { + "extends": [ + "@zeit/eslint-config-node" + ] + }, + "git": { + "pre-commit": "lint-staged" + }, + "homepage": "https://github.com/qix-/node-is-arrayish#readme", + "keywords": [ + "is", + "array", + "duck", + "type", + "arrayish", + "similar", + "proto", + "prototype", + "type" + ], + "license": "MIT", + "name": "is-arrayish", + "repository": { + "type": "git", + "url": "git+https://github.com/qix-/node-is-arrayish.git" + }, + "scripts": { + "lint": "zeit-eslint --ext .jsx,.js .", + "lint-staged": "git diff --diff-filter=ACMRT --cached --name-only '*.js' '*.jsx' | xargs zeit-eslint", + "test": "mocha --require coffeescript/register ./test/**/*.coffee" + }, + "version": "0.3.2" +} diff --git a/build/node_modules/is-arrayish/yarn-error.log b/build/node_modules/is-arrayish/yarn-error.log new file mode 100644 index 00000000..d3dcf37b --- /dev/null +++ b/build/node_modules/is-arrayish/yarn-error.log @@ -0,0 +1,1443 @@ +Arguments: + /Users/junon/n/bin/node /Users/junon/.yarn/bin/yarn.js test + +PATH: + /Users/junon/.yarn/bin:/Users/junon/.config/yarn/global/node_modules/.bin:/Users/junon/perl5/bin:/Users/junon/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Users/junon/bin:/Users/junon/.local/bin:/src/.go/bin:/src/llvm/llvm/build/bin:/Users/junon/Library/Android/sdk/platform-tools:/Users/junon/n/bin:/usr/local/texlive/2017/bin/x86_64-darwin/ + +Yarn version: + 1.5.1 + +Node version: + 9.6.1 + +Platform: + darwin x64 + +npm manifest: + { + "name": "is-arrayish", + "description": "Determines if an object can be used as an array", + "version": "0.3.1", + "author": "Qix (http://github.com/qix-)", + "keywords": [ + "is", + "array", + "duck", + "type", + "arrayish", + "similar", + "proto", + "prototype", + "type" + ], + "license": "MIT", + "scripts": { + "test": "mocha --require coffeescript/register", + "lint": "zeit-eslint --ext .jsx,.js .", + "lint-staged": "git diff --diff-filter=ACMRT --cached --name-only '*.js' '*.jsx' | xargs zeit-eslint" + }, + "repository": { + "type": "git", + "url": "https://github.com/qix-/node-is-arrayish.git" + }, + "devDependencies": { + "@zeit/eslint-config-node": "^0.3.0", + "@zeit/git-hooks": "^0.1.4", + "coffeescript": "^2.3.1", + "coveralls": "^3.0.1", + "eslint": "^4.19.1", + "istanbul": "^0.4.5", + "mocha": "^5.2.0", + "should": "^13.2.1" + }, + "eslintConfig": { + "extends": [ + "@zeit/eslint-config-node" + ] + }, + "git": { + "pre-commit": "lint-staged" + } + } + +yarn manifest: + No manifest + +Lockfile: + # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + # yarn lockfile v1 + + + "@zeit/eslint-config-base@0.3.0": + version "0.3.0" + resolved "https://registry.yarnpkg.com/@zeit/eslint-config-base/-/eslint-config-base-0.3.0.tgz#32a58c3e52eca4025604758cb4591f3d28e22fb4" + dependencies: + arg "^1.0.0" + chalk "^2.3.0" + + "@zeit/eslint-config-node@^0.3.0": + version "0.3.0" + resolved "https://registry.yarnpkg.com/@zeit/eslint-config-node/-/eslint-config-node-0.3.0.tgz#6e328328f366f66c2a0549a69131bbcd9735f098" + dependencies: + "@zeit/eslint-config-base" "0.3.0" + + "@zeit/git-hooks@^0.1.4": + version "0.1.4" + resolved "https://registry.yarnpkg.com/@zeit/git-hooks/-/git-hooks-0.1.4.tgz#70583db5dd69726a62c7963520e67f2c3a33cc5f" + + abbrev@1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" + + abbrev@1.0.x: + version "1.0.9" + resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135" + + acorn-jsx@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-3.0.1.tgz#afdf9488fb1ecefc8348f6fb22f464e32a58b36b" + dependencies: + acorn "^3.0.4" + + acorn@^3.0.4: + version "3.3.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" + + acorn@^5.5.0: + version "5.7.1" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.7.1.tgz#f095829297706a7c9776958c0afc8930a9b9d9d8" + + ajv-keywords@^2.1.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-2.1.1.tgz#617997fc5f60576894c435f940d819e135b80762" + + ajv@^5.1.0, ajv@^5.2.3, ajv@^5.3.0: + version "5.5.2" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965" + dependencies: + co "^4.6.0" + fast-deep-equal "^1.0.0" + fast-json-stable-stringify "^2.0.0" + json-schema-traverse "^0.3.0" + + align-text@^0.1.1, align-text@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" + dependencies: + kind-of "^3.0.2" + longest "^1.0.1" + repeat-string "^1.5.2" + + amdefine@>=0.0.4: + version "1.0.1" + resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" + + ansi-escapes@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.1.0.tgz#f73207bb81207d75fd6c83f125af26eea378ca30" + + ansi-regex@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + + ansi-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" + + ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + + ansi-styles@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" + dependencies: + color-convert "^1.9.0" + + arg@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arg/-/arg-1.0.1.tgz#892a26d841bd5a64880bbc8f73dd64a705910ca3" + + argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + dependencies: + sprintf-js "~1.0.2" + + array-union@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" + dependencies: + array-uniq "^1.0.1" + + array-uniq@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" + + arrify@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" + + asn1@~0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86" + + assert-plus@1.0.0, assert-plus@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" + + async@1.x, async@^1.4.0: + version "1.5.2" + resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" + + asynckit@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" + + aws-sign2@~0.7.0: + version "0.7.0" + resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" + + aws4@^1.6.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.7.0.tgz#d4d0e9b9dbfca77bf08eeb0a8a471550fe39e289" + + babel-code-frame@^6.22.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" + dependencies: + chalk "^1.1.3" + esutils "^2.0.2" + js-tokens "^3.0.2" + + balanced-match@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + + bcrypt-pbkdf@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d" + dependencies: + tweetnacl "^0.14.3" + + brace-expansion@^1.1.7: + version "1.1.11" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + + browser-stdout@1.3.1: + version "1.3.1" + resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.1.tgz#baa559ee14ced73452229bad7326467c61fabd60" + + buffer-from@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.0.tgz#87fcaa3a298358e0ade6e442cfce840740d1ad04" + + caller-path@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/caller-path/-/caller-path-0.1.0.tgz#94085ef63581ecd3daa92444a8fe94e82577751f" + dependencies: + callsites "^0.2.0" + + callsites@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/callsites/-/callsites-0.2.0.tgz#afab96262910a7f33c19a5775825c69f34e350ca" + + camelcase@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" + + caseless@~0.12.0: + version "0.12.0" + resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" + + center-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" + dependencies: + align-text "^0.1.3" + lazy-cache "^1.0.3" + + chalk@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + + chalk@^2.0.0, chalk@^2.1.0, chalk@^2.3.0: + version "2.4.1" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.1.tgz#18c49ab16a037b6eb0152cc83e3471338215b66e" + dependencies: + ansi-styles "^3.2.1" + escape-string-regexp "^1.0.5" + supports-color "^5.3.0" + + chardet@^0.4.0: + version "0.4.2" + resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.4.2.tgz#b5473b33dc97c424e5d98dc87d55d4d8a29c8bf2" + + circular-json@^0.3.1: + version "0.3.3" + resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.3.tgz#815c99ea84f6809529d2f45791bdf82711352d66" + + cli-cursor@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" + dependencies: + restore-cursor "^2.0.0" + + cli-width@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.2.0.tgz#ff19ede8a9a5e579324147b0c11f0fbcbabed639" + + cliui@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" + dependencies: + center-align "^0.1.1" + right-align "^0.1.1" + wordwrap "0.0.2" + + co@^4.6.0: + version "4.6.0" + resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" + + coffeescript@^2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/coffeescript/-/coffeescript-2.3.1.tgz#a25f69c251d25805c9842e57fc94bfc453ef6aed" + + color-convert@^1.9.0: + version "1.9.2" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.2.tgz#49881b8fba67df12a96bdf3f56c0aab9e7913147" + dependencies: + color-name "1.1.1" + + color-name@1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.1.tgz#4b1415304cf50028ea81643643bd82ea05803689" + + combined-stream@1.0.6, combined-stream@~1.0.5: + version "1.0.6" + resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818" + dependencies: + delayed-stream "~1.0.0" + + commander@2.15.1: + version "2.15.1" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.15.1.tgz#df46e867d0fc2aec66a34662b406a9ccafff5b0f" + + concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + + concat-stream@^1.6.0: + version "1.6.2" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" + dependencies: + buffer-from "^1.0.0" + inherits "^2.0.3" + readable-stream "^2.2.2" + typedarray "^0.0.6" + + core-util-is@1.0.2, core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + + coveralls@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-3.0.1.tgz#12e15914eaa29204e56869a5ece7b9e1492d2ae2" + dependencies: + js-yaml "^3.6.1" + lcov-parse "^0.0.10" + log-driver "^1.2.5" + minimist "^1.2.0" + request "^2.79.0" + + cross-spawn@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" + dependencies: + lru-cache "^4.0.1" + shebang-command "^1.2.0" + which "^1.2.9" + + dashdash@^1.12.0: + version "1.14.1" + resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" + dependencies: + assert-plus "^1.0.0" + + debug@3.1.0, debug@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" + dependencies: + ms "2.0.0" + + decamelize@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + + deep-is@~0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" + + del@^2.0.2: + version "2.2.2" + resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" + dependencies: + globby "^5.0.0" + is-path-cwd "^1.0.0" + is-path-in-cwd "^1.0.0" + object-assign "^4.0.1" + pify "^2.0.0" + pinkie-promise "^2.0.0" + rimraf "^2.2.8" + + delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" + + diff@3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" + + doctrine@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" + dependencies: + esutils "^2.0.2" + + ecc-jsbn@~0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" + dependencies: + jsbn "~0.1.0" + + escape-string-regexp@1.0.5, escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + + escodegen@1.8.x: + version "1.8.1" + resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.8.1.tgz#5a5b53af4693110bebb0867aa3430dd3b70a1018" + dependencies: + esprima "^2.7.1" + estraverse "^1.9.1" + esutils "^2.0.2" + optionator "^0.8.1" + optionalDependencies: + source-map "~0.2.0" + + eslint-scope@^3.7.1: + version "3.7.1" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-3.7.1.tgz#3d63c3edfda02e06e01a452ad88caacc7cdcb6e8" + dependencies: + esrecurse "^4.1.0" + estraverse "^4.1.1" + + eslint-visitor-keys@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#3f3180fb2e291017716acb4c9d6d5b5c34a6a81d" + + eslint@^4.19.1: + version "4.19.1" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-4.19.1.tgz#32d1d653e1d90408854bfb296f076ec7e186a300" + dependencies: + ajv "^5.3.0" + babel-code-frame "^6.22.0" + chalk "^2.1.0" + concat-stream "^1.6.0" + cross-spawn "^5.1.0" + debug "^3.1.0" + doctrine "^2.1.0" + eslint-scope "^3.7.1" + eslint-visitor-keys "^1.0.0" + espree "^3.5.4" + esquery "^1.0.0" + esutils "^2.0.2" + file-entry-cache "^2.0.0" + functional-red-black-tree "^1.0.1" + glob "^7.1.2" + globals "^11.0.1" + ignore "^3.3.3" + imurmurhash "^0.1.4" + inquirer "^3.0.6" + is-resolvable "^1.0.0" + js-yaml "^3.9.1" + json-stable-stringify-without-jsonify "^1.0.1" + levn "^0.3.0" + lodash "^4.17.4" + minimatch "^3.0.2" + mkdirp "^0.5.1" + natural-compare "^1.4.0" + optionator "^0.8.2" + path-is-inside "^1.0.2" + pluralize "^7.0.0" + progress "^2.0.0" + regexpp "^1.0.1" + require-uncached "^1.0.3" + semver "^5.3.0" + strip-ansi "^4.0.0" + strip-json-comments "~2.0.1" + table "4.0.2" + text-table "~0.2.0" + + espree@^3.5.4: + version "3.5.4" + resolved "https://registry.yarnpkg.com/espree/-/espree-3.5.4.tgz#b0f447187c8a8bed944b815a660bddf5deb5d1a7" + dependencies: + acorn "^5.5.0" + acorn-jsx "^3.0.0" + + esprima@2.7.x, esprima@^2.7.1: + version "2.7.3" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" + + esprima@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.0.tgz#4499eddcd1110e0b218bacf2fa7f7f59f55ca804" + + esquery@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.1.tgz#406c51658b1f5991a5f9b62b1dc25b00e3e5c708" + dependencies: + estraverse "^4.0.0" + + esrecurse@^4.1.0: + version "4.2.1" + resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.1.tgz#007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf" + dependencies: + estraverse "^4.1.0" + + estraverse@^1.9.1: + version "1.9.3" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.9.3.tgz#af67f2dc922582415950926091a4005d29c9bb44" + + estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1: + version "4.2.0" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" + + esutils@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" + + extend@~3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444" + + external-editor@^2.0.4: + version "2.2.0" + resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-2.2.0.tgz#045511cfd8d133f3846673d1047c154e214ad3d5" + dependencies: + chardet "^0.4.0" + iconv-lite "^0.4.17" + tmp "^0.0.33" + + extsprintf@1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" + + extsprintf@^1.2.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" + + fast-deep-equal@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614" + + fast-json-stable-stringify@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" + + fast-levenshtein@~2.0.4: + version "2.0.6" + resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" + + figures@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/figures/-/figures-2.0.0.tgz#3ab1a2d2a62c8bfb431a0c94cb797a2fce27c962" + dependencies: + escape-string-regexp "^1.0.5" + + file-entry-cache@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-2.0.0.tgz#c392990c3e684783d838b8c84a45d8a048458361" + dependencies: + flat-cache "^1.2.1" + object-assign "^4.0.1" + + flat-cache@^1.2.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-1.3.0.tgz#d3030b32b38154f4e3b7e9c709f490f7ef97c481" + dependencies: + circular-json "^0.3.1" + del "^2.0.2" + graceful-fs "^4.1.2" + write "^0.2.1" + + forever-agent@~0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" + + form-data@~2.3.1: + version "2.3.2" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099" + dependencies: + asynckit "^0.4.0" + combined-stream "1.0.6" + mime-types "^2.1.12" + + fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + + functional-red-black-tree@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" + + getpass@^0.1.1: + version "0.1.7" + resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" + dependencies: + assert-plus "^1.0.0" + + glob@7.1.2, glob@^7.0.3, glob@^7.0.5, glob@^7.1.2: + version "7.1.2" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + + glob@^5.0.15: + version "5.0.15" + resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" + dependencies: + inflight "^1.0.4" + inherits "2" + minimatch "2 || 3" + once "^1.3.0" + path-is-absolute "^1.0.0" + + globals@^11.0.1: + version "11.5.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-11.5.0.tgz#6bc840de6771173b191f13d3a9c94d441ee92642" + + globby@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" + dependencies: + array-union "^1.0.1" + arrify "^1.0.0" + glob "^7.0.3" + object-assign "^4.0.1" + pify "^2.0.0" + pinkie-promise "^2.0.0" + + graceful-fs@^4.1.2: + version "4.1.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" + + growl@1.10.5: + version "1.10.5" + resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e" + + handlebars@^4.0.1: + version "4.0.11" + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.11.tgz#630a35dfe0294bc281edae6ffc5d329fc7982dcc" + dependencies: + async "^1.4.0" + optimist "^0.6.1" + source-map "^0.4.4" + optionalDependencies: + uglify-js "^2.6" + + har-schema@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" + + har-validator@~5.0.3: + version "5.0.3" + resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd" + dependencies: + ajv "^5.1.0" + har-schema "^2.0.0" + + has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + dependencies: + ansi-regex "^2.0.0" + + has-flag@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" + + has-flag@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" + + he@1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/he/-/he-1.1.1.tgz#93410fd21b009735151f8868c2f271f3427e23fd" + + http-signature@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" + dependencies: + assert-plus "^1.0.0" + jsprim "^1.2.2" + sshpk "^1.7.0" + + iconv-lite@^0.4.17: + version "0.4.23" + resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.23.tgz#297871f63be507adcfbfca715d0cd0eed84e9a63" + dependencies: + safer-buffer ">= 2.1.2 < 3" + + ignore@^3.3.3: + version "3.3.8" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.8.tgz#3f8e9c35d38708a3a7e0e9abb6c73e7ee7707b2b" + + imurmurhash@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" + + inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + dependencies: + once "^1.3.0" + wrappy "1" + + inherits@2, inherits@^2.0.3, inherits@~2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" + + inquirer@^3.0.6: + version "3.3.0" + resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-3.3.0.tgz#9dd2f2ad765dcab1ff0443b491442a20ba227dc9" + dependencies: + ansi-escapes "^3.0.0" + chalk "^2.0.0" + cli-cursor "^2.1.0" + cli-width "^2.0.0" + external-editor "^2.0.4" + figures "^2.0.0" + lodash "^4.3.0" + mute-stream "0.0.7" + run-async "^2.2.0" + rx-lite "^4.0.8" + rx-lite-aggregates "^4.0.8" + string-width "^2.1.0" + strip-ansi "^4.0.0" + through "^2.3.6" + + is-buffer@^1.1.5: + version "1.1.6" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" + + is-fullwidth-code-point@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" + + is-path-cwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d" + + is-path-in-cwd@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz#5ac48b345ef675339bd6c7a48a912110b241cf52" + dependencies: + is-path-inside "^1.0.0" + + is-path-inside@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.1.tgz#8ef5b7de50437a3fdca6b4e865ef7aa55cb48036" + dependencies: + path-is-inside "^1.0.1" + + is-promise@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-2.1.0.tgz#79a2a9ece7f096e80f36d2b2f3bc16c1ff4bf3fa" + + is-resolvable@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.1.0.tgz#fb18f87ce1feb925169c9a407c19318a3206ed88" + + is-typedarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" + + isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + + isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + + isstream@~0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" + + istanbul@^0.4.5: + version "0.4.5" + resolved "https://registry.yarnpkg.com/istanbul/-/istanbul-0.4.5.tgz#65c7d73d4c4da84d4f3ac310b918fb0b8033733b" + dependencies: + abbrev "1.0.x" + async "1.x" + escodegen "1.8.x" + esprima "2.7.x" + glob "^5.0.15" + handlebars "^4.0.1" + js-yaml "3.x" + mkdirp "0.5.x" + nopt "3.x" + once "1.x" + resolve "1.1.x" + supports-color "^3.1.0" + which "^1.1.1" + wordwrap "^1.0.0" + + js-tokens@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" + + js-yaml@3.x, js-yaml@^3.6.1, js-yaml@^3.9.1: + version "3.12.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.12.0.tgz#eaed656ec8344f10f527c6bfa1b6e2244de167d1" + dependencies: + argparse "^1.0.7" + esprima "^4.0.0" + + jsbn@~0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" + + json-schema-traverse@^0.3.0: + version "0.3.1" + resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340" + + json-schema@0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" + + json-stable-stringify-without-jsonify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" + + json-stringify-safe@~5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" + + jsprim@^1.2.2: + version "1.4.1" + resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" + dependencies: + assert-plus "1.0.0" + extsprintf "1.3.0" + json-schema "0.2.3" + verror "1.10.0" + + kind-of@^3.0.2: + version "3.2.2" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" + dependencies: + is-buffer "^1.1.5" + + lazy-cache@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" + + lcov-parse@^0.0.10: + version "0.0.10" + resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3" + + levn@^0.3.0, levn@~0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" + dependencies: + prelude-ls "~1.1.2" + type-check "~0.3.2" + + lodash@^4.17.4, lodash@^4.3.0: + version "4.17.10" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.10.tgz#1b7793cf7259ea38fb3661d4d38b3260af8ae4e7" + + log-driver@^1.2.5: + version "1.2.7" + resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.7.tgz#63b95021f0702fedfa2c9bb0a24e7797d71871d8" + + longest@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" + + lru-cache@^4.0.1: + version "4.1.3" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.3.tgz#a1175cf3496dfc8436c156c334b4955992bce69c" + dependencies: + pseudomap "^1.0.2" + yallist "^2.1.2" + + mime-db@~1.33.0: + version "1.33.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db" + + mime-types@^2.1.12, mime-types@~2.1.17: + version "2.1.18" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8" + dependencies: + mime-db "~1.33.0" + + mimic-fn@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" + + "minimatch@2 || 3", minimatch@3.0.4, minimatch@^3.0.2, minimatch@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + dependencies: + brace-expansion "^1.1.7" + + minimist@0.0.8: + version "0.0.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" + + minimist@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" + + minimist@~0.0.1: + version "0.0.10" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" + + mkdirp@0.5.1, mkdirp@0.5.x, mkdirp@^0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" + dependencies: + minimist "0.0.8" + + mocha@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-5.2.0.tgz#6d8ae508f59167f940f2b5b3c4a612ae50c90ae6" + dependencies: + browser-stdout "1.3.1" + commander "2.15.1" + debug "3.1.0" + diff "3.5.0" + escape-string-regexp "1.0.5" + glob "7.1.2" + growl "1.10.5" + he "1.1.1" + minimatch "3.0.4" + mkdirp "0.5.1" + supports-color "5.4.0" + + ms@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + + mute-stream@0.0.7: + version "0.0.7" + resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.7.tgz#3075ce93bc21b8fab43e1bc4da7e8115ed1e7bab" + + natural-compare@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" + + nopt@3.x: + version "3.0.6" + resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9" + dependencies: + abbrev "1" + + oauth-sign@~0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" + + object-assign@^4.0.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" + + once@1.x, once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + dependencies: + wrappy "1" + + onetime@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" + dependencies: + mimic-fn "^1.0.0" + + optimist@^0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" + dependencies: + minimist "~0.0.1" + wordwrap "~0.0.2" + + optionator@^0.8.1, optionator@^0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" + dependencies: + deep-is "~0.1.3" + fast-levenshtein "~2.0.4" + levn "~0.3.0" + prelude-ls "~1.1.2" + type-check "~0.3.2" + wordwrap "~1.0.0" + + os-tmpdir@~1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + + path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + + path-is-inside@^1.0.1, path-is-inside@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" + + performance-now@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" + + pify@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + + pinkie-promise@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" + dependencies: + pinkie "^2.0.0" + + pinkie@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" + + pluralize@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-7.0.0.tgz#298b89df8b93b0221dbf421ad2b1b1ea23fc6777" + + prelude-ls@~1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" + + process-nextick-args@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" + + progress@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.0.tgz#8a1be366bf8fc23db2bd23f10c6fe920b4389d1f" + + pseudomap@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" + + punycode@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" + + qs@~6.5.1: + version "6.5.2" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36" + + readable-stream@^2.2.2: + version "2.3.6" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.1.1" + util-deprecate "~1.0.1" + + regexpp@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-1.1.0.tgz#0e3516dd0b7904f413d2d4193dce4618c3a689ab" + + repeat-string@^1.5.2: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + + request@^2.79.0: + version "2.87.0" + resolved "https://registry.yarnpkg.com/request/-/request-2.87.0.tgz#32f00235cd08d482b4d0d68db93a829c0ed5756e" + dependencies: + aws-sign2 "~0.7.0" + aws4 "^1.6.0" + caseless "~0.12.0" + combined-stream "~1.0.5" + extend "~3.0.1" + forever-agent "~0.6.1" + form-data "~2.3.1" + har-validator "~5.0.3" + http-signature "~1.2.0" + is-typedarray "~1.0.0" + isstream "~0.1.2" + json-stringify-safe "~5.0.1" + mime-types "~2.1.17" + oauth-sign "~0.8.2" + performance-now "^2.1.0" + qs "~6.5.1" + safe-buffer "^5.1.1" + tough-cookie "~2.3.3" + tunnel-agent "^0.6.0" + uuid "^3.1.0" + + require-uncached@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/require-uncached/-/require-uncached-1.0.3.tgz#4e0d56d6c9662fd31e43011c4b95aa49955421d3" + dependencies: + caller-path "^0.1.0" + resolve-from "^1.0.0" + + resolve-from@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226" + + resolve@1.1.x: + version "1.1.7" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" + + restore-cursor@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" + dependencies: + onetime "^2.0.0" + signal-exit "^3.0.2" + + right-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" + dependencies: + align-text "^0.1.1" + + rimraf@^2.2.8: + version "2.6.2" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36" + dependencies: + glob "^7.0.5" + + run-async@^2.2.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.3.0.tgz#0371ab4ae0bdd720d4166d7dfda64ff7a445a6c0" + dependencies: + is-promise "^2.1.0" + + rx-lite-aggregates@^4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz#753b87a89a11c95467c4ac1626c4efc4e05c67be" + dependencies: + rx-lite "*" + + rx-lite@*, rx-lite@^4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-4.0.8.tgz#0b1e11af8bc44836f04a6407e92da42467b79444" + + safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: + version "5.1.2" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" + + "safer-buffer@>= 2.1.2 < 3", safer-buffer@^2.0.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" + + semver@^5.3.0: + version "5.5.0" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab" + + shebang-command@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" + dependencies: + shebang-regex "^1.0.0" + + shebang-regex@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" + + should-equal@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/should-equal/-/should-equal-2.0.0.tgz#6072cf83047360867e68e98b09d71143d04ee0c3" + dependencies: + should-type "^1.4.0" + + should-format@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/should-format/-/should-format-3.0.3.tgz#9bfc8f74fa39205c53d38c34d717303e277124f1" + dependencies: + should-type "^1.3.0" + should-type-adaptors "^1.0.1" + + should-type-adaptors@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz#401e7f33b5533033944d5cd8bf2b65027792e27a" + dependencies: + should-type "^1.3.0" + should-util "^1.0.0" + + should-type@^1.3.0, should-type@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/should-type/-/should-type-1.4.0.tgz#0756d8ce846dfd09843a6947719dfa0d4cff5cf3" + + should-util@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/should-util/-/should-util-1.0.0.tgz#c98cda374aa6b190df8ba87c9889c2b4db620063" + + should@^13.2.1: + version "13.2.1" + resolved "https://registry.yarnpkg.com/should/-/should-13.2.1.tgz#84e6ebfbb145c79e0ae42307b25b3f62dcaf574e" + dependencies: + should-equal "^2.0.0" + should-format "^3.0.3" + should-type "^1.4.0" + should-type-adaptors "^1.0.1" + should-util "^1.0.0" + + signal-exit@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" + + slice-ansi@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-1.0.0.tgz#044f1a49d8842ff307aad6b505ed178bd950134d" + dependencies: + is-fullwidth-code-point "^2.0.0" + + source-map@^0.4.4: + version "0.4.4" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" + dependencies: + amdefine ">=0.0.4" + + source-map@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.2.0.tgz#dab73fbcfc2ba819b4de03bd6f6eaa48164b3f9d" + dependencies: + amdefine ">=0.0.4" + + source-map@~0.5.1: + version "0.5.7" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + + sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + + sshpk@^1.7.0: + version "1.14.2" + resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.14.2.tgz#c6fc61648a3d9c4e764fd3fcdf4ea105e492ba98" + dependencies: + asn1 "~0.2.3" + assert-plus "^1.0.0" + dashdash "^1.12.0" + getpass "^0.1.1" + safer-buffer "^2.0.2" + optionalDependencies: + bcrypt-pbkdf "^1.0.0" + ecc-jsbn "~0.1.1" + jsbn "~0.1.0" + tweetnacl "~0.14.0" + + string-width@^2.1.0, string-width@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^4.0.0" + + string_decoder@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" + dependencies: + safe-buffer "~5.1.0" + + strip-ansi@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + dependencies: + ansi-regex "^2.0.0" + + strip-ansi@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" + dependencies: + ansi-regex "^3.0.0" + + strip-json-comments@~2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" + + supports-color@5.4.0, supports-color@^5.3.0: + version "5.4.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.4.0.tgz#1c6b337402c2137605efe19f10fec390f6faab54" + dependencies: + has-flag "^3.0.0" + + supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + + supports-color@^3.1.0: + version "3.2.3" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" + dependencies: + has-flag "^1.0.0" + + table@4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/table/-/table-4.0.2.tgz#a33447375391e766ad34d3486e6e2aedc84d2e36" + dependencies: + ajv "^5.2.3" + ajv-keywords "^2.1.0" + chalk "^2.1.0" + lodash "^4.17.4" + slice-ansi "1.0.0" + string-width "^2.1.1" + + text-table@~0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" + + through@^2.3.6: + version "2.3.8" + resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" + + tmp@^0.0.33: + version "0.0.33" + resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" + dependencies: + os-tmpdir "~1.0.2" + + tough-cookie@~2.3.3: + version "2.3.4" + resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655" + dependencies: + punycode "^1.4.1" + + tunnel-agent@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" + dependencies: + safe-buffer "^5.0.1" + + tweetnacl@^0.14.3, tweetnacl@~0.14.0: + version "0.14.5" + resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" + + type-check@~0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" + dependencies: + prelude-ls "~1.1.2" + + typedarray@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + + uglify-js@^2.6: + version "2.8.29" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" + dependencies: + source-map "~0.5.1" + yargs "~3.10.0" + optionalDependencies: + uglify-to-browserify "~1.0.0" + + uglify-to-browserify@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" + + util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + + uuid@^3.1.0: + version "3.2.1" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.2.1.tgz#12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14" + + verror@1.10.0: + version "1.10.0" + resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" + dependencies: + assert-plus "^1.0.0" + core-util-is "1.0.2" + extsprintf "^1.2.0" + + which@^1.1.1, which@^1.2.9: + version "1.3.1" + resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" + dependencies: + isexe "^2.0.0" + + window-size@0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" + + wordwrap@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" + + wordwrap@^1.0.0, wordwrap@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" + + wordwrap@~0.0.2: + version "0.0.3" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" + + wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + + write@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/write/-/write-0.2.1.tgz#5fc03828e264cea3fe91455476f7a3c566cb0757" + dependencies: + mkdirp "^0.5.1" + + yallist@^2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" + + yargs@~3.10.0: + version "3.10.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" + dependencies: + camelcase "^1.0.2" + cliui "^2.1.0" + decamelize "^1.0.0" + window-size "0.1.0" + +Trace: + Error: Command failed. + Exit code: 1 + Command: sh + Arguments: -c mocha --require coffeescript/register + Directory: /src/qix-/node-is-arrayish + Output: + + at ProcessTermError.MessageError (/Users/junon/.yarn/lib/cli.js:186:110) + at new ProcessTermError (/Users/junon/.yarn/lib/cli.js:226:113) + at ChildProcess. (/Users/junon/.yarn/lib/cli.js:30281:17) + at ChildProcess.emit (events.js:127:13) + at maybeClose (internal/child_process.js:933:16) + at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5) diff --git a/build/node_modules/is-stream/index.d.ts b/build/node_modules/is-stream/index.d.ts new file mode 100644 index 00000000..b61027f1 --- /dev/null +++ b/build/node_modules/is-stream/index.d.ts @@ -0,0 +1,80 @@ +/// +import * as stream from 'stream'; + +declare const isStream: { + /** + @returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream(fs.createReadStream('unicorn.png')); + //=> true + + isStream({}); + //=> false + ``` + */ + (stream: unknown): stream is stream.Stream; + + /** + @returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.writable(fs.createWriteStrem('unicorn.txt')); + //=> true + ``` + */ + writable(stream: unknown): stream is stream.Writable; + + /** + @returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.readable(fs.createReadStream('unicorn.png')); + //=> true + ``` + */ + readable(stream: unknown): stream is stream.Readable; + + /** + @returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + + @example + ``` + import {Duplex} from 'stream'; + import isStream = require('is-stream'); + + isStream.duplex(new Duplex()); + //=> true + ``` + */ + duplex(stream: unknown): stream is stream.Duplex; + + /** + @returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + @example + ``` + import * as fs from 'fs'; + import Stringify = require('streaming-json-stringify'); + import isStream = require('is-stream'); + + isStream.transform(Stringify()); + //=> true + ``` + */ + transform(input: unknown): input is stream.Transform; +}; + +export = isStream; diff --git a/build/node_modules/is-stream/index.js b/build/node_modules/is-stream/index.js new file mode 100644 index 00000000..a8d571f1 --- /dev/null +++ b/build/node_modules/is-stream/index.js @@ -0,0 +1,29 @@ +'use strict'; + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function' && + typeof stream._transformState === 'object'; + +module.exports = isStream; diff --git a/build/node_modules/is-stream/license b/build/node_modules/is-stream/license new file mode 100644 index 00000000..e7af2f77 --- /dev/null +++ b/build/node_modules/is-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/build/node_modules/is-stream/package.json b/build/node_modules/is-stream/package.json new file mode 100644 index 00000000..9cd93eb9 --- /dev/null +++ b/build/node_modules/is-stream/package.json @@ -0,0 +1,73 @@ +{ + "_from": "is-stream@^2.0.0", + "_id": "is-stream@2.0.0", + "_inBundle": false, + "_integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", + "_location": "/is-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-stream@^2.0.0", + "name": "is-stream", + "escapedName": "is-stream", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "_shasum": "bde9c32680d6fae04129d6ac9d921ce7815f78e3", + "_spec": "is-stream@^2.0.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/is-stream/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Check if something is a Node.js stream", + "devDependencies": { + "@types/node": "^11.13.6", + "ava": "^1.4.1", + "tempy": "^0.3.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/is-stream#readme", + "keywords": [ + "stream", + "type", + "streams", + "writable", + "readable", + "duplex", + "transform", + "check", + "detect", + "is" + ], + "license": "MIT", + "name": "is-stream", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is-stream.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.0.0" +} diff --git a/build/node_modules/is-stream/readme.md b/build/node_modules/is-stream/readme.md new file mode 100644 index 00000000..fdeadb9f --- /dev/null +++ b/build/node_modules/is-stream/readme.md @@ -0,0 +1,57 @@ +# is-stream [![Build Status](https://travis-ci.org/sindresorhus/is-stream.svg?branch=master)](https://travis-ci.org/sindresorhus/is-stream) + +> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html) + + +## Install + +``` +$ npm install is-stream +``` + + +## Usage + +```js +const fs = require('fs'); +const isStream = require('is-stream'); + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` + + +## API + +### isStream(stream) + +Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +#### isStream.writable(stream) + +Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +#### isStream.readable(stream) + +Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +#### isStream.duplex(stream) + +Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +#### isStream.transform(stream) + +Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + +## Related + +- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/build/node_modules/kuler/.travis.yml b/build/node_modules/kuler/.travis.yml new file mode 100644 index 00000000..5f98e901 --- /dev/null +++ b/build/node_modules/kuler/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "9" + - "8" + - "6" diff --git a/build/node_modules/kuler/LICENSE b/build/node_modules/kuler/LICENSE new file mode 100644 index 00000000..d57b7871 --- /dev/null +++ b/build/node_modules/kuler/LICENSE @@ -0,0 +1,7 @@ +Copyright 2014 Arnout Kazemier + +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. diff --git a/build/node_modules/kuler/README.md b/build/node_modules/kuler/README.md new file mode 100644 index 00000000..d9a4cb8a --- /dev/null +++ b/build/node_modules/kuler/README.md @@ -0,0 +1,40 @@ +# kuler + +Kuler is small and nifty node module that allows you to create terminal based +colors using hex color codes, just like you're used to doing in your CSS. We're +in a modern world now and terminals support more than 16 colors so we are stupid +to not take advantage of this. + +## Installation + +The package is released in the public npm registry and can be installed by +running: + +``` +npm install --save kuler +``` + +## Usage + +To color a string simply pass it the string you want to have colored as first +argument and the color as hex as second argument: + +```js +'use strict'; + +const kuler = require('kuler'); +const str = kuler('foo', '#FF6600'); +``` + +The color code sequence is automatically terminated at the end of the string so +the colors do no bleed to other pieces of text. So doing: + +```js +console.log(kuler('red', '#F00'), 'normal'); +``` + +Will work without any issues. + +## License + +[MIT](LICENSE) diff --git a/build/node_modules/kuler/index.js b/build/node_modules/kuler/index.js new file mode 100644 index 00000000..bff36ae0 --- /dev/null +++ b/build/node_modules/kuler/index.js @@ -0,0 +1,118 @@ +'use strict'; + +/** + * Kuler: Color text using CSS colors + * + * @constructor + * @param {String} text The text that needs to be styled + * @param {String} color Optional color for alternate API. + * @api public + */ +function Kuler(text, color) { + if (color) return (new Kuler(text)).style(color); + if (!(this instanceof Kuler)) return new Kuler(text); + + this.text = text; +} + +/** + * ANSI color codes. + * + * @type {String} + * @private + */ +Kuler.prototype.prefix = '\x1b['; +Kuler.prototype.suffix = 'm'; + +/** + * Parse a hex color string and parse it to it's RGB equiv. + * + * @param {String} color + * @returns {Array} + * @api private + */ +Kuler.prototype.hex = function hex(color) { + color = color[0] === '#' ? color.substring(1) : color; + + // + // Pre-parse for shorthand hex colors. + // + if (color.length === 3) { + color = color.split(''); + + color[5] = color[2]; // F60##0 + color[4] = color[2]; // F60#00 + color[3] = color[1]; // F60600 + color[2] = color[1]; // F66600 + color[1] = color[0]; // FF6600 + + color = color.join(''); + } + + var r = color.substring(0, 2) + , g = color.substring(2, 4) + , b = color.substring(4, 6); + + return [ parseInt(r, 16), parseInt(g, 16), parseInt(b, 16) ]; +}; + +/** + * Transform a 255 RGB value to an RGV code. + * + * @param {Number} r Red color channel. + * @param {Number} g Green color channel. + * @param {Number} b Blue color channel. + * @returns {String} + * @api public + */ +Kuler.prototype.rgb = function rgb(r, g, b) { + var red = r / 255 * 5 + , green = g / 255 * 5 + , blue = b / 255 * 5; + + return this.ansi(red, green, blue); +}; + +/** + * Turns RGB 0-5 values into a single ANSI code. + * + * @param {Number} r Red color channel. + * @param {Number} g Green color channel. + * @param {Number} b Blue color channel. + * @returns {String} + * @api public + */ +Kuler.prototype.ansi = function ansi(r, g, b) { + var red = Math.round(r) + , green = Math.round(g) + , blue = Math.round(b); + + return 16 + (red * 36) + (green * 6) + blue; +}; + +/** + * Marks an end of color sequence. + * + * @returns {String} Reset sequence. + * @api public + */ +Kuler.prototype.reset = function reset() { + return this.prefix +'39;49'+ this.suffix; +}; + +/** + * Colour the terminal using CSS. + * + * @param {String} color The HEX color code. + * @returns {String} the escape code. + * @api public + */ +Kuler.prototype.style = function style(color) { + return this.prefix +'38;5;'+ this.rgb.apply(this, this.hex(color)) + this.suffix + this.text + this.reset(); +}; + + +// +// Expose the actual interface. +// +module.exports = Kuler; diff --git a/build/node_modules/kuler/package.json b/build/node_modules/kuler/package.json new file mode 100644 index 00000000..7743f582 --- /dev/null +++ b/build/node_modules/kuler/package.json @@ -0,0 +1,61 @@ +{ + "_from": "kuler@^2.0.0", + "_id": "kuler@2.0.0", + "_inBundle": false, + "_integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==", + "_location": "/kuler", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "kuler@^2.0.0", + "name": "kuler", + "escapedName": "kuler", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/@dabh/diagnostics" + ], + "_resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "_shasum": "e2c570a3800388fb44407e851531c1d670b061b3", + "_spec": "kuler@^2.0.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/@dabh/diagnostics", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/3rd-Eden/kuler/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Color your terminal using CSS/hex color codes", + "devDependencies": { + "assume": "^2.0.1", + "mocha": "^5.1.1" + }, + "homepage": "https://github.com/3rd-Eden/kuler", + "keywords": [ + "kuler", + "ansi", + "color", + "colour", + "chalk", + "css", + "hex", + "rgb", + "rgv" + ], + "license": "MIT", + "main": "index.js", + "name": "kuler", + "repository": { + "type": "git", + "url": "git+https://github.com/3rd-Eden/kuler.git" + }, + "scripts": { + "test": "mocha test.js" + }, + "version": "2.0.0" +} diff --git a/build/node_modules/kuler/test.js b/build/node_modules/kuler/test.js new file mode 100644 index 00000000..c0b1a5b2 --- /dev/null +++ b/build/node_modules/kuler/test.js @@ -0,0 +1,23 @@ +const { it, describe } = require('mocha'); +const assume = require('assume'); +const kuler = require('./'); + +describe('kuler', function () { + it('renders colors in the terminal', function () { + console.log(' VISUAL INSPECTION'); + console.log(' '+ kuler('red').style('F00')); + console.log(' '+ kuler('black').style('#000')); + console.log(' '+ kuler('white').style('#FFFFFF')); + console.log(' '+ kuler('lime').style('AAFF5B')); + console.log(' '+ kuler('violet').style('#ee82ee')); + console.log(' '+ kuler('purple').style('#800080')); + console.log(' '+ kuler('purple').style('#800080'), 'correctly reset to normal color'); + console.log(' '+ kuler('green', '#008000')); + }); + + describe('#style', function () { + it('has a style method', function () { + assume(kuler('what').style).is.a('function'); + }); + }); +}); diff --git a/build/node_modules/logform/.babelrc b/build/node_modules/logform/.babelrc new file mode 100644 index 00000000..1320b9a3 --- /dev/null +++ b/build/node_modules/logform/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["@babel/preset-env"] +} diff --git a/build/node_modules/logform/.eslintrc b/build/node_modules/logform/.eslintrc new file mode 100644 index 00000000..db77059d --- /dev/null +++ b/build/node_modules/logform/.eslintrc @@ -0,0 +1,7 @@ +{ + "extends": "populist", + "rules": { + "no-undefined": 0, + "strict": 0 + } +} diff --git a/build/node_modules/logform/.gitattributes b/build/node_modules/logform/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/build/node_modules/logform/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/build/node_modules/logform/.travis.yml b/build/node_modules/logform/.travis.yml new file mode 100644 index 00000000..f7e50624 --- /dev/null +++ b/build/node_modules/logform/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +language: node_js +node_js: + - "10" + - "12" + - "14" + +before_install: + - travis_retry npm install + +script: + - npm test + +notifications: + email: + - travis@nodejitsu.com + irc: "irc.freenode.org#nodejitsu" diff --git a/build/node_modules/logform/CHANGELOG.md b/build/node_modules/logform/CHANGELOG.md new file mode 100644 index 00000000..e8401a14 --- /dev/null +++ b/build/node_modules/logform/CHANGELOG.md @@ -0,0 +1,232 @@ +# CHANGELOG + +### 2.2.0 +**2020/06/21** + +- [#90], [#91] Add option for using stable stringify when formatting as JSON. +- [#84] Add replacer for BigInt on JSON formatter. +- [#79] Timestamp format type definitions can accept functions. +- Update dependencies and fix most of the oustanding npm audit notices. + +### 2.1.2 +**2019/01/31** + +- [#74] Remove all internal symbols before invoking `util.inspect`. + - Related to [#31]. + +### 2.1.1 +**2019/01/29** + +- [#71] Bump logform to be consistent with winston. + - Fixes https://github.com/winstonjs/winston/issues/1584 + +### 2.1.0 +**2019/01/07** + +- [#59], [#68], [#69] Add error normalizing format. +- [#65] When MESSAGE symbol has a value and `{ all: true }` is set, colorize the entire serialized message. + +### 2.0.0 +**2018/12/23** + +- **BREAKING** [#57] Try better fix for [winston#1485]. See: + [New `splat` behavior`](#new-splat-behavior) below. +- [#54] Fix typo in `README.md` +- [#55] Strip info[LEVEL] in prettyPrint. Fixes [#31]. +- [#56] Document built-in formats. +- [#64] Add TypeScript definitions for all format options. + Relates to [#9] and [#48]. + +#### New `splat` behavior + +Previously `splat` would have added a `meta` property for any additional +`info[SPLAT]` beyond the expected number of tokens. + +**As of `logform@2.0.0`,** `format.splat` assumes additional splat paramters +(aka "metas") are objects and merges enumerable properties into the `info`. +e.g. + +``` js +const { format } = require('logform'); +const { splat } = format; +const { MESSAGE, LEVEL, SPLAT } = require('triple-beam'); + +console.log( + // Expects two tokens, but three splat parameters provided. + splat().transform({ + level: 'info', + message: 'Let us %s for %j', + [LEVEL]: 'info', + [MESSAGE]: 'Let us %s for %j', + [SPLAT]: ['objects', { label: 'sure' }, { thisIsMeta: 'wut' }] + }) +); + +// logform@1.x behavior: +// Added "meta" property. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// meta: { thisIsMeta: 'wut' }, +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } + +// logform@2.x behavior: +// Enumerable properties assigned into `info`. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// thisIsMeta: 'wut', +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } +``` + +The reason for this change is to be consistent with how `winston` itself +handles `meta` objects in its variable-arity conventions. + +**BE ADVISED** previous "metas" that _were not objects_ will very likely lead +to odd behavior. e.g. + +``` js +const { format } = require('logform'); +const { splat } = format; +const { MESSAGE, LEVEL, SPLAT } = require('triple-beam'); + +console.log( + // Expects two tokens, but three splat parameters provided. + splat().transform({ + level: 'info', + message: 'Let us %s for %j', + [LEVEL]: 'info', + [MESSAGE]: 'Let us %s for %j', + // !!NOTICE!! Additional parameters are a string and an Array + [SPLAT]: ['objects', { label: 'sure' }, 'lol', ['ok', 'why']] + }) +); + +// logform@1.x behavior: +// Added "meta" property. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// meta: ['lol', ['ok', 'why']], +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } + +// logform@2.x behavior: Enumerable properties assigned into `info`. +// **Strings and Arrays only have NUMERIC enumerable properties!** +// +// { '0': 'ok', +// '1': 'why', +// '2': 'l', +// level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } +``` + +### 1.10.0 +**2018/09/17** + +- [#52] Add types field in package.json. +- [#46], [#49] Changes for splat when there are no tokens present and no splat present. +- [#47], [#53] Expose transpiled code for Browser-only scenarios. + +### 1.9.1 +**2018/06/26** + +- [#39] Don't break when there are % placeholders but no values. +- [#42] Only set `meta` when non-zero additional `SPLAT` arguments are + provided. (Fixes [winstonjs/winston#1358]). + +### 1.9.0 +**2018/06/12** + +- [#38] Migrate functionality from winston Logger to splat format. +- [#37] Match expectations from `winston@2.x` for padLevels. Create a correct `Cli` format with initial state. (Fixes [#36]). + +### 1.8.0 +**2018/06/11** + +- [#35] Use `fast-safe-stringify` for perf and to support circular refs. +- [#34] Colorize level symbol. + +### 1.7.0 +**2018/05/24** + +- [#28] Use more es6-features across the board. +- [#30] Fix combine return value. +- [#29] Add metadata function to format namespace. + +### 1.6.0 +**2018/04/25** + +- [#25] Implement padLevels format. +- [#26] Update `dependencies` and add `node@10` to the travis build of the project. +- [#27] Refactor logform to use triple-beam. + +### 1.5.0 +**2018/04/22** + +- [#23], (@ChrisAlderson) Add ms format to support '+N ms' format. Fixes #20. +- [#24], (@aneilbaboo) Fix `webpack` warnings. +- Add `.travis.yml`. + +### 1.4.2 +**2018/04/19** + +- [#22], (@Jasu) Fix compilation on Babel 6. + +### 1.4.1 +**2018/04/06** + +- [#21], (@dabh) Add tsconfig.json. Fixes #19. + +### 1.4.0 +**2018/03/23** + +- [#14] @iamkirkbater Added Initial Metadata Support. +- Correct JSDoc for printf.js. Fixes #10. + +### 1.3.0 +**2018/03/16** + +- [#18] Expose browser.js for rollup and the like. Fixes [#5]. +- [#13] @dabh Use new version of colors. +- [#15] @dabh Add Typescript typings (ported from DefinitelyTyped). +- [#17], [#16] Fix error messages other typos. + +### 1.2.2 +**2017/12/05** + +- [#4], [#11] Fix timestamp and replace `date-fns` with `fecha` (with test cases) [`@ChrisAlderson`]. + +### 1.2.1 +**2017/10/01** + +- [#3] Strip `info.splat` in `format.simple` to avoid double inclusion. + +### 1.2.0 +**2017/09/30** + +- Transition from `info.raw` to `info[Symbol.for('message')]`. +- Finish `README.md` except for full list of all built-in formats. +- 100% coverage for everything except for `{ align, cli, padLevels }`. + +### 1.1.0 +**2017/09/29** + +- [#2] Add baseline expected formats that were previously exposed as options to `common.log` in `winston@2.x` and below. +- [#2] Introduce `format.combine` to remove inconsistency in behavior between `format(fn0)` and `format(fn0, ...moreFns)`. +- [#2] `README.md` now covers all of the basics for `logform`. + +### 1.0.0 +**2017/09/26** + +- Initial release. + +[winstonjs/winston#1358]: https://github.com/winstonjs/winston/issues/1358 diff --git a/build/node_modules/logform/LICENSE b/build/node_modules/logform/LICENSE new file mode 100644 index 00000000..c20a4041 --- /dev/null +++ b/build/node_modules/logform/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Charlie Robbins & the 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. diff --git a/build/node_modules/logform/README.md b/build/node_modules/logform/README.md new file mode 100644 index 00000000..05dfe45f --- /dev/null +++ b/build/node_modules/logform/README.md @@ -0,0 +1,655 @@ +# logform + +A mutable object-based log format designed for chaining & objectMode streams. + +``` js +const { format } = require('logform'); + +const alignedWithColorsAndTime = format.combine( + format.colorize(), + format.timestamp(), + format.align(), + format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`) +); +``` + +- [`info` Objects](#info-objects) +- [Understanding formats](#understanding-formats) + - [Combining formats](#combining-formats) + - [Filtering `info` objects](#filtering-info-objects) +- [Formats](#formats) + - [Align](#align) + - [CLI](#cli) + - [Colorize](#colorize) + - [Combine](#combine) + - [Errors](#errors) + - [JSON](#json) + - [Label](#label) + - [Logstash](#logstash) + - [Metadata](#metadata) + - [PadLevels](#padlevels) + - [PrettyPrint](#prettyprint) + - [Printf](#printf) + - [Simple](#simple) + - [Splat](#splat) + - [Timestamp](#timestamp) + - [Uncolorize](#uncolorize) + +## `info` Objects + +The `info` parameter provided to a given format represents a single log +message. The object itself is mutable. Every `info` must have at least the +`level` and `message` properties: + +``` js +const info = { + level: 'info', // Level of the logging message + message: 'Hey! Log something?' // Descriptive message being logged. +} +``` + +Properties **besides level and message** are considered as "`meta`". i.e.: + +``` js +const { level, message, ...meta } = info; +``` + +Several of the formats in `logform` itself add additional properties: + +| Property | Format added by | Description | +| ----------- | --------------- | ----------- | +| `splat` | `splat()` | String interpolation splat for `%d %s`-style messages. | +| `timestamp` | `timestamp()` | timestamp the message was received. | +| `label` | `label()` | Custom label associated with each message. | +| `ms` | `ms()` | Number of milliseconds since the previous log message. | + +As a consumer you may add whatever properties you wish – _internal state is +maintained by `Symbol` properties:_ + +- `Symbol.for('level')` _**(READ-ONLY)**:_ equal to `level` property. + **Is treated as immutable by all code.** +- `Symbol.for('message'):` complete string message set by "finalizing formats": + - `json` + - `logstash` + - `printf` + - `prettyPrint` + - `simple` +- `Symbol.for('splat')`: additional string interpolation arguments. _Used + exclusively by `splat()` format._ + +These Symbols are stored in another package: `triple-beam` so that all +consumers of `logform` can have the same Symbol reference. i.e.: + +``` js +const { LEVEL, MESSAGE, SPLAT } = require('triple-beam'); + +console.log(LEVEL === Symbol.for('level')); +// true + +console.log(MESSAGE === Symbol.for('message')); +// true + +console.log(SPLAT === Symbol.for('splat')); +// true +``` + +## Understanding formats + +Formats are prototypal objects (i.e. class instances) that define a single method: `transform(info, opts)` and return the mutated `info` + +- `info`: an object representing the log message. +- `opts`: setting specific to the current instance of the format. + +They are expected to return one of two things: + +- **An `info` Object** representing the modified `info` argument. Object references need not be preserved if immutability is preferred. All current built-in formats consider `info` mutable, but [immutablejs] is being considered for future releases. +- **A falsey value** indicating that the `info` argument should be ignored by the caller. (See: [Filtering `info` Objects](#filtering-info-objects)) below. + +`logform.format` is designed to be as simple as possible. To define a new format simple pass it a `transform(info, opts)` function to get a new `Format`. + +The named `Format` returned can be used to create as many copies of the given `Format` as desired: + +``` js +const { format } = require('logform'); + +const volume = format((info, opts) => { + if (opts.yell) { + info.message = info.message.toUpperCase(); + } else if (opts.whisper) { + info.message = info.message.toLowerCase(); + } + + return info; +}); + +// `volume` is now a function that returns instances of the format. +const scream = volume({ yell: true }); +console.dir(scream.transform({ + level: 'info', + message: `sorry for making you YELL in your head!` +}, scream.options)); +// { +// level: 'info' +// message: 'SORRY FOR MAKING YOU YELL IN YOUR HEAD!' +// } + +// `volume` can be used multiple times to create different formats. +const whisper = volume({ whisper: true }); +console.dir(whisper.transform({ + level: 'info', + message: `WHY ARE THEY MAKING US YELL SO MUCH!` +}), whisper.options); +// { +// level: 'info' +// message: 'why are they making us yell so much!' +// } +``` + +### Combining formats + +Any number of formats may be combined into a single format using `format.combine`. Since `format.combine` takes no `opts`, as a convenience it returns pre-created instance of the combined format. + +``` js +const { format } = require('logform'); +const { combine, timestamp, label } = format; + +const labelTimestamp = combine( + label({ label: 'right meow!' }), + timestamp() +); + +const info = labelTimestamp.transform({ + level: 'info', + message: 'What time is the testing at?' +}); + +console.dir(info); +// { level: 'info', +// message: 'What time is the testing at?', +// label: 'right meow!', +// timestamp: '2017-09-30T03:57:26.875Z' } +``` + +### Filtering `info` Objects + +If you wish to filter out a given `info` Object completely then simply return a falsey value. + +``` js +const ignorePrivate = format((info, opts) => { + if (info.private) { return false; } + return info; +}); + +console.dir(ignorePrivate.transform({ + level: 'error', + message: 'Public error to share' +})); +// { level: 'error', message: 'Public error to share' } + +console.dir(ignorePrivate.transform({ + level: 'error', + private: true, + message: 'This is super secret - hide it.' +})); +// false +``` + +Use of `format.combine` will respect any falsey values return and stop evaluation of later formats in the series. For example: + +``` js +const { format } = require('logform'); +const { combine, timestamp, label } = format; + +const willNeverThrow = format.combine( + format(info => { return false })(), // Ignores everything + format(info => { throw new Error('Never reached') })() +); + +console.dir(willNeverThrow.transform({ + level: 'info', + message: 'wow such testing' +})) +``` + +## Formats + +### Align + +The `align` format adds a `\t` delimiter before the message to align it in the same place. + +```js +const { format } = require('logform'); + +const alignFormat = format.align(); + +const info = alignFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', message: '\tmy message' } +``` + +This was previously exposed as `{ align: true }` in `winston < 3.0.0`. + +### CLI + +The `cli` format is a combination of the `colorize` and the `padLevels` formats. It turns a log `info` object into the same format previously available in `winston.cli()` in `winston < 3.0.0`. + +```js +const { format } = require('logform'); +const LEVEL = Symbol.for('level'); + +const cliFormat = format.cli({ colors: { info: 'blue' }}); + +const info = cliFormat.transform({ + [LEVEL]: 'info', + level: 'info', + message: 'my message' +}, { all: true }); + +console.log(info); +// { level: '\u001b[34minfo\u001b[39m', +// message: '\u001b[34m my message\u001b[39m', +// [Symbol(level)]: 'info', +// [Symbol(message)]: +// '\u001b[34minfo\u001b[39m:\u001b[34m my message\u001b[39m' } +``` + +### Colorize + +The `colorize` format adds different colors depending on the log level to the message and/or level. +It accepts the following options: + +* **level**: If set to `true` the color will be applied to the `level`. +* **all**: If set to `true` the color will be applied to the `message` and `level`. +* **message**: If set to `true` the color will be applied to the `message`. +* **colors**: An object containing the colors for the log levels. For example: `{ info: 'blue', error: 'red' }` + +```js +const { format } = require('logform'); +const LEVEL = Symbol.for('level'); + +const colorizeFormat = format.colorize({ colors: { info: 'blue' }}); + +const info = colorizeFormat.transform({ + [LEVEL]: 'info', + level: 'info', + message: 'my message' +}, { all: true }); + +console.log(info); +// { level: '\u001b[34minfo\u001b[39m', +// message: '\u001b[34mmy message\u001b[39m', +// [Symbol(level)]: 'info' } +``` + +This was previously exposed as `{ colorize: true }` to transports in `winston < 3.0.0`. + +### Combine + +The `combine` Format allows to combine multiple formats: + +```js +const { format } = require('logform'); +const { combine, timestamp, json } = format; + +const jsonWithTimestamp = combine( + timestamp(), + json() +); + +const info = jsonWithTimestamp.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// timestamp: '2018-10-02T15:03:14.230Z', +// [Symbol(message)]: +// '{"level":"info","message":"my message","timestamp":"2018-10-02T15:03:14.230Z"}' } +``` + +### Errors + +The `errors` format allows you to pass in an instance of a JavaScript `Error` +directly to the logger. It allows you to specify whether not to include the +stack-trace. + +```js +const { format } = require('logform'); +const { errors } = format; + +const errorsFormat = errors({ stack: true }) + +const info = errorsFormat.transform(new Error('Oh no!')); + +console.log(info); +// Error: Oh no! +// at repl:1:13 +// at ContextifyScript.Script.runInThisContext (vm.js:50:33) +// at REPLServer.defaultEval (repl.js:240:29) +// at bound (domain.js:301:14) +// at REPLServer.runBound [as eval] (domain.js:314:12) +// at REPLServer.onLine (repl.js:468:10) +// at emitOne (events.js:121:20) +// at REPLServer.emit (events.js:211:7) +// at REPLServer.Interface._onLine (readline.js:282:10) +// at REPLServer.Interface._line (readline.js:631:8) +``` + +It will also handle `{ message }` properties as `Error` instances: + +```js +const { format } = require('logform'); +const { errors } = format; + +const errorsFormat = errors({ stack: true }) + +const info = errorsFormat.transform({ + message: new Error('Oh no!') +}); + +console.log(info); +// Error: Oh no! +// at repl:1:13 +// at ContextifyScript.Script.runInThisContext (vm.js:50:33) +// at REPLServer.defaultEval (repl.js:240:29) +// at bound (domain.js:301:14) +// at REPLServer.runBound [as eval] (domain.js:314:12) +// at REPLServer.onLine (repl.js:468:10) +// at emitOne (events.js:121:20) +// at REPLServer.emit (events.js:211:7) +// at REPLServer.Interface._onLine (readline.js:282:10) +// at REPLServer.Interface._line (readline.js:631:8) +``` + +### JSON + +The `json` format uses `fast-safe-stringify` to finalize the message. +It accepts the following options: + +* **replacer**: A function that influences how the `info` is stringified. +* **space**: The number of white space used to format the json. +* **stable**: If set to `true` the objects' attributes will always be stringified in alphabetical order. + +```js +const { format } = require('logform'); + +const jsonFormat = format.json(); + +const info = jsonFormat.transform({ + level: 'info', + message: 'my message', + stable: true, +}); +console.log(info); +// { level: 'info', +// message: 'my message', +// [Symbol(message)]: '{"level":"info","message":"my message"}' } +``` + +This was previously exposed as `{ json: true }` to transports in `winston < 3.0.0`. + +### Label + +The `label` format adds the specified `label` before the message or adds it to the `info` object. +It accepts the following options: + +* **label**: A label to be added before the message. +* **message**: If set to `true` the `label` will be added to `info.message`. If set to `false` the `label` will be added as `info.label`. + +```js +const { format } = require('logform'); + +const labelFormat = format.label(); + +const info = labelFormat.transform({ + level: 'info', + message: 'my message' +}, { label: 'my label', message: true }); + +console.log(info); +// { level: 'info', message: '[my label] my message' } +``` + +This was previously exposed as `{ label: 'my label' }` to transports in `winston < 3.0.0`. + +### Logstash + +The `logstash` Format turns a log `info` object into pure JSON with the appropriate logstash options. + +```js +const { format } = require('logform'); +const { logstash, combine, timestamp } = format; + +const logstashFormat = combine( + timestamp(), + logstash() +); + +const info = logstashFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// [Symbol(message)]: +// '{"@message":"my message","@timestamp":"2018-10-02T11:04:52.915Z","@fields":{"level":"info"}}' } +``` + +This was previously exposed as `{ logstash: true }` to transports in `winston < 3.0.0`. + +### Metadata + +The `metadata` format adds a metadata object to collect extraneous data, similar to the metadata object in winston 2.x. +It accepts the following options: + +* **key**: The name of the key used for the metadata object. Defaults to `metadata`. +* **fillExcept**: An array of keys that should not be added to the metadata object. +* **fillWith**: An array of keys that will be added to the metadata object. + +```js +const { format } = require('logform'); + +const metadataFormat = format.metadata(); + +const info = metadataFormat.transform({ + level: 'info', + message: 'my message', + meta: 42 +}); + +console.log(info); +// { level: 'info', message: 'my message', metadata: { meta: 42 } } +``` + +### PadLevels + +The `padLevels` format pads levels to be the same length. + +```js +const { format } = require('logform'); +const LEVEL = Symbol.for('level'); + +const padLevelsFormat = format.padLevels(); + +const info = padLevelsFormat.transform({ + [LEVEL]: 'info', + message: 'my message' +}); + +console.log(info); +// { message: ' my message', [Symbol(level)]: 'info' } +``` + +This was previously exposed as `{ padLevels: true }` to transports in `winston < 3.0.0`. + +### PrettyPrint + +The `prettyPrint` format finalizes the message using `util.inspect`. +It accepts the following options: + +* **depth**: A `number` that specifies the maximum depth of the `info` object being stringified by `util.inspect`. Defaults to `2`. +* **colorize**: Colorizes the message if set to `true`. Defaults to `false`. + +The `prettyPrint` format should not be used in production because it may impact performance negatively and block the event loop. + +> **NOTE:** the `LEVEL`, `MESSAGE`, and `SPLAT` symbols are stripped from the +> output message _by design._ + +This was previously exposed as `{ prettyPrint: true }` to transports in `winston < 3.0.0`. + +```js +const { format } = require('logform'); + +const prettyPrintFormat = format.prettyPrint(); + +const info = prettyPrintFormat.transform({ + [LEVEL]: 'info', + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// [Symbol(level)]: 'info', +// [Symbol(message)]: '{ level: \'info\', message: \'my message\' }' } +``` + +### Printf + +The `printf` format allows to create a custom logging format: + +```js +const { format } = require('logform'); + +const myFormat = format.printf((info) => { + return `${info.level} ${info.message}`; +}) + +const info = myFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// [Symbol(message)]: 'info my message' } +``` + +### Simple + +The `simple` format finalizes the `info` object using the format: `level: message stringifiedRest`. +```js +const { format } = require('logform'); +const MESSAGE = Symbol.for('message'); + +const simpleFormat = format.simple(); + +const info = simpleFormat.transform({ + level: 'info', + message: 'my message', + number: 123 +}); +console.log(info[MESSAGE]); +// info: my message {number:123} +``` + +### Splat + +The `splat` format transforms the message by using `util.format` to complete any `info.message` provided it has string interpolation tokens. + +```js +const { format } = require('logform'); + +const splatFormat = format.splat(); + +const info = splatFormat.transform({ + level: 'info', + message: 'my message %s', + splat: ['test'] +}); + +console.log(info); +// { level: 'info', message: 'my message test', splat: [ 'test' ] } +``` + +Any additional splat parameters beyond those needed for the `%` tokens +(aka "metas") are assumed to be objects. Their enumerable properties are +merged into the `info`. + +```js +const { format } = require('logform'); + +const splatFormat = format.splat(); + +const info = splatFormat.transform({ + level: 'info', + message: 'my message %s', + splat: ['test', { thisIsMeta: true }] +}); + +console.log(info); +// { level: 'info', +// message: 'my message test', +// thisIsMeta: true, +// splat: [ 'test' ] } +``` + +This was previously exposed implicitly in `winston < 3.0.0`. + +### Timestamp + +The `timestamp` format adds a timestamp to the info. +It accepts the following options: + +* **format**: Either the format as a string accepted by the [fecha](https://github.com/taylorhakes/fecha) module or a function that returns a formatted date. If no format is provided `new Date().toISOString()` will be used. +* **alias**: The name of an alias for the timestamp property, that will be added to the `info` object. + +```js +const { format } = require('logform'); + +const timestampFormat = format.timestamp(); + +const info = timestampFormat.transform({ + level: 'info', + message: 'my message' +}); + +console.log(info); +// { level: 'info', +// message: 'my message', +// timestamp: '2018-10-02T11:47:02.682Z' } +``` + +It was previously available in `winston < 3.0.0` as `{ timestamp: true }` and `{ timestamp: function:String }`. + + +### Uncolorize + +The `uncolorize` format strips colors from `info` objects. +It accepts the following options: + +* **level**: Disables the uncolorize format for `info.level` if set to `false`. +* **message**: Disables the uncolorize format for `info.message` if set to `false`. +* **raw**: Disables the uncolorize format for `info[MESSAGE]` if set to `false`. + +This was previously exposed as `{ stripColors: true }` to transports in `winston < 3.0.0`. + +## Tests + +Tests are written with `mocha`, `assume`, and `nyc`. They can be run with `npm`: + +``` +npm test +``` + +##### LICENSE: MIT +##### AUTHOR: [Charlie Robbins](https://github.com/indexzero) diff --git a/build/node_modules/logform/align.js b/build/node_modules/logform/align.js new file mode 100644 index 00000000..358514b0 --- /dev/null +++ b/build/node_modules/logform/align.js @@ -0,0 +1,14 @@ +'use strict'; + +const format = require('./format'); + +/* + * function align (info) + * Returns a new instance of the align Format which adds a `\t` + * delimiter before the message to properly align it in the same place. + * It was previously { align: true } in winston < 3.0.0 + */ +module.exports = format(info => { + info.message = `\t${info.message}`; + return info; +}); diff --git a/build/node_modules/logform/browser.js b/build/node_modules/logform/browser.js new file mode 100644 index 00000000..a675b82b --- /dev/null +++ b/build/node_modules/logform/browser.js @@ -0,0 +1,36 @@ +'use strict'; + +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ +const format = exports.format = require('././format'); + +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ +exports.levels = require('././levels'); + +// +// Setup all transports as eager-loaded exports +// so that they are static for the bundlers. +// +Object.defineProperty(format, 'align', { value: require('./align') }); +Object.defineProperty(format, 'cli', { value: require('./cli') }); +Object.defineProperty(format, 'combine', { value: require('./combine') }); +Object.defineProperty(format, 'colorize', { value: require('./colorize') }); +Object.defineProperty(format, 'json', { value: require('./json') }); +Object.defineProperty(format, 'label', { value: require('./label') }); +Object.defineProperty(format, 'logstash', { value: require('./logstash') }); +Object.defineProperty(format, 'metadata', { value: require('./metadata') }); +Object.defineProperty(format, 'padLevels', { value: require('./pad-levels') }); +Object.defineProperty(format, 'prettyPrint', { value: require('./pretty-print') }); +Object.defineProperty(format, 'printf', { value: require('./printf') }); +Object.defineProperty(format, 'simple', { value: require('./simple') }); +Object.defineProperty(format, 'splat', { value: require('./splat') }); +Object.defineProperty(format, 'timestamp', { value: require('./timestamp') }); +Object.defineProperty(format, 'uncolorize', { value: require('./uncolorize') }); diff --git a/build/node_modules/logform/cli.js b/build/node_modules/logform/cli.js new file mode 100644 index 00000000..2337e47b --- /dev/null +++ b/build/node_modules/logform/cli.js @@ -0,0 +1,52 @@ +'use strict'; + +const { Colorizer } = require('./colorize'); +const { Padder } = require('./pad-levels'); +const { configs, MESSAGE } = require('triple-beam'); + + +/** + * Cli format class that handles initial state for a a separate + * Colorizer and Padder instance. + */ +class CliFormat { + constructor(opts = {}) { + if (!opts.levels) { + opts.levels = configs.npm.levels; + } + + this.colorizer = new Colorizer(opts); + this.padder = new Padder(opts); + this.options = opts; + } + + /* + * function transform (info, opts) + * Attempts to both: + * 1. Pad the { level } + * 2. Colorize the { level, message } + * of the given `logform` info object depending on the `opts`. + */ + transform(info, opts) { + this.colorizer.transform( + this.padder.transform(info, opts), + opts + ); + + info[MESSAGE] = `${info.level}:${info.message}`; + return info; + } +} + +/* + * function cli (opts) + * Returns a new instance of the CLI format that turns a log + * `info` object into the same format previously available + * in `winston.cli()` in `winston < 3.0.0`. + */ +module.exports = opts => new CliFormat(opts); + +// +// Attach the CliFormat for registration purposes +// +module.exports.Format = CliFormat; diff --git a/build/node_modules/logform/colorize.js b/build/node_modules/logform/colorize.js new file mode 100644 index 00000000..ba6860e2 --- /dev/null +++ b/build/node_modules/logform/colorize.js @@ -0,0 +1,122 @@ +'use strict'; + +const colors = require('colors/safe'); +const { LEVEL, MESSAGE } = require('triple-beam'); + +// +// Fix colors not appearing in non-tty environments +// +colors.enabled = true; + +/** + * @property {RegExp} hasSpace + * Simple regex to check for presence of spaces. + */ +const hasSpace = /\s+/; + +/* + * Colorizer format. Wraps the `level` and/or `message` properties + * of the `info` objects with ANSI color codes based on a few options. + */ +class Colorizer { + constructor(opts = {}) { + if (opts.colors) { + this.addColors(opts.colors); + } + + this.options = opts; + } + + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + static addColors(clrs) { + const nextColors = Object.keys(clrs).reduce((acc, level) => { + acc[level] = hasSpace.test(clrs[level]) + ? clrs[level].split(hasSpace) + : clrs[level]; + + return acc; + }, {}); + + Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors); + return Colorizer.allColors; + } + + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + addColors(clrs) { + return Colorizer.addColors(clrs); + } + + /* + * function colorize (lookup, level, message) + * Performs multi-step colorization using colors/safe + */ + colorize(lookup, level, message) { + if (typeof message === 'undefined') { + message = level; + } + + // + // If the color for the level is just a string + // then attempt to colorize the message with it. + // + if (!Array.isArray(Colorizer.allColors[lookup])) { + return colors[Colorizer.allColors[lookup]](message); + } + + // + // If it is an Array then iterate over that Array, applying + // the colors function for each item. + // + for (let i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) { + message = colors[Colorizer.allColors[lookup][i]](message); + } + + return message; + } + + /* + * function transform (info, opts) + * Attempts to colorize the { level, message } of the given + * `logform` info object. + */ + transform(info, opts) { + if (opts.all && typeof info[MESSAGE] === 'string') { + info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); + } + + if (opts.level || opts.all || !opts.message) { + info.level = this.colorize(info[LEVEL], info.level); + } + + if (opts.all || opts.message) { + info.message = this.colorize(info[LEVEL], info.level, info.message); + } + + return info; + } +} + +/* + * function colorize (info) + * Returns a new instance of the colorize Format that applies + * level colors to `info` objects. This was previously exposed + * as { colorize: true } to transports in `winston < 3.0.0`. + */ +module.exports = opts => new Colorizer(opts); + +// +// Attach the Colorizer for registration purposes +// +module.exports.Colorizer + = module.exports.Format + = Colorizer; diff --git a/build/node_modules/logform/combine.js b/build/node_modules/logform/combine.js new file mode 100644 index 00000000..975482c9 --- /dev/null +++ b/build/node_modules/logform/combine.js @@ -0,0 +1,66 @@ +'use strict'; + +const format = require('./format'); + +/* + * function cascade(formats) + * Returns a function that invokes the `._format` function in-order + * for the specified set of `formats`. In this manner we say that Formats + * are "pipe-like", but not a pure pumpify implementation. Since there is no back + * pressure we can remove all of the "readable" plumbing in Node streams. + */ +function cascade(formats) { + if (!formats.every(isValidFormat)) { + return; + } + + return info => { + let obj = info; + for (let i = 0; i < formats.length; i++) { + obj = formats[i].transform(obj, formats[i].options); + if (!obj) { + return false; + } + } + + return obj; + }; +} + +/* + * function isValidFormat(format) + * If the format does not define a `transform` function throw an error + * with more detailed usage. + */ +function isValidFormat(fmt) { + if (typeof fmt.transform !== 'function') { + throw new Error([ + 'No transform function found on format. Did you create a format instance?', + 'const myFormat = format(formatFn);', + 'const instance = myFormat();' + ].join('\n')); + } + + return true; +} + +/* + * function combine (info) + * Returns a new instance of the combine Format which combines the specified + * formats into a new format. This is similar to a pipe-chain in transform streams. + * We choose to combine the prototypes this way because there is no back pressure in + * an in-memory transform chain. + */ +module.exports = (...formats) => { + const combinedFormat = format(cascade(formats)); + const instance = combinedFormat(); + instance.Format = combinedFormat.Format; + return instance; +}; + +// +// Export the cascade method for use in cli and other +// combined formats that should not be assumed to be +// singletons. +// +module.exports.cascade = cascade; diff --git a/build/node_modules/logform/dist/align.js b/build/node_modules/logform/dist/align.js new file mode 100644 index 00000000..b4378e22 --- /dev/null +++ b/build/node_modules/logform/dist/align.js @@ -0,0 +1,15 @@ +'use strict'; + +var format = require('./format'); +/* + * function align (info) + * Returns a new instance of the align Format which adds a `\t` + * delimiter before the message to properly align it in the same place. + * It was previously { align: true } in winston < 3.0.0 + */ + + +module.exports = format(function (info) { + info.message = "\t".concat(info.message); + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/browser.js b/build/node_modules/logform/dist/browser.js new file mode 100644 index 00000000..b89538b8 --- /dev/null +++ b/build/node_modules/logform/dist/browser.js @@ -0,0 +1,66 @@ +'use strict'; +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ + +var format = exports.format = require('././format'); +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ + + +exports.levels = require('././levels'); // +// Setup all transports as eager-loaded exports +// so that they are static for the bundlers. +// + +Object.defineProperty(format, 'align', { + value: require('./align') +}); +Object.defineProperty(format, 'cli', { + value: require('./cli') +}); +Object.defineProperty(format, 'combine', { + value: require('./combine') +}); +Object.defineProperty(format, 'colorize', { + value: require('./colorize') +}); +Object.defineProperty(format, 'json', { + value: require('./json') +}); +Object.defineProperty(format, 'label', { + value: require('./label') +}); +Object.defineProperty(format, 'logstash', { + value: require('./logstash') +}); +Object.defineProperty(format, 'metadata', { + value: require('./metadata') +}); +Object.defineProperty(format, 'padLevels', { + value: require('./pad-levels') +}); +Object.defineProperty(format, 'prettyPrint', { + value: require('./pretty-print') +}); +Object.defineProperty(format, 'printf', { + value: require('./printf') +}); +Object.defineProperty(format, 'simple', { + value: require('./simple') +}); +Object.defineProperty(format, 'splat', { + value: require('./splat') +}); +Object.defineProperty(format, 'timestamp', { + value: require('./timestamp') +}); +Object.defineProperty(format, 'uncolorize', { + value: require('./uncolorize') +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/cli.js b/build/node_modules/logform/dist/cli.js new file mode 100644 index 00000000..7a0306d8 --- /dev/null +++ b/build/node_modules/logform/dist/cli.js @@ -0,0 +1,73 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('./colorize'), + Colorizer = _require.Colorizer; + +var _require2 = require('./pad-levels'), + Padder = _require2.Padder; + +var _require3 = require('triple-beam'), + configs = _require3.configs, + MESSAGE = _require3.MESSAGE; +/** + * Cli format class that handles initial state for a a separate + * Colorizer and Padder instance. + */ + + +var CliFormat = /*#__PURE__*/function () { + function CliFormat() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, CliFormat); + + if (!opts.levels) { + opts.levels = configs.npm.levels; + } + + this.colorizer = new Colorizer(opts); + this.padder = new Padder(opts); + this.options = opts; + } + /* + * function transform (info, opts) + * Attempts to both: + * 1. Pad the { level } + * 2. Colorize the { level, message } + * of the given `logform` info object depending on the `opts`. + */ + + + _createClass(CliFormat, [{ + key: "transform", + value: function transform(info, opts) { + this.colorizer.transform(this.padder.transform(info, opts), opts); + info[MESSAGE] = "".concat(info.level, ":").concat(info.message); + return info; + } + }]); + + return CliFormat; +}(); +/* + * function cli (opts) + * Returns a new instance of the CLI format that turns a log + * `info` object into the same format previously available + * in `winston.cli()` in `winston < 3.0.0`. + */ + + +module.exports = function (opts) { + return new CliFormat(opts); +}; // +// Attach the CliFormat for registration purposes +// + + +module.exports.Format = CliFormat; \ No newline at end of file diff --git a/build/node_modules/logform/dist/colorize.js b/build/node_modules/logform/dist/colorize.js new file mode 100644 index 00000000..79b9ef30 --- /dev/null +++ b/build/node_modules/logform/dist/colorize.js @@ -0,0 +1,144 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var colors = require('colors/safe'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; // +// Fix colors not appearing in non-tty environments +// + + +colors.enabled = true; +/** + * @property {RegExp} hasSpace + * Simple regex to check for presence of spaces. + */ + +var hasSpace = /\s+/; +/* + * Colorizer format. Wraps the `level` and/or `message` properties + * of the `info` objects with ANSI color codes based on a few options. + */ + +var Colorizer = /*#__PURE__*/function () { + function Colorizer() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, Colorizer); + + if (opts.colors) { + this.addColors(opts.colors); + } + + this.options = opts; + } + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + + + _createClass(Colorizer, [{ + key: "addColors", + + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + value: function addColors(clrs) { + return Colorizer.addColors(clrs); + } + /* + * function colorize (lookup, level, message) + * Performs multi-step colorization using colors/safe + */ + + }, { + key: "colorize", + value: function colorize(lookup, level, message) { + if (typeof message === 'undefined') { + message = level; + } // + // If the color for the level is just a string + // then attempt to colorize the message with it. + // + + + if (!Array.isArray(Colorizer.allColors[lookup])) { + return colors[Colorizer.allColors[lookup]](message); + } // + // If it is an Array then iterate over that Array, applying + // the colors function for each item. + // + + + for (var i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) { + message = colors[Colorizer.allColors[lookup][i]](message); + } + + return message; + } + /* + * function transform (info, opts) + * Attempts to colorize the { level, message } of the given + * `logform` info object. + */ + + }, { + key: "transform", + value: function transform(info, opts) { + if (opts.all && typeof info[MESSAGE] === 'string') { + info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); + } + + if (opts.level || opts.all || !opts.message) { + info.level = this.colorize(info[LEVEL], info.level); + } + + if (opts.all || opts.message) { + info.message = this.colorize(info[LEVEL], info.level, info.message); + } + + return info; + } + }], [{ + key: "addColors", + value: function addColors(clrs) { + var nextColors = Object.keys(clrs).reduce(function (acc, level) { + acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level]; + return acc; + }, {}); + Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors); + return Colorizer.allColors; + } + }]); + + return Colorizer; +}(); +/* + * function colorize (info) + * Returns a new instance of the colorize Format that applies + * level colors to `info` objects. This was previously exposed + * as { colorize: true } to transports in `winston < 3.0.0`. + */ + + +module.exports = function (opts) { + return new Colorizer(opts); +}; // +// Attach the Colorizer for registration purposes +// + + +module.exports.Colorizer = module.exports.Format = Colorizer; \ No newline at end of file diff --git a/build/node_modules/logform/dist/combine.js b/build/node_modules/logform/dist/combine.js new file mode 100644 index 00000000..7b386e6e --- /dev/null +++ b/build/node_modules/logform/dist/combine.js @@ -0,0 +1,71 @@ +'use strict'; + +var format = require('./format'); +/* + * function cascade(formats) + * Returns a function that invokes the `._format` function in-order + * for the specified set of `formats`. In this manner we say that Formats + * are "pipe-like", but not a pure pumpify implementation. Since there is no back + * pressure we can remove all of the "readable" plumbing in Node streams. + */ + + +function cascade(formats) { + if (!formats.every(isValidFormat)) { + return; + } + + return function (info) { + var obj = info; + + for (var i = 0; i < formats.length; i++) { + obj = formats[i].transform(obj, formats[i].options); + + if (!obj) { + return false; + } + } + + return obj; + }; +} +/* + * function isValidFormat(format) + * If the format does not define a `transform` function throw an error + * with more detailed usage. + */ + + +function isValidFormat(fmt) { + if (typeof fmt.transform !== 'function') { + throw new Error(['No transform function found on format. Did you create a format instance?', 'const myFormat = format(formatFn);', 'const instance = myFormat();'].join('\n')); + } + + return true; +} +/* + * function combine (info) + * Returns a new instance of the combine Format which combines the specified + * formats into a new format. This is similar to a pipe-chain in transform streams. + * We choose to combine the prototypes this way because there is no back pressure in + * an in-memory transform chain. + */ + + +module.exports = function () { + for (var _len = arguments.length, formats = new Array(_len), _key = 0; _key < _len; _key++) { + formats[_key] = arguments[_key]; + } + + var combinedFormat = format(cascade(formats)); + var instance = combinedFormat(); + instance.Format = combinedFormat.Format; + return instance; +}; // +// Export the cascade method for use in cli and other +// combined formats that should not be assumed to be +// singletons. +// + + +module.exports.cascade = cascade; \ No newline at end of file diff --git a/build/node_modules/logform/dist/errors.js b/build/node_modules/logform/dist/errors.js new file mode 100644 index 00000000..d26b71bb --- /dev/null +++ b/build/node_modules/logform/dist/errors.js @@ -0,0 +1,43 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var format = require('./format'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; +/* + * function errors (info) + * If the `message` property of the `info` object is an instance of `Error`, + * replace the `Error` object its own `message` property. + * + * Optionally, the Error's `stack` property can also be appended to the `info` object. + */ + + +module.exports = format(function (einfo, _ref) { + var stack = _ref.stack; + + if (einfo instanceof Error) { + var _Object$assign; + + var info = Object.assign({}, einfo, (_Object$assign = { + level: einfo.level + }, _defineProperty(_Object$assign, LEVEL, einfo[LEVEL] || einfo.level), _defineProperty(_Object$assign, "message", einfo.message), _defineProperty(_Object$assign, MESSAGE, einfo[MESSAGE] || einfo.message), _Object$assign)); + if (stack) info.stack = einfo.stack; + return info; + } + + if (!(einfo.message instanceof Error)) return einfo; // Assign all enumerable properties and the + // message property from the error provided. + + Object.assign(einfo, einfo.message); + var err = einfo.message; + einfo.message = err.message; + einfo[MESSAGE] = err.message; // Assign the stack if requested. + + if (stack) einfo.stack = err.stack; + return einfo; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/format.js b/build/node_modules/logform/dist/format.js new file mode 100644 index 00000000..97eedff9 --- /dev/null +++ b/build/node_modules/logform/dist/format.js @@ -0,0 +1,87 @@ +'use strict'; +/* + * Displays a helpful message and the source of + * the format when it is invalid. + */ + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } + +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var InvalidFormatError = /*#__PURE__*/function (_Error) { + _inherits(InvalidFormatError, _Error); + + var _super = _createSuper(InvalidFormatError); + + function InvalidFormatError(formatFn) { + var _this; + + _classCallCheck(this, InvalidFormatError); + + _this = _super.call(this, "Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ".concat(formatFn.toString().split('\n')[0], "\n")); + Error.captureStackTrace(_assertThisInitialized(_this), InvalidFormatError); + return _this; + } + + return InvalidFormatError; +}( /*#__PURE__*/_wrapNativeSuper(Error)); +/* + * function format (formatFn) + * Returns a create function for the `formatFn`. + */ + + +module.exports = function (formatFn) { + if (formatFn.length > 2) { + throw new InvalidFormatError(formatFn); + } + /* + * function Format (options) + * Base prototype which calls a `_format` + * function and pushes the result. + */ + + + function Format() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + this.options = options; + } + + Format.prototype.transform = formatFn; // + // Create a function which returns new instances of + // FormatWrap for simple syntax like: + // + // require('winston').formats.json(); + // + + function createFormatWrap(opts) { + return new Format(opts); + } // + // Expose the FormatWrap through the create function + // for testability. + // + + + createFormatWrap.Format = Format; + return createFormatWrap; +}; \ No newline at end of file diff --git a/build/node_modules/logform/dist/index.js b/build/node_modules/logform/dist/index.js new file mode 100644 index 00000000..cb652fd9 --- /dev/null +++ b/build/node_modules/logform/dist/index.js @@ -0,0 +1,54 @@ +'use strict'; +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ + +var format = exports.format = require('./format'); +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ + + +exports.levels = require('./levels'); +/* + * @api private + * method {function} exposeFormat + * Exposes a sub-format on the main format object + * as a lazy-loaded getter. + */ + +function exposeFormat(name, path) { + path = path || name; + Object.defineProperty(format, name, { + get: function get() { + return require("./".concat(path, ".js")); + }, + configurable: true + }); +} // +// Setup all transports as lazy-loaded getters. +// + + +exposeFormat('align'); +exposeFormat('errors'); +exposeFormat('cli'); +exposeFormat('combine'); +exposeFormat('colorize'); +exposeFormat('json'); +exposeFormat('label'); +exposeFormat('logstash'); +exposeFormat('metadata'); +exposeFormat('ms'); +exposeFormat('padLevels', 'pad-levels'); +exposeFormat('prettyPrint', 'pretty-print'); +exposeFormat('printf'); +exposeFormat('simple'); +exposeFormat('splat'); +exposeFormat('timestamp'); +exposeFormat('uncolorize'); \ No newline at end of file diff --git a/build/node_modules/logform/dist/json.js b/build/node_modules/logform/dist/json.js new file mode 100644 index 00000000..06685ef6 --- /dev/null +++ b/build/node_modules/logform/dist/json.js @@ -0,0 +1,33 @@ +'use strict'; + +var format = require('./format'); + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +var jsonStringify = require('fast-safe-stringify'); +/* + * function replacer (key, value) + * Handles proper stringification of Buffer and bigint output. + */ + + +function replacer(key, value) { + if (value instanceof Buffer) return value.toString('base64'); // eslint-disable-next-line valid-typeof + + if (typeof value === 'bigint') return value.toString(); + return value; +} +/* + * function json (info) + * Returns a new instance of the JSON format that turns a log `info` + * object into pure JSON. This was previously exposed as { json: true } + * to transports in `winston < 3.0.0`. + */ + + +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + info[MESSAGE] = (opts.stable ? jsonStringify.stableStringify : jsonStringify)(info, opts.replacer || replacer, opts.space); + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/label.js b/build/node_modules/logform/dist/label.js new file mode 100644 index 00000000..6e28f592 --- /dev/null +++ b/build/node_modules/logform/dist/label.js @@ -0,0 +1,20 @@ +'use strict'; + +var format = require('./format'); +/* + * function label (info) + * Returns a new instance of the label Format which adds the specified + * `opts.label` before the message. This was previously exposed as + * { label: 'my label' } to transports in `winston < 3.0.0`. + */ + + +module.exports = format(function (info, opts) { + if (opts.message) { + info.message = "[".concat(opts.label, "] ").concat(info.message); + return info; + } + + info.label = opts.label; + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/levels.js b/build/node_modules/logform/dist/levels.js new file mode 100644 index 00000000..277ec3f4 --- /dev/null +++ b/build/node_modules/logform/dist/levels.js @@ -0,0 +1,14 @@ +'use strict'; + +var _require = require('./colorize'), + Colorizer = _require.Colorizer; +/* + * Simple method to register colors with a simpler require + * path within the module. + */ + + +module.exports = function (config) { + Colorizer.addColors(config.colors || config); + return config; +}; \ No newline at end of file diff --git a/build/node_modules/logform/dist/logstash.js b/build/node_modules/logform/dist/logstash.js new file mode 100644 index 00000000..4a20983c --- /dev/null +++ b/build/node_modules/logform/dist/logstash.js @@ -0,0 +1,34 @@ +'use strict'; + +var format = require('./format'); + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +var jsonStringify = require('fast-safe-stringify'); +/* + * function logstash (info) + * Returns a new instance of the LogStash Format that turns a + * log `info` object into pure JSON with the appropriate logstash + * options. This was previously exposed as { logstash: true } + * to transports in `winston < 3.0.0`. + */ + + +module.exports = format(function (info) { + var logstash = {}; + + if (info.message) { + logstash['@message'] = info.message; + delete info.message; + } + + if (info.timestamp) { + logstash['@timestamp'] = info.timestamp; + delete info.timestamp; + } + + logstash['@fields'] = info; + info[MESSAGE] = jsonStringify(logstash); + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/metadata.js b/build/node_modules/logform/dist/metadata.js new file mode 100644 index 00000000..cfabc3ba --- /dev/null +++ b/build/node_modules/logform/dist/metadata.js @@ -0,0 +1,64 @@ +'use strict'; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var format = require('./format'); + +function fillExcept(info, fillExceptKeys, metadataKey) { + var savedKeys = fillExceptKeys.reduce(function (acc, key) { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + var metadata = Object.keys(info).reduce(function (acc, key) { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + Object.assign(info, savedKeys, _defineProperty({}, metadataKey, metadata)); + return info; +} + +function fillWith(info, fillWithKeys, metadataKey) { + info[metadataKey] = fillWithKeys.reduce(function (acc, key) { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + return info; +} +/** + * Adds in a "metadata" object to collect extraneous data, similar to the metadata + * object in winston 2.x. + */ + + +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var metadataKey = 'metadata'; + + if (opts.key) { + metadataKey = opts.key; + } + + var fillExceptKeys = []; + + if (!opts.fillExcept && !opts.fillWith) { + fillExceptKeys.push('level'); + fillExceptKeys.push('message'); + } + + if (opts.fillExcept) { + fillExceptKeys = opts.fillExcept; + } + + if (fillExceptKeys.length > 0) { + return fillExcept(info, fillExceptKeys, metadataKey); + } + + if (opts.fillWith) { + return fillWith(info, opts.fillWith, metadataKey); + } + + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/ms.js b/build/node_modules/logform/dist/ms.js new file mode 100644 index 00000000..ba300328 --- /dev/null +++ b/build/node_modules/logform/dist/ms.js @@ -0,0 +1,21 @@ +'use strict'; + +var _this = void 0; + +var format = require('./format'); + +var ms = require('ms'); +/* + * function ms (info) + * Returns an `info` with a `ms` property. The `ms` property holds the Value + * of the time difference between two calls in milliseconds. + */ + + +module.exports = format(function (info) { + var curr = +new Date(); + _this.diff = curr - (_this.prevTime || curr); + _this.prevTime = curr; + info.ms = "+".concat(ms(_this.diff)); + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/pad-levels.js b/build/node_modules/logform/dist/pad-levels.js new file mode 100644 index 00000000..2f039ebc --- /dev/null +++ b/build/node_modules/logform/dist/pad-levels.js @@ -0,0 +1,127 @@ +/* eslint no-unused-vars: 0 */ +'use strict'; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('triple-beam'), + configs = _require.configs, + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; + +var Padder = /*#__PURE__*/function () { + function Padder() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + levels: configs.npm.levels + }; + + _classCallCheck(this, Padder); + + this.paddings = Padder.paddingForLevels(opts.levels, opts.filler); + this.options = opts; + } + /** + * Returns the maximum length of keys in the specified `levels` Object. + * @param {Object} levels Set of all levels to calculate longest level against. + * @returns {Number} Maximum length of the longest level string. + */ + + + _createClass(Padder, [{ + key: "transform", + + /** + * Prepends the padding onto the `message` based on the `LEVEL` of + * the `info`. This is based on the behavior of `winston@2` which also + * prepended the level onto the message. + * + * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 + * + * @param {Info} info Logform info object + * @param {Object} opts Options passed along to this instance. + * @returns {Info} Modified logform info object. + */ + value: function transform(info, opts) { + info.message = "".concat(this.paddings[info[LEVEL]]).concat(info.message); + + if (info[MESSAGE]) { + info[MESSAGE] = "".concat(this.paddings[info[LEVEL]]).concat(info[MESSAGE]); + } + + return info; + } + }], [{ + key: "getLongestLevel", + value: function getLongestLevel(levels) { + var lvls = Object.keys(levels).map(function (level) { + return level.length; + }); + return Math.max.apply(Math, _toConsumableArray(lvls)); + } + /** + * Returns the padding for the specified `level` assuming that the + * maximum length of all levels it's associated with is `maxLength`. + * @param {String} level Level to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @param {Number} maxLength Length of the longest level + * @returns {String} Padding string for the `level` + */ + + }, { + key: "paddingForLevel", + value: function paddingForLevel(level, filler, maxLength) { + var targetLen = maxLength + 1 - level.length; + var rep = Math.floor(targetLen / filler.length); + var padding = "".concat(filler).concat(filler.repeat(rep)); + return padding.slice(0, targetLen); + } + /** + * Returns an object with the string paddings for the given `levels` + * using the specified `filler`. + * @param {Object} levels Set of all levels to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @returns {Object} Mapping of level to desired padding. + */ + + }, { + key: "paddingForLevels", + value: function paddingForLevels(levels) { + var filler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' '; + var maxLength = Padder.getLongestLevel(levels); + return Object.keys(levels).reduce(function (acc, level) { + acc[level] = Padder.paddingForLevel(level, filler, maxLength); + return acc; + }, {}); + } + }]); + + return Padder; +}(); +/* + * function padLevels (info) + * Returns a new instance of the padLevels Format which pads + * levels to be the same length. This was previously exposed as + * { padLevels: true } to transports in `winston < 3.0.0`. + */ + + +module.exports = function (opts) { + return new Padder(opts); +}; + +module.exports.Padder = module.exports.Format = Padder; \ No newline at end of file diff --git a/build/node_modules/logform/dist/pretty-print.js b/build/node_modules/logform/dist/pretty-print.js new file mode 100644 index 00000000..0d5ed70b --- /dev/null +++ b/build/node_modules/logform/dist/pretty-print.js @@ -0,0 +1,34 @@ +'use strict'; + +var inspect = require('util').inspect; + +var format = require('./format'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE, + SPLAT = _require.SPLAT; +/* + * function prettyPrint (info) + * Returns a new instance of the prettyPrint Format that "prettyPrint" + * serializes `info` objects. This was previously exposed as + * { prettyPrint: true } to transports in `winston < 3.0.0`. + */ + + +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + // + // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they + // are internal, we remove them before util.inspect so they + // are not printed. + // + var stripped = Object.assign({}, info); // Remark (indexzero): update this technique in April 2019 + // when node@6 is EOL + + delete stripped[LEVEL]; + delete stripped[MESSAGE]; + delete stripped[SPLAT]; + info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/printf.js b/build/node_modules/logform/dist/printf.js new file mode 100644 index 00000000..fcfa11db --- /dev/null +++ b/build/node_modules/logform/dist/printf.js @@ -0,0 +1,41 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +var Printf = /*#__PURE__*/function () { + function Printf(templateFn) { + _classCallCheck(this, Printf); + + this.template = templateFn; + } + + _createClass(Printf, [{ + key: "transform", + value: function transform(info) { + info[MESSAGE] = this.template(info); + return info; + } + }]); + + return Printf; +}(); +/* + * function printf (templateFn) + * Returns a new instance of the printf Format that creates an + * intermediate prototype to store the template string-based formatter + * function. + */ + + +module.exports = function (opts) { + return new Printf(opts); +}; + +module.exports.Printf = module.exports.Format = Printf; \ No newline at end of file diff --git a/build/node_modules/logform/dist/simple.js b/build/node_modules/logform/dist/simple.js new file mode 100644 index 00000000..52f12cd3 --- /dev/null +++ b/build/node_modules/logform/dist/simple.js @@ -0,0 +1,37 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +var format = require('./format'); + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +var jsonStringify = require('fast-safe-stringify'); +/* + * function simple (info) + * Returns a new instance of the simple format TransformStream + * which writes a simple representation of logs. + * + * const { level, message, splat, ...rest } = info; + * + * ${level}: ${message} if rest is empty + * ${level}: ${message} ${JSON.stringify(rest)} otherwise + */ + + +module.exports = format(function (info) { + var stringifiedRest = jsonStringify(Object.assign({}, info, { + level: undefined, + message: undefined, + splat: undefined + })); + var padding = info.padding && info.padding[info.level] || ''; + + if (stringifiedRest !== '{}') { + info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message, " ").concat(stringifiedRest); + } else { + info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message); + } + + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/splat.js b/build/node_modules/logform/dist/splat.js new file mode 100644 index 00000000..0ab6bc38 --- /dev/null +++ b/build/node_modules/logform/dist/splat.js @@ -0,0 +1,159 @@ +'use strict'; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var util = require('util'); + +var _require = require('triple-beam'), + SPLAT = _require.SPLAT; +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ + + +var formatRegExp = /%[scdjifoO%]/g; +/** + * Captures the number of escaped % signs in a format string (i.e. %s strings). + * @type {RegExp} + */ + +var escapedPercent = /%%/g; + +var Splatter = /*#__PURE__*/function () { + function Splatter(opts) { + _classCallCheck(this, Splatter); + + this.options = opts; + } + /** + * Check to see if tokens <= splat.length, assign { splat, meta } into the + * `info` accordingly, and write to this instance. + * + * @param {Info} info Logform info message. + * @param {String[]} tokens Set of string interpolation tokens. + * @returns {Info} Modified info message + * @private + */ + + + _createClass(Splatter, [{ + key: "_splat", + value: function _splat(info, tokens) { + var msg = info.message; + var splat = info[SPLAT] || info.splat || []; + var percents = msg.match(escapedPercent); + var escapes = percents && percents.length || 0; // The expected splat is the number of tokens minus the number of escapes + // e.g. + // - { expectedSplat: 3 } '%d %s %j' + // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j' + // + // Any "meta" will be arugments in addition to the expected splat size + // regardless of type. e.g. + // + // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true }); + // would result in splat of four (4), but only three (3) are expected. Therefore: + // + // extraSplat = 3 - 4 = -1 + // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1); + // splat = [100, 'wow', { such: 'js' }] + + var expectedSplat = tokens.length - escapes; + var extraSplat = expectedSplat - splat.length; + var metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + + var metalen = metas.length; + + if (metalen) { + for (var i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + + info.message = util.format.apply(util, [msg].concat(_toConsumableArray(splat))); + return info; + } + /** + * Transforms the `info` message by using `util.format` to complete + * any `info.message` provided it has string interpolation tokens. + * If no tokens exist then `info` is immutable. + * + * @param {Info} info Logform info message. + * @param {Object} opts Options for this instance. + * @returns {Info} Modified info message + */ + + }, { + key: "transform", + value: function transform(info) { + var msg = info.message; + var splat = info[SPLAT] || info.splat; // No need to process anything if splat is undefined + + if (!splat || !splat.length) { + return info; + } // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + + + var tokens = msg && msg.match && msg.match(formatRegExp); // This condition will take care of inputs with info[SPLAT] + // but no tokens present + + if (!tokens && (splat || splat.length)) { + var metas = splat.length > 1 ? splat.splice(0) : splat; // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + + var metalen = metas.length; + + if (metalen) { + for (var i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + + return info; + } + + if (tokens) { + return this._splat(info, tokens); + } + + return info; + } + }]); + + return Splatter; +}(); +/* + * function splat (info) + * Returns a new instance of the splat format TransformStream + * which performs string interpolation from `info` objects. This was + * previously exposed implicitly in `winston < 3.0.0`. + */ + + +module.exports = function (opts) { + return new Splatter(opts); +}; \ No newline at end of file diff --git a/build/node_modules/logform/dist/timestamp.js b/build/node_modules/logform/dist/timestamp.js new file mode 100644 index 00000000..fe88b52f --- /dev/null +++ b/build/node_modules/logform/dist/timestamp.js @@ -0,0 +1,32 @@ +'use strict'; + +var fecha = require('fecha'); + +var format = require('./format'); +/* + * function timestamp (info) + * Returns a new instance of the timestamp Format which adds a timestamp + * to the info. It was previously available in winston < 3.0.0 as: + * + * - { timestamp: true } // `new Date.toISOString()` + * - { timestamp: function:String } // Value returned by `timestamp()` + */ + + +module.exports = format(function (info) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (opts.format) { + info.timestamp = typeof opts.format === 'function' ? opts.format() : fecha.format(new Date(), opts.format); + } + + if (!info.timestamp) { + info.timestamp = new Date().toISOString(); + } + + if (opts.alias) { + info[opts.alias] = info.timestamp; + } + + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/dist/uncolorize.js b/build/node_modules/logform/dist/uncolorize.js new file mode 100644 index 00000000..0dc47c26 --- /dev/null +++ b/build/node_modules/logform/dist/uncolorize.js @@ -0,0 +1,31 @@ +'use strict'; + +var colors = require('colors/safe'); + +var format = require('./format'); + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; +/* + * function uncolorize (info) + * Returns a new instance of the uncolorize Format that strips colors + * from `info` objects. This was previously exposed as { stripColors: true } + * to transports in `winston < 3.0.0`. + */ + + +module.exports = format(function (info, opts) { + if (opts.level !== false) { + info.level = colors.strip(info.level); + } + + if (opts.message !== false) { + info.message = colors.strip(info.message); + } + + if (opts.raw !== false && info[MESSAGE]) { + info[MESSAGE] = colors.strip(info[MESSAGE]); + } + + return info; +}); \ No newline at end of file diff --git a/build/node_modules/logform/errors.js b/build/node_modules/logform/errors.js new file mode 100644 index 00000000..b7a09757 --- /dev/null +++ b/build/node_modules/logform/errors.js @@ -0,0 +1,39 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +const format = require('./format'); +const { LEVEL, MESSAGE } = require('triple-beam'); + +/* + * function errors (info) + * If the `message` property of the `info` object is an instance of `Error`, + * replace the `Error` object its own `message` property. + * + * Optionally, the Error's `stack` property can also be appended to the `info` object. + */ +module.exports = format((einfo, { stack }) => { + if (einfo instanceof Error) { + const info = Object.assign({}, einfo, { + level: einfo.level, + [LEVEL]: einfo[LEVEL] || einfo.level, + message: einfo.message, + [MESSAGE]: einfo[MESSAGE] || einfo.message + }); + + if (stack) info.stack = einfo.stack; + return info; + } + + if (!(einfo.message instanceof Error)) return einfo; + + // Assign all enumerable properties and the + // message property from the error provided. + Object.assign(einfo, einfo.message); + const err = einfo.message; + einfo.message = err.message; + einfo[MESSAGE] = err.message; + + // Assign the stack if requested. + if (stack) einfo.stack = err.stack; + return einfo; +}); diff --git a/build/node_modules/logform/examples/combine.js b/build/node_modules/logform/examples/combine.js new file mode 100644 index 00000000..71a70bec --- /dev/null +++ b/build/node_modules/logform/examples/combine.js @@ -0,0 +1,14 @@ +const { format } = require('../'); +const { combine, timestamp, label } = format; + +const labelTimestamp = combine( + label({ label: 'right meow!' }), + timestamp() +); + +const info = labelTimestamp.transform({ + level: 'info', + message: 'What time is the testing at?' +}); + +console.dir(info); diff --git a/build/node_modules/logform/examples/filter.js b/build/node_modules/logform/examples/filter.js new file mode 100644 index 00000000..89a16788 --- /dev/null +++ b/build/node_modules/logform/examples/filter.js @@ -0,0 +1,30 @@ +/* eslint no-unused-vars: 0 */ + +const { format } = require('../'); +const { combine, timestamp, label } = format; + +const ignorePrivate = format((info, opts) => { + if (info.private) { return false; } + return info; +})(); + +console.dir(ignorePrivate.transform({ + level: 'error', + message: 'Public error to share' +})); + +console.dir(ignorePrivate.transform({ + level: 'error', + private: true, + message: 'This is super secret - hide it.' +})); + +const willNeverThrow = format.combine( + format(info => { return false; })(), // Ignores everything + format(info => { throw new Error('Never reached'); })() +); + +console.dir(willNeverThrow.transform({ + level: 'info', + message: 'wow such testing' +})); diff --git a/build/node_modules/logform/examples/invalid.js b/build/node_modules/logform/examples/invalid.js new file mode 100644 index 00000000..bd2b4087 --- /dev/null +++ b/build/node_modules/logform/examples/invalid.js @@ -0,0 +1,6 @@ +/* eslint no-unused-vars: 0 */ +const { format } = require('../'); + +const invalid = format(function invalid(just, too, many, args) { + return just; +}); diff --git a/build/node_modules/logform/examples/metadata.js b/build/node_modules/logform/examples/metadata.js new file mode 100644 index 00000000..4846f74f --- /dev/null +++ b/build/node_modules/logform/examples/metadata.js @@ -0,0 +1,78 @@ +const { format } = require('../'); +const { combine, json, metadata, timestamp } = format; + +// Default Functionality (no options passed) +const defaultFormatter = combine( + timestamp(), + metadata(), + json() +); + +const defaultMessage = defaultFormatter.transform({ + level: 'info', + message: 'This should be a message.', + application: 'Microsoft Office', + store: 'Big Box Store', + purchaseAmount: '9.99' +}); + +console.dir(defaultMessage); + + +// Fill all keys into metadata except those provided +const formattedLogger = combine( + timestamp(), + metadata({ fillExcept: ['message', 'level', 'timestamp'] }), + json() +); + +const fillExceptMessage = formattedLogger.transform({ + level: 'info', + message: 'This should have attached metadata', + category: 'movies', + subCategory: 'action' +}); + +console.dir(fillExceptMessage); + + +// Fill only the keys provided into the object, and also give it a different key +const customMetadataLogger = combine( + timestamp(), + metadata({ fillWith: ['publisher', 'author', 'book'], key: 'bookInfo' }), + json() +); + +const fillWithMessage = customMetadataLogger.transform({ + level: 'debug', + message: 'This message should be outside of the bookInfo object', + publisher: 'Lorem Press', + author: 'Albert Einstein', + book: '4D Chess for Dummies', + label: 'myCustomLabel' +}); + +console.dir(fillWithMessage); + +// Demonstrates Metadata 'chaining' to combine multiple datapoints. +const chainedMetadata = combine( + timestamp(), + metadata({ fillWith: ['publisher', 'author', 'book'], key: 'bookInfo' }), + metadata({ fillWith: ['purchasePrice', 'purchaseDate', 'transactionId'], key: 'transactionInfo' }), + metadata({ fillExcept: ['level', 'message', 'label', 'timestamp'] }), + json() +); + +const chainedMessage = chainedMetadata.transform({ + level: 'debug', + message: 'This message should be outside of the bookInfo object', + publisher: 'Lorem Press', + author: 'Albert Einstein', + book: '4D Chess for Dummies', + label: 'myCustomLabel', + purchasePrice: '9.99', + purchaseDate: '2.10.2018', + transactionId: '123ABC' +}); + +console.dir(chainedMessage); diff --git a/build/node_modules/logform/examples/padLevels.js b/build/node_modules/logform/examples/padLevels.js new file mode 100644 index 00000000..568964da --- /dev/null +++ b/build/node_modules/logform/examples/padLevels.js @@ -0,0 +1,39 @@ +const { format } = require('../'); +const { combine, padLevels, simple } = format; + +const { MESSAGE } = require('triple-beam'); + +const paddedFormat = combine( + padLevels({ + // Uncomment for a custom filler for the padding, defaults to ' '. + // filler: 'foo', + // Levels has to be defined, same as `winston.createLoggers({ levels })`. + levels: { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 + } + }), + simple() +); + +const info = paddedFormat.transform({ + level: 'info', + message: 'This is an info level message.' +}); +const error = paddedFormat.transform({ + level: 'error', + message: 'This is an error level message.' +}); +const verbose = paddedFormat.transform({ + level: 'verbose', + message: 'This is a verbose level message.' +}); + +console.dir(info[MESSAGE]); +console.dir(error[MESSAGE]); +console.dir(verbose[MESSAGE]); diff --git a/build/node_modules/logform/examples/volume.js b/build/node_modules/logform/examples/volume.js new file mode 100644 index 00000000..cce36f60 --- /dev/null +++ b/build/node_modules/logform/examples/volume.js @@ -0,0 +1,25 @@ +const { format } = require('../'); + +const volume = format((info, opts) => { + if (opts.yell) { + info.message = info.message.toUpperCase(); + } else if (opts.whisper) { + info.message = info.message.toLowerCase(); + } + + return info; +}); + +// `volume` is now a function that returns instances of the format. +const scream = volume({ yell: true }); +console.dir(scream.transform({ + level: 'info', + message: `sorry for making you YELL in your head!` +}, scream.options)); + +// `volume` can be used multiple times to create different formats. +const whisper = volume({ whisper: true }); +console.dir(whisper.transform({ + level: 'info', + message: `WHY ARE THEY MAKING US YELL SO MUCH!` +}, whisper.options)); diff --git a/build/node_modules/logform/format.js b/build/node_modules/logform/format.js new file mode 100644 index 00000000..c2294b6c --- /dev/null +++ b/build/node_modules/logform/format.js @@ -0,0 +1,52 @@ +'use strict'; + +/* + * Displays a helpful message and the source of + * the format when it is invalid. + */ +class InvalidFormatError extends Error { + constructor(formatFn) { + super(`Format functions must be synchronous taking a two arguments: (info, opts) +Found: ${formatFn.toString().split('\n')[0]}\n`); + + Error.captureStackTrace(this, InvalidFormatError); + } +} + +/* + * function format (formatFn) + * Returns a create function for the `formatFn`. + */ +module.exports = formatFn => { + if (formatFn.length > 2) { + throw new InvalidFormatError(formatFn); + } + + /* + * function Format (options) + * Base prototype which calls a `_format` + * function and pushes the result. + */ + function Format(options = {}) { + this.options = options; + } + + Format.prototype.transform = formatFn; + + // + // Create a function which returns new instances of + // FormatWrap for simple syntax like: + // + // require('winston').formats.json(); + // + function createFormatWrap(opts) { + return new Format(opts); + } + + // + // Expose the FormatWrap through the create function + // for testability. + // + createFormatWrap.Format = Format; + return createFormatWrap; +}; diff --git a/build/node_modules/logform/index.d.ts b/build/node_modules/logform/index.d.ts new file mode 100644 index 00000000..e37a6e80 --- /dev/null +++ b/build/node_modules/logform/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for logform 1.2 +// Project: https://github.com/winstonjs/logform +// Definitions by: DABH +// Definitions: https://github.com/winstonjs/logform +// TypeScript Version: 2.2 + +export interface TransformableInfo { + level: string; + message: string; + [key: string]: any; +} + +export type TransformFunction = (info: TransformableInfo, opts?: any) => TransformableInfo | boolean; +export type Colors = { [key: string]: string | string[] }; // tslint:disable-line interface-over-type-literal +export type FormatWrap = (opts?: any) => Format; + +export class Format { + constructor(opts?: object); + + options?: object; + transform: TransformFunction; +} + +export class Colorizer extends Format { + constructor(opts?: object); + + createColorize: (opts?: object) => Colorizer; + addColors: (colors: Colors) => Colors; + colorize: (level: string, message: string) => string; +} + +export function format(transform: TransformFunction): FormatWrap; + +export function levels(config: object): object; + +export namespace format { + function align(): Format; + function cli(opts?: CliOptions): Format; + function colorize(opts?: ColorizeOptions): Colorizer; + function combine(...formats: Format[]): Format; + function errors(opts?: object): Format; + function json(opts?: JsonOptions): Format; + function label(opts?: LabelOptions): Format; + function logstash(): Format; + function metadata(opts?: MetadataOptions): Format; + function ms(): Format; + function padLevels(opts?: PadLevelsOptions): Format; + function prettyPrint(opts?: PrettyPrintOptions): Format; + function printf(templateFunction: (info: TransformableInfo) => string): Format; + function simple(): Format; + function splat(): Format; + function timestamp(opts?: TimestampOptions): Format; + function uncolorize(opts?: UncolorizeOptions): Format; +} + +export interface CliOptions extends ColorizeOptions, PadLevelsOptions {} + +export interface ColorizeOptions { + /** + * If set to `true` the color will be applied to the `level`. + */ + level?: boolean; + /** + * If set to `true` the color will be applied to the `message` and `level`. + */ + all?: boolean; + /** + * If set to `true` the color will be applied to the `message`. + */ + message?: boolean; + /** + * An object containing the colors for the log levels. For example: `{ info: 'blue', error: 'red' }`. + */ + colors?: Record; +} + +export interface JsonOptions { + /** + * A function that influences how the `info` is stringified. + */ + replacer?: (this: any, key: string, value: any) => any; + /** + * The number of white space used to format the json. + */ + space?: number; +} + +export interface LabelOptions { + /** + * A label to be added before the message. + */ + label?: string; + /** + * If set to `true` the `label` will be added to `info.message`. If set to `false` the `label` + * will be added as `info.label`. + */ + message?: boolean; +} + +export interface MetadataOptions { + /** + * The name of the key used for the metadata object. Defaults to `metadata`. + */ + key?: string; + /** + * An array of keys that should not be added to the metadata object. + */ + fillExcept?: string[]; + /** + * An array of keys that will be added to the metadata object. + */ + fillWith?: string[]; +} + +export interface PadLevelsOptions { + /** + * Log levels. Defaults to `configs.npm.levels` from [triple-beam](https://github.com/winstonjs/triple-beam) + * module. + */ + levels?: Record; +} + +export interface PrettyPrintOptions { + /** + * A `number` that specifies the maximum depth of the `info` object being stringified by + * `util.inspect`. Defaults to `2`. + */ + depth?: number; + /** + * Colorizes the message if set to `true`. Defaults to `false`. + */ + colorize?: boolean; +} + +export interface TimestampOptions { + /** + * Either the format as a string accepted by the [fecha](https://github.com/taylorhakes/fecha) + * module or a function that returns a formatted date. If no format is provided `new + * Date().toISOString()` will be used. + */ + format?: string | (() => string); + /** + * The name of an alias for the timestamp property, that will be added to the `info` object. + */ + alias?: string; +} + +export interface UncolorizeOptions { + /** + * Disables the uncolorize format for `info.level` if set to `false`. + */ + level?: boolean; + /** + * Disables the uncolorize format for `info.message` if set to `false`. + */ + message?: boolean; + /** + * Disables the uncolorize format for `info[MESSAGE]` if set to `false`. + */ + raw?: boolean; +} diff --git a/build/node_modules/logform/index.js b/build/node_modules/logform/index.js new file mode 100644 index 00000000..2e663aa7 --- /dev/null +++ b/build/node_modules/logform/index.js @@ -0,0 +1,53 @@ +'use strict'; + +/* + * @api public + * @property {function} format + * Both the construction method and set of exposed + * formats. + */ +const format = exports.format = require('./format'); + +/* + * @api public + * @method {function} levels + * Registers the specified levels with logform. + */ +exports.levels = require('./levels'); + +/* + * @api private + * method {function} exposeFormat + * Exposes a sub-format on the main format object + * as a lazy-loaded getter. + */ +function exposeFormat(name, path) { + path = path || name; + Object.defineProperty(format, name, { + get() { + return require(`./${path}.js`); + }, + configurable: true + }); +} + +// +// Setup all transports as lazy-loaded getters. +// +exposeFormat('align'); +exposeFormat('errors'); +exposeFormat('cli'); +exposeFormat('combine'); +exposeFormat('colorize'); +exposeFormat('json'); +exposeFormat('label'); +exposeFormat('logstash'); +exposeFormat('metadata'); +exposeFormat('ms'); +exposeFormat('padLevels', 'pad-levels'); +exposeFormat('prettyPrint', 'pretty-print'); +exposeFormat('printf'); +exposeFormat('simple'); +exposeFormat('splat'); +exposeFormat('timestamp'); +exposeFormat('uncolorize'); diff --git a/build/node_modules/logform/json.js b/build/node_modules/logform/json.js new file mode 100644 index 00000000..dac12a68 --- /dev/null +++ b/build/node_modules/logform/json.js @@ -0,0 +1,30 @@ +'use strict'; + +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); +const jsonStringify = require('fast-safe-stringify'); + +/* + * function replacer (key, value) + * Handles proper stringification of Buffer and bigint output. + */ +function replacer(key, value) { + if (value instanceof Buffer) + return value.toString('base64'); + // eslint-disable-next-line valid-typeof + if (typeof value === 'bigint') + return value.toString(); + return value; +} + +/* + * function json (info) + * Returns a new instance of the JSON format that turns a log `info` + * object into pure JSON. This was previously exposed as { json: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts = {}) => { + info[MESSAGE] = (opts.stable ? jsonStringify.stableStringify + : jsonStringify)(info, opts.replacer || replacer, opts.space); + return info; +}); diff --git a/build/node_modules/logform/label.js b/build/node_modules/logform/label.js new file mode 100644 index 00000000..e6127fd0 --- /dev/null +++ b/build/node_modules/logform/label.js @@ -0,0 +1,19 @@ +'use strict'; + +const format = require('./format'); + +/* + * function label (info) + * Returns a new instance of the label Format which adds the specified + * `opts.label` before the message. This was previously exposed as + * { label: 'my label' } to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts) => { + if (opts.message) { + info.message = `[${opts.label}] ${info.message}`; + return info; + } + + info.label = opts.label; + return info; +}); diff --git a/build/node_modules/logform/levels.js b/build/node_modules/logform/levels.js new file mode 100644 index 00000000..5a7345cc --- /dev/null +++ b/build/node_modules/logform/levels.js @@ -0,0 +1,12 @@ +'use strict'; + +const { Colorizer } = require('./colorize'); + +/* + * Simple method to register colors with a simpler require + * path within the module. + */ +module.exports = config => { + Colorizer.addColors(config.colors || config); + return config; +}; diff --git a/build/node_modules/logform/logstash.js b/build/node_modules/logform/logstash.js new file mode 100644 index 00000000..aac8492f --- /dev/null +++ b/build/node_modules/logform/logstash.js @@ -0,0 +1,29 @@ +'use strict'; + +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); +const jsonStringify = require('fast-safe-stringify'); + +/* + * function logstash (info) + * Returns a new instance of the LogStash Format that turns a + * log `info` object into pure JSON with the appropriate logstash + * options. This was previously exposed as { logstash: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format(info => { + const logstash = {}; + if (info.message) { + logstash['@message'] = info.message; + delete info.message; + } + + if (info.timestamp) { + logstash['@timestamp'] = info.timestamp; + delete info.timestamp; + } + + logstash['@fields'] = info; + info[MESSAGE] = jsonStringify(logstash); + return info; +}); diff --git a/build/node_modules/logform/metadata.js b/build/node_modules/logform/metadata.js new file mode 100644 index 00000000..dc796db2 --- /dev/null +++ b/build/node_modules/logform/metadata.js @@ -0,0 +1,61 @@ +'use strict'; + +const format = require('./format'); + +function fillExcept(info, fillExceptKeys, metadataKey) { + const savedKeys = fillExceptKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + const metadata = Object.keys(info).reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + + Object.assign(info, savedKeys, { + [metadataKey]: metadata + }); + return info; +} + +function fillWith(info, fillWithKeys, metadataKey) { + info[metadataKey] = fillWithKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + return info; +} + +/** + * Adds in a "metadata" object to collect extraneous data, similar to the metadata + * object in winston 2.x. + */ +module.exports = format((info, opts = {}) => { + let metadataKey = 'metadata'; + if (opts.key) { + metadataKey = opts.key; + } + + let fillExceptKeys = []; + if (!opts.fillExcept && !opts.fillWith) { + fillExceptKeys.push('level'); + fillExceptKeys.push('message'); + } + + if (opts.fillExcept) { + fillExceptKeys = opts.fillExcept; + } + + if (fillExceptKeys.length > 0) { + return fillExcept(info, fillExceptKeys, metadataKey); + } + + if (opts.fillWith) { + return fillWith(info, opts.fillWith, metadataKey); + } + + return info; +}); diff --git a/build/node_modules/logform/ms.js b/build/node_modules/logform/ms.js new file mode 100644 index 00000000..88830faa --- /dev/null +++ b/build/node_modules/logform/ms.js @@ -0,0 +1,18 @@ +'use strict'; + +const format = require('./format'); +const ms = require('ms'); + +/* + * function ms (info) + * Returns an `info` with a `ms` property. The `ms` property holds the Value + * of the time difference between two calls in milliseconds. + */ +module.exports = format(info => { + const curr = +new Date(); + this.diff = curr - (this.prevTime || curr); + this.prevTime = curr; + info.ms = `+${ms(this.diff)}`; + + return info; +}); diff --git a/build/node_modules/logform/package.json b/build/node_modules/logform/package.json new file mode 100644 index 00000000..2b0b47e4 --- /dev/null +++ b/build/node_modules/logform/package.json @@ -0,0 +1,76 @@ +{ + "_from": "logform@^2.2.0", + "_id": "logform@2.2.0", + "_inBundle": false, + "_integrity": "sha512-N0qPlqfypFx7UHNn4B3lzS/b0uLqt2hmuoa+PpuXNYgozdJYAyauF5Ky0BWVjrxDlMWiT3qN4zPq3vVAfZy7Yg==", + "_location": "/logform", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "logform@^2.2.0", + "name": "logform", + "escapedName": "logform", + "rawSpec": "^2.2.0", + "saveSpec": null, + "fetchSpec": "^2.2.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/logform/-/logform-2.2.0.tgz", + "_shasum": "40f036d19161fc76b68ab50fdc7fe495544492f2", + "_spec": "logform@^2.2.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "browser": "dist/browser.js", + "bugs": { + "url": "https://github.com/winstonjs/logform/issues" + }, + "bundleDependencies": false, + "dependencies": { + "colors": "^1.2.1", + "fast-safe-stringify": "^2.0.4", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "triple-beam": "^1.3.0" + }, + "deprecated": false, + "description": "An mutable object-based log format designed for chaining & objectMode streams.", + "devDependencies": { + "@babel/cli": "^7.10.3", + "@babel/core": "^7.10.3", + "@babel/preset-env": "^7.10.3", + "assume": "^2.2.0", + "eslint-config-populist": "^4.1.0", + "mocha": "^8.0.1", + "nyc": "^15.1.0", + "rimraf": "^3.0.2" + }, + "homepage": "https://github.com/winstonjs/logform#readme", + "keywords": [ + "winston", + "logging", + "format", + "winstonjs" + ], + "license": "MIT", + "main": "index.js", + "name": "logform", + "repository": { + "type": "git", + "url": "git+https://github.com/winstonjs/logform.git" + }, + "scripts": { + "build": "rimraf dist && babel *.js -d ./dist", + "lint": "populist *.js test/*.js examples/*.js", + "prepublishOnly": "npm run build", + "pretest": "npm run lint && npm run build", + "test": "nyc mocha test/*.test.js" + }, + "types": "./index.d.ts", + "version": "2.2.0" +} diff --git a/build/node_modules/logform/pad-levels.js b/build/node_modules/logform/pad-levels.js new file mode 100644 index 00000000..7db5a9d6 --- /dev/null +++ b/build/node_modules/logform/pad-levels.js @@ -0,0 +1,83 @@ +/* eslint no-unused-vars: 0 */ +'use strict'; + +const { configs, LEVEL, MESSAGE } = require('triple-beam'); + +class Padder { + constructor(opts = { levels: configs.npm.levels }) { + this.paddings = Padder.paddingForLevels(opts.levels, opts.filler); + this.options = opts; + } + + /** + * Returns the maximum length of keys in the specified `levels` Object. + * @param {Object} levels Set of all levels to calculate longest level against. + * @returns {Number} Maximum length of the longest level string. + */ + static getLongestLevel(levels) { + const lvls = Object.keys(levels).map(level => level.length); + return Math.max(...lvls); + } + + /** + * Returns the padding for the specified `level` assuming that the + * maximum length of all levels it's associated with is `maxLength`. + * @param {String} level Level to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @param {Number} maxLength Length of the longest level + * @returns {String} Padding string for the `level` + */ + static paddingForLevel(level, filler, maxLength) { + const targetLen = maxLength + 1 - level.length; + const rep = Math.floor(targetLen / filler.length); + const padding = `${filler}${filler.repeat(rep)}`; + return padding.slice(0, targetLen); + } + + /** + * Returns an object with the string paddings for the given `levels` + * using the specified `filler`. + * @param {Object} levels Set of all levels to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @returns {Object} Mapping of level to desired padding. + */ + static paddingForLevels(levels, filler = ' ') { + const maxLength = Padder.getLongestLevel(levels); + return Object.keys(levels).reduce((acc, level) => { + acc[level] = Padder.paddingForLevel(level, filler, maxLength); + return acc; + }, {}); + } + + /** + * Prepends the padding onto the `message` based on the `LEVEL` of + * the `info`. This is based on the behavior of `winston@2` which also + * prepended the level onto the message. + * + * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 + * + * @param {Info} info Logform info object + * @param {Object} opts Options passed along to this instance. + * @returns {Info} Modified logform info object. + */ + transform(info, opts) { + info.message = `${this.paddings[info[LEVEL]]}${info.message}`; + if (info[MESSAGE]) { + info[MESSAGE] = `${this.paddings[info[LEVEL]]}${info[MESSAGE]}`; + } + + return info; + } +} + +/* + * function padLevels (info) + * Returns a new instance of the padLevels Format which pads + * levels to be the same length. This was previously exposed as + * { padLevels: true } to transports in `winston < 3.0.0`. + */ +module.exports = opts => new Padder(opts); + +module.exports.Padder + = module.exports.Format + = Padder; diff --git a/build/node_modules/logform/pretty-print.js b/build/node_modules/logform/pretty-print.js new file mode 100644 index 00000000..2ad3dbea --- /dev/null +++ b/build/node_modules/logform/pretty-print.js @@ -0,0 +1,29 @@ +'use strict'; + +const inspect = require('util').inspect; +const format = require('./format'); +const { LEVEL, MESSAGE, SPLAT } = require('triple-beam'); + +/* + * function prettyPrint (info) + * Returns a new instance of the prettyPrint Format that "prettyPrint" + * serializes `info` objects. This was previously exposed as + * { prettyPrint: true } to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts = {}) => { + // + // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they + // are internal, we remove them before util.inspect so they + // are not printed. + // + const stripped = Object.assign({}, info); + + // Remark (indexzero): update this technique in April 2019 + // when node@6 is EOL + delete stripped[LEVEL]; + delete stripped[MESSAGE]; + delete stripped[SPLAT]; + + info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); + return info; +}); diff --git a/build/node_modules/logform/printf.js b/build/node_modules/logform/printf.js new file mode 100644 index 00000000..4e60bbce --- /dev/null +++ b/build/node_modules/logform/printf.js @@ -0,0 +1,26 @@ +'use strict'; + +const { MESSAGE } = require('triple-beam'); + +class Printf { + constructor(templateFn) { + this.template = templateFn; + } + + transform(info) { + info[MESSAGE] = this.template(info); + return info; + } +} + +/* + * function printf (templateFn) + * Returns a new instance of the printf Format that creates an + * intermediate prototype to store the template string-based formatter + * function. + */ +module.exports = opts => new Printf(opts); + +module.exports.Printf + = module.exports.Format + = Printf; diff --git a/build/node_modules/logform/simple.js b/build/node_modules/logform/simple.js new file mode 100644 index 00000000..09f822cc --- /dev/null +++ b/build/node_modules/logform/simple.js @@ -0,0 +1,33 @@ +/* eslint no-undefined: 0 */ +'use strict'; + +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); +const jsonStringify = require('fast-safe-stringify'); + +/* + * function simple (info) + * Returns a new instance of the simple format TransformStream + * which writes a simple representation of logs. + * + * const { level, message, splat, ...rest } = info; + * + * ${level}: ${message} if rest is empty + * ${level}: ${message} ${JSON.stringify(rest)} otherwise + */ +module.exports = format(info => { + const stringifiedRest = jsonStringify(Object.assign({}, info, { + level: undefined, + message: undefined, + splat: undefined + })); + + const padding = info.padding && info.padding[info.level] || ''; + if (stringifiedRest !== '{}') { + info[MESSAGE] = `${info.level}:${padding} ${info.message} ${stringifiedRest}`; + } else { + info[MESSAGE] = `${info.level}:${padding} ${info.message}`; + } + + return info; +}); diff --git a/build/node_modules/logform/splat.js b/build/node_modules/logform/splat.js new file mode 100644 index 00000000..08ff6f7f --- /dev/null +++ b/build/node_modules/logform/splat.js @@ -0,0 +1,132 @@ +'use strict'; + +const util = require('util'); +const { SPLAT } = require('triple-beam'); + +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ +const formatRegExp = /%[scdjifoO%]/g; + +/** + * Captures the number of escaped % signs in a format string (i.e. %s strings). + * @type {RegExp} + */ +const escapedPercent = /%%/g; + +class Splatter { + constructor(opts) { + this.options = opts; + } + + /** + * Check to see if tokens <= splat.length, assign { splat, meta } into the + * `info` accordingly, and write to this instance. + * + * @param {Info} info Logform info message. + * @param {String[]} tokens Set of string interpolation tokens. + * @returns {Info} Modified info message + * @private + */ + _splat(info, tokens) { + const msg = info.message; + const splat = info[SPLAT] || info.splat || []; + const percents = msg.match(escapedPercent); + const escapes = percents && percents.length || 0; + + // The expected splat is the number of tokens minus the number of escapes + // e.g. + // - { expectedSplat: 3 } '%d %s %j' + // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j' + // + // Any "meta" will be arugments in addition to the expected splat size + // regardless of type. e.g. + // + // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true }); + // would result in splat of four (4), but only three (3) are expected. Therefore: + // + // extraSplat = 3 - 4 = -1 + // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1); + // splat = [100, 'wow', { such: 'js' }] + const expectedSplat = tokens.length - escapes; + const extraSplat = expectedSplat - splat.length; + const metas = extraSplat < 0 + ? splat.splice(extraSplat, -1 * extraSplat) + : []; + + // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + + info.message = util.format(msg, ...splat); + return info; + } + + /** + * Transforms the `info` message by using `util.format` to complete + * any `info.message` provided it has string interpolation tokens. + * If no tokens exist then `info` is immutable. + * + * @param {Info} info Logform info message. + * @param {Object} opts Options for this instance. + * @returns {Info} Modified info message + */ + transform(info) { + const msg = info.message; + const splat = info[SPLAT] || info.splat; + + // No need to process anything if splat is undefined + if (!splat || !splat.length) { + return info; + } + + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + const tokens = msg && msg.match && msg.match(formatRegExp); + + // This condition will take care of inputs with info[SPLAT] + // but no tokens present + if (!tokens && (splat || splat.length)) { + const metas = splat.length > 1 + ? splat.splice(0) + : splat; + + // Now that { splat } has been separated from any potential { meta }. we + // can assign this to the `info` object and write it to our format stream. + // If the additional metas are **NOT** objects or **LACK** enumerable properties + // you are going to have a bad time. + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + + return info; + } + + if (tokens) { + return this._splat(info, tokens); + } + + return info; + } +} + +/* + * function splat (info) + * Returns a new instance of the splat format TransformStream + * which performs string interpolation from `info` objects. This was + * previously exposed implicitly in `winston < 3.0.0`. + */ +module.exports = opts => new Splatter(opts); diff --git a/build/node_modules/logform/timestamp.js b/build/node_modules/logform/timestamp.js new file mode 100644 index 00000000..706e4881 --- /dev/null +++ b/build/node_modules/logform/timestamp.js @@ -0,0 +1,30 @@ +'use strict'; + +const fecha = require('fecha'); +const format = require('./format'); + +/* + * function timestamp (info) + * Returns a new instance of the timestamp Format which adds a timestamp + * to the info. It was previously available in winston < 3.0.0 as: + * + * - { timestamp: true } // `new Date.toISOString()` + * - { timestamp: function:String } // Value returned by `timestamp()` + */ +module.exports = format((info, opts = {}) => { + if (opts.format) { + info.timestamp = typeof opts.format === 'function' + ? opts.format() + : fecha.format(new Date(), opts.format); + } + + if (!info.timestamp) { + info.timestamp = new Date().toISOString(); + } + + if (opts.alias) { + info[opts.alias] = info.timestamp; + } + + return info; +}); diff --git a/build/node_modules/logform/tsconfig.json b/build/node_modules/logform/tsconfig.json new file mode 100644 index 00000000..1d494cf6 --- /dev/null +++ b/build/node_modules/logform/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/build/node_modules/logform/uncolorize.js b/build/node_modules/logform/uncolorize.js new file mode 100644 index 00000000..baae0f04 --- /dev/null +++ b/build/node_modules/logform/uncolorize.js @@ -0,0 +1,27 @@ +'use strict'; + +const colors = require('colors/safe'); +const format = require('./format'); +const { MESSAGE } = require('triple-beam'); + +/* + * function uncolorize (info) + * Returns a new instance of the uncolorize Format that strips colors + * from `info` objects. This was previously exposed as { stripColors: true } + * to transports in `winston < 3.0.0`. + */ +module.exports = format((info, opts) => { + if (opts.level !== false) { + info.level = colors.strip(info.level); + } + + if (opts.message !== false) { + info.message = colors.strip(info.message); + } + + if (opts.raw !== false && info[MESSAGE]) { + info[MESSAGE] = colors.strip(info[MESSAGE]); + } + + return info; +}); diff --git a/build/node_modules/minimist/.travis.yml b/build/node_modules/minimist/.travis.yml index cc4dba29..74c57bf1 100644 --- a/build/node_modules/minimist/.travis.yml +++ b/build/node_modules/minimist/.travis.yml @@ -2,3 +2,7 @@ language: node_js node_js: - "0.8" - "0.10" + - "0.12" + - "iojs" +before_install: + - npm install -g npm@~1.4.6 diff --git a/build/node_modules/minimist/example/parse.js b/build/node_modules/minimist/example/parse.js index abff3e8e..f7c8d498 100644 --- a/build/node_modules/minimist/example/parse.js +++ b/build/node_modules/minimist/example/parse.js @@ -1,2 +1,2 @@ var argv = require('../')(process.argv.slice(2)); -console.dir(argv); +console.log(argv); diff --git a/build/node_modules/minimist/index.js b/build/node_modules/minimist/index.js index 584f551a..d2afe5e4 100644 --- a/build/node_modules/minimist/index.js +++ b/build/node_modules/minimist/index.js @@ -1,15 +1,19 @@ module.exports = function (args, opts) { if (!opts) opts = {}; - var flags = { bools : {}, strings : {} }; - - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); - - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - }); + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } var aliases = {}; Object.keys(opts.alias || {}).forEach(function (key) { @@ -20,7 +24,14 @@ module.exports = function (args, opts) { })); }); }); - + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + var defaults = opts['default'] || {}; var argv = { _ : [] }; @@ -35,7 +46,16 @@ module.exports = function (args, opts) { args = args.slice(0, args.indexOf('--')); } - function setArg (key, val) { + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + var value = !flags.strings[key] && isNumber(val) ? Number(val) : val ; @@ -45,7 +65,41 @@ module.exports = function (args, opts) { setKey(argv, x.split('.'), value); }); } + + function setKey (obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length-1; i++) { + var key = keys[i]; + if (key === '__proto__') return; + if (o[key] === undefined) o[key] = {}; + if (o[key] === Object.prototype || o[key] === Number.prototype + || o[key] === String.prototype) o[key] = {}; + if (o[key] === Array.prototype) o[key] = []; + o = o[key]; + } + + var key = keys[keys.length - 1]; + if (key === '__proto__') return; + if (o === Object.prototype || o === Number.prototype + || o === String.prototype) o = {}; + if (o === Array.prototype) o = []; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + for (var i = 0; i < args.length; i++) { var arg = args[i]; @@ -54,27 +108,33 @@ module.exports = function (args, opts) { // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - setArg(m[1], m[2]); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); } else if (/^--no-.+/.test(arg)) { var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false); + setArg(key, false, arg); } else if (/^--.+/.test(arg)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !/^-/.test(next) && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, next); + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); i++; } else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true'); + setArg(key, next === 'true', arg); i++; } else { - setArg(key, flags.strings[key] ? '' : true); + setArg(key, flags.strings[key] ? '' : true, arg); } } else if (/^-[^-]+/.test(arg)) { @@ -85,24 +145,30 @@ module.exports = function (args, opts) { var next = arg.slice(j+2); if (next === '-') { - setArg(letters[j], next) + setArg(letters[j], next, arg) continue; } + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next); + setArg(letters[j], next, arg); broken = true; break; } if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2)); + setArg(letters[j], arg.slice(j+2), arg); broken = true; break; } else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true); + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } @@ -110,23 +176,29 @@ module.exports = function (args, opts) { if (!broken && key !== '-') { if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, args[i+1]); + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); i++; } - else if (args[i+1] && /true|false/.test(args[i+1])) { - setArg(key, args[i+1] === 'true'); + else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); i++; } else { - setArg(key, flags.strings[key] ? '' : true); + setArg(key, flags.strings[key] ? '' : true, arg); } } } else { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } } } @@ -140,9 +212,17 @@ module.exports = function (args, opts) { } }); - notFlags.forEach(function(key) { - argv._.push(key); - }); + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } return argv; }; @@ -157,31 +237,9 @@ function hasKey (obj, keys) { return key in o; } -function setKey (obj, keys, value) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - if (o[key] === undefined) o[key] = {}; - o = o[key]; - }); - - var key = keys[keys.length - 1]; - if (o[key] === undefined || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } -} - function isNumber (x) { if (typeof x === 'number') return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } -function longest (xs) { - return Math.max.apply(null, xs.map(function (x) { return x.length })); -} diff --git a/build/node_modules/minimist/package.json b/build/node_modules/minimist/package.json index 9cbd8611..7501ee27 100644 --- a/build/node_modules/minimist/package.json +++ b/build/node_modules/minimist/package.json @@ -1,26 +1,26 @@ { - "_from": "minimist@0.0.8", - "_id": "minimist@0.0.8", + "_from": "minimist@^1.2.5", + "_id": "minimist@1.2.5", "_inBundle": false, - "_integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "_integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", "_location": "/minimist", "_phantomChildren": {}, "_requested": { - "type": "version", + "type": "range", "registry": true, - "raw": "minimist@0.0.8", + "raw": "minimist@^1.2.5", "name": "minimist", "escapedName": "minimist", - "rawSpec": "0.0.8", + "rawSpec": "^1.2.5", "saveSpec": null, - "fetchSpec": "0.0.8" + "fetchSpec": "^1.2.5" }, "_requiredBy": [ "/mkdirp" ], - "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", - "_spec": "minimist@0.0.8", + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "_shasum": "67d66014b66a6a8aaa0c083c5fd58df4e4e97602", + "_spec": "minimist@^1.2.5", "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/mkdirp", "author": { "name": "James Halliday", @@ -34,8 +34,9 @@ "deprecated": false, "description": "parse argument options", "devDependencies": { + "covert": "^1.0.0", "tap": "~0.4.0", - "tape": "~1.0.4" + "tape": "^3.5.0" }, "homepage": "https://github.com/substack/minimist", "keywords": [ @@ -52,6 +53,7 @@ "url": "git://github.com/substack/minimist.git" }, "scripts": { + "coverage": "covert test/*.js", "test": "tap test/*.js" }, "testling": { @@ -67,5 +69,5 @@ "opera/12" ] }, - "version": "0.0.8" + "version": "1.2.5" } diff --git a/build/node_modules/minimist/readme.markdown b/build/node_modules/minimist/readme.markdown index c2563532..5fd97ab1 100644 --- a/build/node_modules/minimist/readme.markdown +++ b/build/node_modules/minimist/readme.markdown @@ -5,15 +5,11 @@ parse argument options This module is the guts of optimist's argument parser without all the fanciful decoration. -[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) - -[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) - # example ``` js var argv = require('minimist')(process.argv.slice(2)); -console.dir(argv); +console.log(argv); ``` ``` @@ -33,6 +29,13 @@ $ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz beep: 'boop' } ``` +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.3 or later: https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 + # methods ``` js @@ -55,10 +58,29 @@ options can be: * `opts.string` - a string or array of strings argument names to always treat as strings -* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) * `opts.alias` - an object mapping string names to strings or arrays of string argument names to use as aliases * `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { _: [ 'one', 'two', 'three' ], + '--': [ 'four', 'five', '--six' ] } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. # install diff --git a/build/node_modules/minimist/test/all_bool.js b/build/node_modules/minimist/test/all_bool.js new file mode 100644 index 00000000..ac835483 --- /dev/null +++ b/build/node_modules/minimist/test/all_bool.js @@ -0,0 +1,32 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/build/node_modules/minimist/test/bool.js b/build/node_modules/minimist/test/bool.js new file mode 100644 index 00000000..5f7dbde1 --- /dev/null +++ b/build/node_modules/minimist/test/bool.js @@ -0,0 +1,178 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var alt = [ '--harp', 'derp' ]; + var opts = { + alias: { 'h': ['herp', 'harp'] }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, false); + t.end(); +}); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + '_': ['true.txt'] + }; + + t.same(result, expected); + t.end(); +}); \ No newline at end of file diff --git a/build/node_modules/minimist/test/dash.js b/build/node_modules/minimist/test/dash.js index 8b034b99..5a4fa5be 100644 --- a/build/node_modules/minimist/test/dash.js +++ b/build/node_modules/minimist/test/dash.js @@ -22,3 +22,10 @@ test('-a -- b', function (t) { t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); }); + +test('move arguments after the -- into their own `--` array', function(t) { + t.plan(1); + t.deepEqual( + parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), + { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); +}); diff --git a/build/node_modules/minimist/test/default_bool.js b/build/node_modules/minimist/test/default_bool.js index f0041ee4..780a3112 100644 --- a/build/node_modules/minimist/test/default_bool.js +++ b/build/node_modules/minimist/test/default_bool.js @@ -18,3 +18,18 @@ test('boolean default false', function (t) { t.equal(argv.somefalse, false); t.end(); }); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, null); + var argv = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, true); + t.end(); + +}) diff --git a/build/node_modules/minimist/test/dotted.js b/build/node_modules/minimist/test/dotted.js index ef0ae349..d8b3e856 100644 --- a/build/node_modules/minimist/test/dotted.js +++ b/build/node_modules/minimist/test/dotted.js @@ -14,3 +14,9 @@ test('dotted default', function (t) { t.equal(argv.aa.bb, 11); t.end(); }); + +test('dotted default with no alias', function (t) { + var argv = parse('', {default: {'a.b': 11}}); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/build/node_modules/minimist/test/kv_short.js b/build/node_modules/minimist/test/kv_short.js new file mode 100644 index 00000000..f813b305 --- /dev/null +++ b/build/node_modules/minimist/test/kv_short.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-b=123' ]); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-a=whatever', '-b=robots' ]); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); diff --git a/build/node_modules/minimist/test/num.js b/build/node_modules/minimist/test/num.js new file mode 100644 index 00000000..2cc77f4d --- /dev/null +++ b/build/node_modules/minimist/test/num.js @@ -0,0 +1,36 @@ +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse([ '-x', 1234, 789 ]); + t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/build/node_modules/minimist/test/parse.js b/build/node_modules/minimist/test/parse.js index 8a906466..7b4a2a17 100644 --- a/build/node_modules/minimist/test/parse.js +++ b/build/node_modules/minimist/test/parse.js @@ -42,32 +42,6 @@ test('comprehensive', function (t) { t.end(); }); -test('nums', function (t) { - var argv = parse([ - '-x', '1234', - '-y', '5.67', - '-z', '1e7', - '-w', '10f', - '--hex', '0xdeadbeef', - '789' - ]); - t.deepEqual(argv, { - x : 1234, - y : 5.67, - z : 1e7, - w : '10f', - hex : 0xdeadbeef, - _ : [ 789 ] - }); - t.deepEqual(typeof argv.x, 'number'); - t.deepEqual(typeof argv.y, 'number'); - t.deepEqual(typeof argv.z, 'number'); - t.deepEqual(typeof argv.w, 'string'); - t.deepEqual(typeof argv.hex, 'number'); - t.deepEqual(typeof argv._[0], 'number'); - t.end(); -}); - test('flag boolean', function (t) { var argv = parse([ '-t', 'moo' ], { boolean: 't' }); t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); @@ -92,42 +66,6 @@ test('flag boolean value', function (t) { t.end(); }); -test('flag boolean default false', function (t) { - var argv = parse(['moo'], { - boolean: ['t', 'verbose'], - default: { verbose: false, t: false } - }); - - t.deepEqual(argv, { - verbose: false, - t: false, - _: ['moo'] - }); - - t.deepEqual(typeof argv.verbose, 'boolean'); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); - -}); - -test('boolean groups', function (t) { - var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { - boolean: ['x','y','z'] - }); - - t.deepEqual(argv, { - x : true, - y : false, - z : true, - _ : [ 'one', 'two', 'three' ] - }); - - t.deepEqual(typeof argv.x, 'boolean'); - t.deepEqual(typeof argv.y, 'boolean'); - t.deepEqual(typeof argv.z, 'boolean'); - t.end(); -}); - test('newlines in params' , function (t) { var args = parse([ '-s', "X\nX" ]) t.deepEqual(args, { _ : [], s : "X\nX" }); @@ -183,6 +121,29 @@ test('empty strings', function(t) { }); +test('string and alias', function(t) { + var x = parse([ '--str', '000123' ], { + string: 's', + alias: { s: 'str' } + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse([ '-s', '000123' ], { + string: 'str', + alias: { str: 's' } + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + t.end(); +}); + test('slashBreak', function (t) { t.same( parse([ '-I/foo/bar/baz' ]), @@ -234,85 +195,3 @@ test('nested dotted objects', function (t) { t.same(argv.beep, { boop : true }); t.end(); }); - -test('boolean and alias with chainable api', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = parse(aliased, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var propertyArgv = parse(regular, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias with options hash', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - alias: { 'h': 'herp' }, - boolean: 'herp' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias using explicit true', function (t) { - var aliased = [ '-h', 'true' ]; - var regular = [ '--herp', 'true' ]; - var opts = { - alias: { h: 'herp' }, - boolean: 'h' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -// regression, see https://github.com/substack/node-optimist/issues/71 -test('boolean and --x=true', function(t) { - var parsed = parse(['--boool', '--other=true'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'true'); - - parsed = parse(['--boool', '--other=false'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'false'); - t.end(); -}); diff --git a/build/node_modules/minimist/test/parse_modified.js b/build/node_modules/minimist/test/parse_modified.js index 21851b03..ab620dc5 100644 --- a/build/node_modules/minimist/test/parse_modified.js +++ b/build/node_modules/minimist/test/parse_modified.js @@ -5,5 +5,5 @@ test('parse with modifier functions' , function (t) { t.plan(1); var argv = parse([ '-b', '123' ], { boolean: 'b' }); - t.deepEqual(argv, { b: true, _: ['123'] }); + t.deepEqual(argv, { b: true, _: [123] }); }); diff --git a/build/node_modules/minimist/test/proto.js b/build/node_modules/minimist/test/proto.js new file mode 100644 index 00000000..8649107e --- /dev/null +++ b/build/node_modules/minimist/test/proto.js @@ -0,0 +1,44 @@ +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x','123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4,5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x','5','--x.__proto__.z','100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x','abc','--x.__proto__.z','def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y','123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); diff --git a/build/node_modules/minimist/test/stop_early.js b/build/node_modules/minimist/test/stop_early.js new file mode 100644 index 00000000..bdf9fbcb --- /dev/null +++ b/build/node_modules/minimist/test/stop_early.js @@ -0,0 +1,15 @@ +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'] + }); + + t.end(); +}); diff --git a/build/node_modules/minimist/test/unknown.js b/build/node_modules/minimist/test/unknown.js new file mode 100644 index 00000000..462a36bd --- /dev/null +++ b/build/node_modules/minimist/test/unknown.js @@ -0,0 +1,102 @@ +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'true', '--derp', 'true' ]; + var regular = [ '--herp', 'true', '-d', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [] + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; + var regular = [ '--herp', 'hello', '-d', 'moon' ]; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello' ]; + var regular = [ '--herp', 'hello' ]; + var opts = { + default: { 'h': 'bar' }, + alias: { 'h': 'herp' }, + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '--bad', '--', 'good', 'arg' ]; + var opts = { + '--': true, + unknown: unknownFn + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + '_': [] + }) + t.end(); +}); diff --git a/build/node_modules/mkdirp/index.js b/build/node_modules/mkdirp/index.js index a1742b20..468d7cd8 100644 --- a/build/node_modules/mkdirp/index.js +++ b/build/node_modules/mkdirp/index.js @@ -1,5 +1,6 @@ var path = require('path'); var fs = require('fs'); +var _0777 = parseInt('0777', 8); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; @@ -16,7 +17,7 @@ function mkdirP (p, opts, f, made) { var xfs = opts.fs || fs; if (mode === undefined) { - mode = 0777 & (~process.umask()); + mode = _0777 } if (!made) made = null; @@ -30,6 +31,7 @@ function mkdirP (p, opts, f, made) { } switch (er.code) { case 'ENOENT': + if (path.dirname(p) === p) return cb(er); mkdirP(path.dirname(p), opts, function (er, made) { if (er) cb(er, made); else mkdirP(p, opts, cb, made); @@ -60,7 +62,7 @@ mkdirP.sync = function sync (p, opts, made) { var xfs = opts.fs || fs; if (mode === undefined) { - mode = 0777 & (~process.umask()); + mode = _0777 } if (!made) made = null; diff --git a/build/node_modules/mkdirp/package.json b/build/node_modules/mkdirp/package.json index 4fdbf745..4e5db40b 100644 --- a/build/node_modules/mkdirp/package.json +++ b/build/node_modules/mkdirp/package.json @@ -1,27 +1,27 @@ { - "_from": "mkdirp@0.5.0", - "_id": "mkdirp@0.5.0", + "_from": "mkdirp@^0.5.1", + "_id": "mkdirp@0.5.5", "_inBundle": false, - "_integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", + "_integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", "_location": "/mkdirp", "_phantomChildren": {}, "_requested": { - "type": "version", + "type": "range", "registry": true, - "raw": "mkdirp@0.5.0", + "raw": "mkdirp@^0.5.1", "name": "mkdirp", "escapedName": "mkdirp", - "rawSpec": "0.5.0", + "rawSpec": "^0.5.1", "saveSpec": null, - "fetchSpec": "0.5.0" + "fetchSpec": "^0.5.1" }, "_requiredBy": [ - "/mocha" + "/configparser" ], - "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", - "_shasum": "1d73076a6df986cd9344e15e71fcc05a4c9abf12", - "_spec": "mkdirp@0.5.0", - "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/mocha", + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "_shasum": "d91cefd62d1436ca0f41620e251288d420099def", + "_spec": "mkdirp@^0.5.1", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/configparser", "author": { "name": "James Halliday", "email": "mail@substack.net", @@ -35,22 +35,29 @@ }, "bundleDependencies": false, "dependencies": { - "minimist": "0.0.8" + "minimist": "^1.2.5" }, - "deprecated": "Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)", + "deprecated": false, "description": "Recursively mkdir, like `mkdir -p`", "devDependencies": { - "mock-fs": "~2.2.0", - "tap": "~0.4.0" + "mock-fs": "^3.7.0", + "tap": "^5.4.2" }, + "files": [ + "bin", + "index.js" + ], "homepage": "https://github.com/substack/node-mkdirp#readme", "keywords": [ "mkdir", "directory" ], "license": "MIT", - "main": "./index", + "main": "index.js", "name": "mkdirp", + "publishConfig": { + "tag": "legacy" + }, "repository": { "type": "git", "url": "git+https://github.com/substack/node-mkdirp.git" @@ -58,5 +65,5 @@ "scripts": { "test": "tap test/*.js" }, - "version": "0.5.0" + "version": "0.5.5" } diff --git a/build/node_modules/mkdirp/readme.markdown b/build/node_modules/mkdirp/readme.markdown index 3cc13153..fc314bfb 100644 --- a/build/node_modules/mkdirp/readme.markdown +++ b/build/node_modules/mkdirp/readme.markdown @@ -37,7 +37,7 @@ Create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a non-object, it will be treated as the `opts.mode`. -If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. +If `opts.mode` isn't specified, it defaults to `0777`. `cb(err, made)` fires with the error or the first directory `made` that had to be created, if any. @@ -52,7 +52,7 @@ Synchronously create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a non-object, it will be treated as the `opts.mode`. -If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. +If `opts.mode` isn't specified, it defaults to `0777`. Returns the first directory that had to be created, if any. diff --git a/build/node_modules/mocha/node_modules/.bin/mkdirp b/build/node_modules/mocha/node_modules/.bin/mkdirp new file mode 120000 index 00000000..017896ce --- /dev/null +++ b/build/node_modules/mocha/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/build/node_modules/mocha/node_modules/minimist/.travis.yml b/build/node_modules/mocha/node_modules/minimist/.travis.yml new file mode 100644 index 00000000..cc4dba29 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/build/node_modules/mocha/node_modules/minimist/LICENSE b/build/node_modules/mocha/node_modules/minimist/LICENSE new file mode 100644 index 00000000..ee27ba4b --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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. diff --git a/build/node_modules/mocha/node_modules/minimist/example/parse.js b/build/node_modules/mocha/node_modules/minimist/example/parse.js new file mode 100644 index 00000000..abff3e8e --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.dir(argv); diff --git a/build/node_modules/mocha/node_modules/minimist/index.js b/build/node_modules/mocha/node_modules/minimist/index.js new file mode 100644 index 00000000..584f551a --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/index.js @@ -0,0 +1,187 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {} }; + + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + }); + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function setArg (key, val) { + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + setArg(m[1], m[2]); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2)); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, args[i+1]); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + } + else { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + notFlags.forEach(function(key) { + argv._.push(key); + }); + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function longest (xs) { + return Math.max.apply(null, xs.map(function (x) { return x.length })); +} diff --git a/build/node_modules/mocha/node_modules/minimist/package.json b/build/node_modules/mocha/node_modules/minimist/package.json new file mode 100644 index 00000000..66f818b3 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/package.json @@ -0,0 +1,71 @@ +{ + "_from": "minimist@0.0.8", + "_id": "minimist@0.0.8", + "_inBundle": false, + "_integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "_location": "/mocha/minimist", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "minimist@0.0.8", + "name": "minimist", + "escapedName": "minimist", + "rawSpec": "0.0.8", + "saveSpec": null, + "fetchSpec": "0.0.8" + }, + "_requiredBy": [ + "/mocha/mkdirp" + ], + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", + "_spec": "minimist@0.0.8", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/mocha/node_modules/mkdirp", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "parse argument options", + "devDependencies": { + "tap": "~0.4.0", + "tape": "~1.0.4" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "license": "MIT", + "main": "index.js", + "name": "minimist", + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "version": "0.0.8" +} diff --git a/build/node_modules/mocha/node_modules/minimist/readme.markdown b/build/node_modules/mocha/node_modules/minimist/readme.markdown new file mode 100644 index 00000000..c2563532 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/readme.markdown @@ -0,0 +1,73 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) + +[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.dir(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/build/node_modules/mocha/node_modules/minimist/test/dash.js b/build/node_modules/mocha/node_modules/minimist/test/dash.js new file mode 100644 index 00000000..8b034b99 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/dash.js @@ -0,0 +1,24 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/default_bool.js b/build/node_modules/mocha/node_modules/minimist/test/default_bool.js new file mode 100644 index 00000000..f0041ee4 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/default_bool.js @@ -0,0 +1,20 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/dotted.js b/build/node_modules/mocha/node_modules/minimist/test/dotted.js new file mode 100644 index 00000000..ef0ae349 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/dotted.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/long.js b/build/node_modules/mocha/node_modules/minimist/test/long.js new file mode 100644 index 00000000..5d3a1e09 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/parse.js b/build/node_modules/mocha/node_modules/minimist/test/parse.js new file mode 100644 index 00000000..8a906466 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/parse.js @@ -0,0 +1,318 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); + +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/parse_modified.js b/build/node_modules/mocha/node_modules/minimist/test/parse_modified.js new file mode 100644 index 00000000..21851b03 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: ['123'] }); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/short.js b/build/node_modules/mocha/node_modules/minimist/test/short.js new file mode 100644 index 00000000..d513a1c2 --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/build/node_modules/mocha/node_modules/minimist/test/whitespace.js b/build/node_modules/mocha/node_modules/minimist/test/whitespace.js new file mode 100644 index 00000000..8a52a58c --- /dev/null +++ b/build/node_modules/mocha/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/build/node_modules/mkdirp/.npmignore b/build/node_modules/mocha/node_modules/mkdirp/.npmignore similarity index 100% rename from build/node_modules/mkdirp/.npmignore rename to build/node_modules/mocha/node_modules/mkdirp/.npmignore diff --git a/build/node_modules/mkdirp/.travis.yml b/build/node_modules/mocha/node_modules/mkdirp/.travis.yml similarity index 100% rename from build/node_modules/mkdirp/.travis.yml rename to build/node_modules/mocha/node_modules/mkdirp/.travis.yml diff --git a/build/node_modules/mocha/node_modules/mkdirp/LICENSE b/build/node_modules/mocha/node_modules/mkdirp/LICENSE new file mode 100644 index 00000000..432d1aeb --- /dev/null +++ b/build/node_modules/mocha/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +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. diff --git a/build/node_modules/mocha/node_modules/mkdirp/bin/cmd.js b/build/node_modules/mocha/node_modules/mkdirp/bin/cmd.js new file mode 100755 index 00000000..d95de15a --- /dev/null +++ b/build/node_modules/mocha/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/build/node_modules/mocha/node_modules/mkdirp/bin/usage.txt b/build/node_modules/mocha/node_modules/mkdirp/bin/usage.txt new file mode 100644 index 00000000..f952aa2c --- /dev/null +++ b/build/node_modules/mocha/node_modules/mkdirp/bin/usage.txt @@ -0,0 +1,12 @@ +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + diff --git a/build/node_modules/mkdirp/examples/pow.js b/build/node_modules/mocha/node_modules/mkdirp/examples/pow.js similarity index 100% rename from build/node_modules/mkdirp/examples/pow.js rename to build/node_modules/mocha/node_modules/mkdirp/examples/pow.js diff --git a/build/node_modules/mocha/node_modules/mkdirp/index.js b/build/node_modules/mocha/node_modules/mkdirp/index.js new file mode 100644 index 00000000..a1742b20 --- /dev/null +++ b/build/node_modules/mocha/node_modules/mkdirp/index.js @@ -0,0 +1,97 @@ +var path = require('path'); +var fs = require('fs'); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/build/node_modules/mocha/node_modules/mkdirp/package.json b/build/node_modules/mocha/node_modules/mkdirp/package.json new file mode 100644 index 00000000..c29def61 --- /dev/null +++ b/build/node_modules/mocha/node_modules/mkdirp/package.json @@ -0,0 +1,62 @@ +{ + "_from": "mkdirp@0.5.0", + "_id": "mkdirp@0.5.0", + "_inBundle": false, + "_integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", + "_location": "/mocha/mkdirp", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mkdirp@0.5.0", + "name": "mkdirp", + "escapedName": "mkdirp", + "rawSpec": "0.5.0", + "saveSpec": null, + "fetchSpec": "0.5.0" + }, + "_requiredBy": [ + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", + "_shasum": "1d73076a6df986cd9344e15e71fcc05a4c9abf12", + "_spec": "mkdirp@0.5.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/mocha", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "bundleDependencies": false, + "dependencies": { + "minimist": "0.0.8" + }, + "deprecated": "Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)", + "description": "Recursively mkdir, like `mkdir -p`", + "devDependencies": { + "mock-fs": "~2.2.0", + "tap": "~0.4.0" + }, + "homepage": "https://github.com/substack/node-mkdirp#readme", + "keywords": [ + "mkdir", + "directory" + ], + "license": "MIT", + "main": "./index", + "name": "mkdirp", + "repository": { + "type": "git", + "url": "git+https://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "0.5.0" +} diff --git a/build/node_modules/mocha/node_modules/mkdirp/readme.markdown b/build/node_modules/mocha/node_modules/mkdirp/readme.markdown new file mode 100644 index 00000000..3cc13153 --- /dev/null +++ b/build/node_modules/mocha/node_modules/mkdirp/readme.markdown @@ -0,0 +1,100 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, opts, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a non-object, it will be treated as +the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and +`opts.fs.stat(path, cb)`. + +## mkdirp.sync(dir, opts) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `opts.mode`. If `opts` is a non-object, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +Returns the first directory that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and +`opts.fs.statSync(path)`. + +# usage + +This package also ships with a `mkdirp` command. + +``` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library, or + +``` +npm install -g mkdirp +``` + +to get the command. + +# license + +MIT diff --git a/build/node_modules/mkdirp/test/chmod.js b/build/node_modules/mocha/node_modules/mkdirp/test/chmod.js similarity index 100% rename from build/node_modules/mkdirp/test/chmod.js rename to build/node_modules/mocha/node_modules/mkdirp/test/chmod.js diff --git a/build/node_modules/mkdirp/test/clobber.js b/build/node_modules/mocha/node_modules/mkdirp/test/clobber.js similarity index 100% rename from build/node_modules/mkdirp/test/clobber.js rename to build/node_modules/mocha/node_modules/mkdirp/test/clobber.js diff --git a/build/node_modules/mkdirp/test/mkdirp.js b/build/node_modules/mocha/node_modules/mkdirp/test/mkdirp.js similarity index 100% rename from build/node_modules/mkdirp/test/mkdirp.js rename to build/node_modules/mocha/node_modules/mkdirp/test/mkdirp.js diff --git a/build/node_modules/mkdirp/test/opts_fs.js b/build/node_modules/mocha/node_modules/mkdirp/test/opts_fs.js similarity index 100% rename from build/node_modules/mkdirp/test/opts_fs.js rename to build/node_modules/mocha/node_modules/mkdirp/test/opts_fs.js diff --git a/build/node_modules/mkdirp/test/opts_fs_sync.js b/build/node_modules/mocha/node_modules/mkdirp/test/opts_fs_sync.js similarity index 100% rename from build/node_modules/mkdirp/test/opts_fs_sync.js rename to build/node_modules/mocha/node_modules/mkdirp/test/opts_fs_sync.js diff --git a/build/node_modules/mkdirp/test/perm.js b/build/node_modules/mocha/node_modules/mkdirp/test/perm.js similarity index 100% rename from build/node_modules/mkdirp/test/perm.js rename to build/node_modules/mocha/node_modules/mkdirp/test/perm.js diff --git a/build/node_modules/mkdirp/test/perm_sync.js b/build/node_modules/mocha/node_modules/mkdirp/test/perm_sync.js similarity index 100% rename from build/node_modules/mkdirp/test/perm_sync.js rename to build/node_modules/mocha/node_modules/mkdirp/test/perm_sync.js diff --git a/build/node_modules/mkdirp/test/race.js b/build/node_modules/mocha/node_modules/mkdirp/test/race.js similarity index 100% rename from build/node_modules/mkdirp/test/race.js rename to build/node_modules/mocha/node_modules/mkdirp/test/race.js diff --git a/build/node_modules/mkdirp/test/rel.js b/build/node_modules/mocha/node_modules/mkdirp/test/rel.js similarity index 100% rename from build/node_modules/mkdirp/test/rel.js rename to build/node_modules/mocha/node_modules/mkdirp/test/rel.js diff --git a/build/node_modules/mkdirp/test/return.js b/build/node_modules/mocha/node_modules/mkdirp/test/return.js similarity index 100% rename from build/node_modules/mkdirp/test/return.js rename to build/node_modules/mocha/node_modules/mkdirp/test/return.js diff --git a/build/node_modules/mkdirp/test/return_sync.js b/build/node_modules/mocha/node_modules/mkdirp/test/return_sync.js similarity index 100% rename from build/node_modules/mkdirp/test/return_sync.js rename to build/node_modules/mocha/node_modules/mkdirp/test/return_sync.js diff --git a/build/node_modules/mkdirp/test/root.js b/build/node_modules/mocha/node_modules/mkdirp/test/root.js similarity index 100% rename from build/node_modules/mkdirp/test/root.js rename to build/node_modules/mocha/node_modules/mkdirp/test/root.js diff --git a/build/node_modules/mkdirp/test/sync.js b/build/node_modules/mocha/node_modules/mkdirp/test/sync.js similarity index 100% rename from build/node_modules/mkdirp/test/sync.js rename to build/node_modules/mocha/node_modules/mkdirp/test/sync.js diff --git a/build/node_modules/mkdirp/test/umask.js b/build/node_modules/mocha/node_modules/mkdirp/test/umask.js similarity index 100% rename from build/node_modules/mkdirp/test/umask.js rename to build/node_modules/mocha/node_modules/mkdirp/test/umask.js diff --git a/build/node_modules/mkdirp/test/umask_sync.js b/build/node_modules/mocha/node_modules/mkdirp/test/umask_sync.js similarity index 100% rename from build/node_modules/mkdirp/test/umask_sync.js rename to build/node_modules/mocha/node_modules/mkdirp/test/umask_sync.js diff --git a/build/node_modules/ms/package.json b/build/node_modules/ms/package.json index ba4cfcf4..709a21fa 100644 --- a/build/node_modules/ms/package.json +++ b/build/node_modules/ms/package.json @@ -16,7 +16,8 @@ "fetchSpec": "^2.1.1" }, "_requiredBy": [ - "/debug" + "/debug", + "/logform" ], "_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "_shasum": "574c8138ce1d2b5861f0b44579dbadd60c6615b2", diff --git a/build/node_modules/one-time/LICENSE b/build/node_modules/one-time/LICENSE new file mode 100644 index 00000000..6dc9316a --- /dev/null +++ b/build/node_modules/one-time/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Unshift.io, Arnout Kazemier, the 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. + diff --git a/build/node_modules/one-time/README.md b/build/node_modules/one-time/README.md new file mode 100644 index 00000000..75143adb --- /dev/null +++ b/build/node_modules/one-time/README.md @@ -0,0 +1,88 @@ +# one-time + +Call the supplied function exactly one time. This prevents double callback +execution. This module can be used on both Node.js, React-Native, or browsers +using Browserify. No magical ES5/6 methods used unlike the `once` module does +(except for the async version). + +## Installation + +This module is published to the public npm registry and can be installed +by running: + +```sh +npm install --save one-time +``` + +## Usage (normal) + +Simply supply the function with the function that should only be called one +time: + +```js +var one = require('one-time'); + +function load(file, fn) { + fn = one(fn); + + eventemitter.once('load', fn); + eventemitter.once('error', fn); + + // do stuff + eventemitter.emit('error', new Error('Failed to load, but still finished')); + eventemitter.emit('load'); +} + +function example(fn) { + fn = one(fn); + + fn(); + fn('also receives all arguments'); + fn('it returns the same value') === 'bar'; + fn('never'); + fn('gonna'); + fn('give'); + fn('you'); + fn('up'); +} + +example(function () { + return 'bar' +}); +``` + +## Usage (async) + +The same pattern is available for **async** functions as well, for that you +should import that `one-time/async` version instead. This one is optimized +for **async** and **await** support. It following exactly the same as the +normal version but assumes it's an `async function () {}` that it's wrapping +instead of a regular function, and it will return an `async function() {}` +instead of a regular function. + +```js +import one from 'one-time/async'; + +const fn = one(async function () { + return await example(); +}); + +await fn(); +await fn(); +await fn(); +``` + +### Why not `once`? + +The main reason is that `once` cannot be used in a browser environment unless +it's ES5 compatible. For a module as simple as this I find that unacceptable. In +addition to that it super heavy on the dependency side. So it's totally not +suitable to be used in client side applications. + +In addition to that we make sure that your code stays easy to debug as returned +functions are named in the same way as your supplied functions. Making heap +inspection and stack traces easier to understand. + +## License + +[MIT](LICENSE) diff --git a/build/node_modules/one-time/async.js b/build/node_modules/one-time/async.js new file mode 100644 index 00000000..7370ae31 --- /dev/null +++ b/build/node_modules/one-time/async.js @@ -0,0 +1,43 @@ +'use strict'; + +var name = require('fn.name'); + +/** + * Wrap callbacks to prevent double execution. + * + * @param {Function} fn Function that should only be called once. + * @returns {Function} A async wrapped callback which prevents multiple executions. + * @public + */ +module.exports = function one(fn) { + var called = 0 + , value; + + /** + * The function that prevents double execution. + * + * @async + * @public + */ + async function onetime() { + if (called) return value; + + called = 1; + value = await fn.apply(this, arguments); + fn = null; + + return value; + } + + // + // To make debugging more easy we want to use the name of the supplied + // function. So when you look at the functions that are assigned to event + // listeners you don't see a load of `onetime` functions but actually the + // names of the functions that this module will call. + // + // NOTE: We cannot override the `name` property, as that is `readOnly` + // property, so displayName will have to do. + // + onetime.displayName = name(fn); + return onetime; +}; diff --git a/build/node_modules/one-time/index.js b/build/node_modules/one-time/index.js new file mode 100644 index 00000000..96b2f3dc --- /dev/null +++ b/build/node_modules/one-time/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var name = require('fn.name'); + +/** + * Wrap callbacks to prevent double execution. + * + * @param {Function} fn Function that should only be called once. + * @returns {Function} A wrapped callback which prevents multiple executions. + * @public + */ +module.exports = function one(fn) { + var called = 0 + , value; + + /** + * The function that prevents double execution. + * + * @private + */ + function onetime() { + if (called) return value; + + called = 1; + value = fn.apply(this, arguments); + fn = null; + + return value; + } + + // + // To make debugging more easy we want to use the name of the supplied + // function. So when you look at the functions that are assigned to event + // listeners you don't see a load of `onetime` functions but actually the + // names of the functions that this module will call. + // + // NOTE: We cannot override the `name` property, as that is `readOnly` + // property, so displayName will have to do. + // + onetime.displayName = name(fn); + return onetime; +}; diff --git a/build/node_modules/one-time/package.json b/build/node_modules/one-time/package.json new file mode 100644 index 00000000..2a1ba3c7 --- /dev/null +++ b/build/node_modules/one-time/package.json @@ -0,0 +1,65 @@ +{ + "_from": "one-time@^1.0.0", + "_id": "one-time@1.0.0", + "_inBundle": false, + "_integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "_location": "/one-time", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "one-time@^1.0.0", + "name": "one-time", + "escapedName": "one-time", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "_shasum": "e06bc174aed214ed58edede573b433bbf827cb45", + "_spec": "one-time@^1.0.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/3rd-Eden/one-time/issues" + }, + "bundleDependencies": false, + "dependencies": { + "fn.name": "1.x.x" + }, + "deprecated": false, + "description": "Run the supplied function exactly one time (once)", + "devDependencies": { + "assume": "^2.2.0", + "mocha": "^6.1.4", + "nyc": "^14.1.0" + }, + "homepage": "https://github.com/3rd-Eden/one-time#readme", + "keywords": [ + "once", + "function", + "single", + "one", + "one-time", + "execution", + "nope" + ], + "license": "MIT", + "main": "index.js", + "name": "one-time", + "repository": { + "type": "git", + "url": "git+https://github.com/3rd-Eden/one-time.git" + }, + "scripts": { + "test": "nyc --reporter=text --reporter=json-summary npm run test:runner", + "test:runner": "mocha test.js", + "test:watch": "npm run test:runner -- --watch" + }, + "version": "1.0.0" +} diff --git a/build/node_modules/readable-stream/package.json b/build/node_modules/readable-stream/package.json index 2b1c546d..c8860037 100644 --- a/build/node_modules/readable-stream/package.json +++ b/build/node_modules/readable-stream/package.json @@ -17,7 +17,8 @@ }, "_requiredBy": [ "/concat-stream", - "/superagent" + "/superagent", + "/winston-transport" ], "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", "_shasum": "1eca1cf711aef814c04f62252a36a62f6cb23b57", diff --git a/build/node_modules/simple-swizzle/LICENSE b/build/node_modules/simple-swizzle/LICENSE new file mode 100644 index 00000000..1b77e5be --- /dev/null +++ b/build/node_modules/simple-swizzle/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Josh Junon + +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. diff --git a/build/node_modules/simple-swizzle/README.md b/build/node_modules/simple-swizzle/README.md new file mode 100644 index 00000000..7624577b --- /dev/null +++ b/build/node_modules/simple-swizzle/README.md @@ -0,0 +1,39 @@ +# simple-swizzle [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-simple-swizzle.svg?style=flat-square)](https://travis-ci.org/Qix-/node-simple-swizzle) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-simple-swizzle.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-simple-swizzle) + +> [Swizzle](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) your function arguments; pass in mixed arrays/values and get a clean array + +## Usage + +```js +var swizzle = require('simple-swizzle'); + +function myFunc() { + var args = swizzle(arguments); + // ... + return args; +} + +myFunc(1, [2, 3], 4); // [1, 2, 3, 4] +myFunc(1, 2, 3, 4); // [1, 2, 3, 4] +myFunc([1, 2, 3, 4]); // [1, 2, 3, 4] +``` + +Functions can also be wrapped to automatically swizzle arguments and be passed +the resulting array. + +```js +var swizzle = require('simple-swizzle'); + +var swizzledFn = swizzle.wrap(function (args) { + // ... + return args; +}); + +swizzledFn(1, [2, 3], 4); // [1, 2, 3, 4] +swizzledFn(1, 2, 3, 4); // [1, 2, 3, 4] +swizzledFn([1, 2, 3, 4]); // [1, 2, 3, 4] +``` + +## License +Licensed under the [MIT License](http://opensource.org/licenses/MIT). +You can find a copy of it in [LICENSE](LICENSE). diff --git a/build/node_modules/simple-swizzle/index.js b/build/node_modules/simple-swizzle/index.js new file mode 100644 index 00000000..4d6b8ff7 --- /dev/null +++ b/build/node_modules/simple-swizzle/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var isArrayish = require('is-arrayish'); + +var concat = Array.prototype.concat; +var slice = Array.prototype.slice; + +var swizzle = module.exports = function swizzle(args) { + var results = []; + + for (var i = 0, len = args.length; i < len; i++) { + var arg = args[i]; + + if (isArrayish(arg)) { + // http://jsperf.com/javascript-array-concat-vs-push/98 + results = concat.call(results, slice.call(arg)); + } else { + results.push(arg); + } + } + + return results; +}; + +swizzle.wrap = function (fn) { + return function () { + return fn(swizzle(arguments)); + }; +}; diff --git a/build/node_modules/simple-swizzle/package.json b/build/node_modules/simple-swizzle/package.json new file mode 100644 index 00000000..2e004c27 --- /dev/null +++ b/build/node_modules/simple-swizzle/package.json @@ -0,0 +1,71 @@ +{ + "_from": "simple-swizzle@^0.2.2", + "_id": "simple-swizzle@0.2.2", + "_inBundle": false, + "_integrity": "sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=", + "_location": "/simple-swizzle", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "simple-swizzle@^0.2.2", + "name": "simple-swizzle", + "escapedName": "simple-swizzle", + "rawSpec": "^0.2.2", + "saveSpec": null, + "fetchSpec": "^0.2.2" + }, + "_requiredBy": [ + "/color-string" + ], + "_resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "_shasum": "a4da6b635ffcccca33f70d17cb92592de95e557a", + "_spec": "simple-swizzle@^0.2.2", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/color-string", + "author": { + "name": "Qix", + "url": "http://github.com/qix-" + }, + "bugs": { + "url": "https://github.com/qix-/node-simple-swizzle/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-arrayish": "^0.3.1" + }, + "deprecated": false, + "description": "Simply swizzle your arguments", + "devDependencies": { + "coffee-script": "^1.9.3", + "coveralls": "^2.11.2", + "istanbul": "^0.3.17", + "mocha": "^2.2.5", + "should": "^7.0.1", + "xo": "^0.7.1" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/qix-/node-simple-swizzle#readme", + "keywords": [ + "argument", + "arguments", + "swizzle", + "swizzling", + "parameter", + "parameters", + "mixed", + "array" + ], + "license": "MIT", + "name": "simple-swizzle", + "repository": { + "type": "git", + "url": "git+https://github.com/qix-/node-simple-swizzle.git" + }, + "scripts": { + "pretest": "xo", + "test": "mocha --compilers coffee:coffee-script/register" + }, + "version": "0.2.2" +} diff --git a/build/node_modules/stack-trace/.npmignore b/build/node_modules/stack-trace/.npmignore new file mode 100644 index 00000000..b59f7e3a --- /dev/null +++ b/build/node_modules/stack-trace/.npmignore @@ -0,0 +1 @@ +test/ \ No newline at end of file diff --git a/build/node_modules/stack-trace/License b/build/node_modules/stack-trace/License new file mode 100644 index 00000000..11ec094e --- /dev/null +++ b/build/node_modules/stack-trace/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com) + + 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. diff --git a/build/node_modules/stack-trace/Makefile b/build/node_modules/stack-trace/Makefile new file mode 100644 index 00000000..a7ce31d3 --- /dev/null +++ b/build/node_modules/stack-trace/Makefile @@ -0,0 +1,11 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +release: + git push + git push --tags + npm publish . + +.PHONY: test diff --git a/build/node_modules/stack-trace/Readme.md b/build/node_modules/stack-trace/Readme.md new file mode 100644 index 00000000..fcd1b97c --- /dev/null +++ b/build/node_modules/stack-trace/Readme.md @@ -0,0 +1,98 @@ +# stack-trace + +Get v8 stack traces as an array of CallSite objects. + +## Install + +``` bash +npm install stack-trace +``` + +## Usage + +The stack-trace module makes it easy for you to capture the current stack: + +``` javascript +var stackTrace = require('stack-trace'); +var trace = stackTrace.get(); + +require('assert').strictEqual(trace[0].getFileName(), __filename); +``` + +However, sometimes you have already popped the stack you are interested in, +and all you have left is an `Error` object. This module can help: + +``` javascript +var stackTrace = require('stack-trace'); +var err = new Error('something went wrong'); +var trace = stackTrace.parse(err); + +require('assert').strictEqual(trace[0].getFileName(), __filename); +``` + +Please note that parsing the `Error#stack` property is not perfect, only +certain properties can be retrieved with it as noted in the API docs below. + +## Long stack traces + +stack-trace works great with [long-stack-traces][], when parsing an `err.stack` +that has crossed the event loop boundary, a `CallSite` object returning +`'----------------------------------------'` for `getFileName()` is created. +All other methods of the event loop boundary call site return `null`. + +[long-stack-traces]: https://github.com/tlrobinson/long-stack-traces + +## API + +### stackTrace.get([belowFn]) + +Returns an array of `CallSite` objects, where element `0` is the current call +site. + +When passing a function on the current stack as the `belowFn` parameter, the +returned array will only include `CallSite` objects below this function. + +### stackTrace.parse(err) + +Parses the `err.stack` property of an `Error` object into an array compatible +with those returned by `stackTrace.get()`. However, only the following methods +are implemented on the returned `CallSite` objects. + +* getTypeName +* getFunctionName +* getMethodName +* getFileName +* getLineNumber +* getColumnNumber +* isNative + +Note: Except `getFunctionName()`, all of the above methods return exactly the +same values as you would get from `stackTrace.get()`. `getFunctionName()` +is sometimes a little different, but still useful. + +### CallSite + +The official v8 CallSite object API can be found [here][v8stackapi]. A quick +excerpt: + +> A CallSite object defines the following methods: +> +> * **getThis**: returns the value of this +> * **getTypeName**: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. +> * **getFunction**: returns the current function +> * **getFunctionName**: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. +> * **getMethodName**: returns the name of the property of this or one of its prototypes that holds the current function +> * **getFileName**: if this function was defined in a script returns the name of the script +> * **getLineNumber**: if this function was defined in a script returns the current line number +> * **getColumnNumber**: if this function was defined in a script returns the current column number +> * **getEvalOrigin**: if this function was created using a call to eval returns a CallSite object representing the location where eval was called +> * **isToplevel**: is this a toplevel invocation, that is, is this the global object? +> * **isEval**: does this call take place in code defined by a call to eval? +> * **isNative**: is this call in native V8 code? +> * **isConstructor**: is this a constructor call? + +[v8stackapi]: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + +## License + +stack-trace is licensed under the MIT license. diff --git a/build/node_modules/stack-trace/lib/stack-trace.js b/build/node_modules/stack-trace/lib/stack-trace.js new file mode 100644 index 00000000..cbadd58f --- /dev/null +++ b/build/node_modules/stack-trace/lib/stack-trace.js @@ -0,0 +1,136 @@ +exports.get = function(belowFn) { + var oldLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + + var dummyObject = {}; + + var v8Handler = Error.prepareStackTrace; + Error.prepareStackTrace = function(dummyObject, v8StackTrace) { + return v8StackTrace; + }; + Error.captureStackTrace(dummyObject, belowFn || exports.get); + + var v8StackTrace = dummyObject.stack; + Error.prepareStackTrace = v8Handler; + Error.stackTraceLimit = oldLimit; + + return v8StackTrace; +}; + +exports.parse = function(err) { + if (!err.stack) { + return []; + } + + var self = this; + var lines = err.stack.split('\n').slice(1); + + return lines + .map(function(line) { + if (line.match(/^\s*[-]{4,}$/)) { + return self._createParsedCallSite({ + fileName: line, + lineNumber: null, + functionName: null, + typeName: null, + methodName: null, + columnNumber: null, + 'native': null, + }); + } + + var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return; + } + + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = (lineMatch[5] === 'native'); + + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart-1] == '.') + methodStart--; + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = null; + } + + if (method) { + typeName = object; + methodName = method; + } + + if (method === '') { + methodName = null; + functionName = null; + } + + var properties = { + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3], 10) || null, + functionName: functionName, + typeName: typeName, + methodName: methodName, + columnNumber: parseInt(lineMatch[4], 10) || null, + 'native': isNative, + }; + + return self._createParsedCallSite(properties); + }) + .filter(function(callSite) { + return !!callSite; + }); +}; + +function CallSite(properties) { + for (var property in properties) { + this[property] = properties[property]; + } +} + +var strProperties = [ + 'this', + 'typeName', + 'functionName', + 'methodName', + 'fileName', + 'lineNumber', + 'columnNumber', + 'function', + 'evalOrigin' +]; +var boolProperties = [ + 'topLevel', + 'eval', + 'native', + 'constructor' +]; +strProperties.forEach(function (property) { + CallSite.prototype[property] = null; + CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () { + return this[property]; + } +}); +boolProperties.forEach(function (property) { + CallSite.prototype[property] = false; + CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () { + return this[property]; + } +}); + +exports._createParsedCallSite = function(properties) { + return new CallSite(properties); +}; diff --git a/build/node_modules/stack-trace/package.json b/build/node_modules/stack-trace/package.json new file mode 100644 index 00000000..3c63c0c0 --- /dev/null +++ b/build/node_modules/stack-trace/package.json @@ -0,0 +1,53 @@ +{ + "_from": "stack-trace@0.0.x", + "_id": "stack-trace@0.0.10", + "_inBundle": false, + "_integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "_location": "/stack-trace", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "stack-trace@0.0.x", + "name": "stack-trace", + "escapedName": "stack-trace", + "rawSpec": "0.0.x", + "saveSpec": null, + "fetchSpec": "0.0.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "_shasum": "547c70b347e8d32b4e108ea1a2a159e5fdde19c0", + "_spec": "stack-trace@0.0.x", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "bugs": { + "url": "https://github.com/felixge/node-stack-trace/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Get v8 stack traces as an array of CallSite objects.", + "devDependencies": { + "far": "0.0.3", + "long-stack-traces": "0.1.2" + }, + "engines": { + "node": "*" + }, + "homepage": "https://github.com/felixge/node-stack-trace", + "license": "MIT", + "main": "./lib/stack-trace", + "name": "stack-trace", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-stack-trace.git" + }, + "version": "0.0.10" +} diff --git a/build/node_modules/string_decoder/package.json b/build/node_modules/string_decoder/package.json index ccce3980..6cdc4471 100644 --- a/build/node_modules/string_decoder/package.json +++ b/build/node_modules/string_decoder/package.json @@ -18,7 +18,8 @@ "_requiredBy": [ "/browserify-sign/readable-stream", "/hash-base/readable-stream", - "/readable-stream" + "/readable-stream", + "/winston/readable-stream" ], "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "_shasum": "9cf1611ba62685d7030ae9e4ba34149c3af03fc8", diff --git a/build/node_modules/text-hex/LICENSE b/build/node_modules/text-hex/LICENSE new file mode 100644 index 00000000..bfb9d773 --- /dev/null +++ b/build/node_modules/text-hex/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 Arnout Kazemier + +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. diff --git a/build/node_modules/text-hex/README.md b/build/node_modules/text-hex/README.md new file mode 100644 index 00000000..bb867054 --- /dev/null +++ b/build/node_modules/text-hex/README.md @@ -0,0 +1,20 @@ +# text-hex + +Transforms a given piece of text to a hex color. + +## Install + +``` +npm install text-hex +``` + +## Usage + +```js +var hex = require('text-hex'); +console.log(hex('foo')); +``` + +## License + +MIT diff --git a/build/node_modules/text-hex/index.js b/build/node_modules/text-hex/index.js new file mode 100644 index 00000000..5bec54d3 --- /dev/null +++ b/build/node_modules/text-hex/index.js @@ -0,0 +1,24 @@ +'use strict'; + +/*** + * Convert string to hex color. + * + * @param {String} str Text to hash and convert to hex. + * @returns {String} + * @api public + */ +module.exports = function hex(str) { + for ( + var i = 0, hash = 0; + i < str.length; + hash = str.charCodeAt(i++) + ((hash << 5) - hash) + ); + + var color = Math.floor( + Math.abs( + (Math.sin(hash) * 10000) % 1 * 16777216 + ) + ).toString(16); + + return '#' + Array(6 - color.length + 1).join('0') + color; +}; diff --git a/build/node_modules/text-hex/package.json b/build/node_modules/text-hex/package.json new file mode 100644 index 00000000..7b5ba34d --- /dev/null +++ b/build/node_modules/text-hex/package.json @@ -0,0 +1,57 @@ +{ + "_from": "text-hex@1.0.x", + "_id": "text-hex@1.0.0", + "_inBundle": false, + "_integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==", + "_location": "/text-hex", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "text-hex@1.0.x", + "name": "text-hex", + "escapedName": "text-hex", + "rawSpec": "1.0.x", + "saveSpec": null, + "fetchSpec": "1.0.x" + }, + "_requiredBy": [ + "/colorspace" + ], + "_resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "_shasum": "69dc9c1b17446ee79a92bf5b884bb4b9127506f5", + "_spec": "text-hex@1.0.x", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/colorspace", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/3rd-Eden/text-hex/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Generate a hex color from the given text", + "devDependencies": { + "assume": "2.1.x", + "mocha": "5.2.x", + "pre-commit": "1.2.x" + }, + "homepage": "https://github.com/3rd-Eden/text-hex", + "keywords": [ + "css", + "color", + "hex", + "text" + ], + "license": "MIT", + "main": "index.js", + "name": "text-hex", + "repository": { + "type": "git", + "url": "git+https://github.com/3rd-Eden/text-hex.git" + }, + "scripts": { + "test": "mocha --reporter spec --ui bdd test.js" + }, + "version": "1.0.0" +} diff --git a/build/node_modules/text-hex/test.js b/build/node_modules/text-hex/test.js new file mode 100644 index 00000000..2adbbd1b --- /dev/null +++ b/build/node_modules/text-hex/test.js @@ -0,0 +1,11 @@ +describe('text-hex', function () { + 'use strict'; + + var assume = require('assume') + , hex = require('./'); + + it('is a 6 digit hex', function () { + assume(hex('a')).to.have.length(7); // including a # + assume(hex('a244fdafadfa4 adfau8fa a u adf8a0')).to.have.length(7); + }); +}); diff --git a/build/node_modules/triple-beam/.eslintrc b/build/node_modules/triple-beam/.eslintrc new file mode 100644 index 00000000..9dafa5ab --- /dev/null +++ b/build/node_modules/triple-beam/.eslintrc @@ -0,0 +1,7 @@ +{ + "extends": "populist", + "rules": { + "one-var": ["error", { var: "never", let: "never", const: "never" }], + "strict": 0 + } +} diff --git a/build/node_modules/triple-beam/.gitattributes b/build/node_modules/triple-beam/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/build/node_modules/triple-beam/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/build/node_modules/triple-beam/.travis.yml b/build/node_modules/triple-beam/.travis.yml new file mode 100644 index 00000000..eccd47c0 --- /dev/null +++ b/build/node_modules/triple-beam/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" + +before_install: + - travis_retry npm install + +script: + - npm test + +notifications: + email: + - travis@nodejitsu.com + irc: "irc.freenode.org#nodejitsu" diff --git a/build/node_modules/triple-beam/CHANGELOG.md b/build/node_modules/triple-beam/CHANGELOG.md new file mode 100644 index 00000000..9c5e54ac --- /dev/null +++ b/build/node_modules/triple-beam/CHANGELOG.md @@ -0,0 +1,22 @@ +# CHANGELOG + +### 1.3.0 + +- [#4] Add `SPLAT` symbol. +- [#3] Add linting & TravisCI. + +### 1.2.0 + +- [#2] Move configs from `winston.config.{npm,syslog,npm}` into `triple-beam`. + +### 1.1.0 + +- Expose a `MESSAGE` Symbol, nothing more. + +### 1.0.1 + +- Use `Symbol.for` because that is how they work apparently. + +### 1.0.0 + +- Initial version. Defines a `LEVEL` Symbol, nothing more. diff --git a/build/node_modules/triple-beam/LICENSE b/build/node_modules/triple-beam/LICENSE new file mode 100644 index 00000000..1a1238aa --- /dev/null +++ b/build/node_modules/triple-beam/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 winstonjs + +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. diff --git a/build/node_modules/triple-beam/README.md b/build/node_modules/triple-beam/README.md new file mode 100644 index 00000000..19543164 --- /dev/null +++ b/build/node_modules/triple-beam/README.md @@ -0,0 +1,34 @@ +# triple-beam + +Definitions of levels for logging purposes & shareable Symbol constants. + +## Usage + +``` js +const { LEVEL } = require('triple-beam'); +const colors = require('colors/safe'); + +const info = { + [LEVEL]: 'error', + level: 'error', + message: 'hey a logging message!' +}; + +// Colorize your log level! +info.level = colors.green(info.level); + +// And still have an unmutated copy of your level! +console.log(info.level === 'error'); // false +console.log(info[LEVEL] === 'error'); // true +``` + +## Tests + +Tests are written with `mocha`, `assume`, and `nyc`. They can be run with `npm`: + +``` +npm test +``` + +##### LICENSE: MIT +##### AUTHOR: [Charlie Robbins](https://github.com/indexzero) diff --git a/build/node_modules/triple-beam/config/cli.js b/build/node_modules/triple-beam/config/cli.js new file mode 100644 index 00000000..028c117e --- /dev/null +++ b/build/node_modules/triple-beam/config/cli.js @@ -0,0 +1,42 @@ +/** + * cli.js: Config that conform to commonly used CLI logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Default levels for the CLI configuration. + * @type {Object} + */ +exports.levels = { + error: 0, + warn: 1, + help: 2, + data: 3, + info: 4, + debug: 5, + prompt: 6, + verbose: 7, + input: 8, + silly: 9 +}; + +/** + * Default colors for the CLI configuration. + * @type {Object} + */ +exports.colors = { + error: 'red', + warn: 'yellow', + help: 'cyan', + data: 'grey', + info: 'green', + debug: 'blue', + prompt: 'grey', + verbose: 'cyan', + input: 'grey', + silly: 'magenta' +}; diff --git a/build/node_modules/triple-beam/config/index.js b/build/node_modules/triple-beam/config/index.js new file mode 100644 index 00000000..96b6566d --- /dev/null +++ b/build/node_modules/triple-beam/config/index.js @@ -0,0 +1,32 @@ +/** + * index.js: Default settings for all levels that winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Export config set for the CLI. + * @type {Object} + */ +Object.defineProperty(exports, 'cli', { + value: require('./cli') +}); + +/** + * Export config set for npm. + * @type {Object} + */ +Object.defineProperty(exports, 'npm', { + value: require('./npm') +}); + +/** + * Export config set for the syslog. + * @type {Object} + */ +Object.defineProperty(exports, 'syslog', { + value: require('./syslog') +}); diff --git a/build/node_modules/triple-beam/config/npm.js b/build/node_modules/triple-beam/config/npm.js new file mode 100644 index 00000000..01f88ab4 --- /dev/null +++ b/build/node_modules/triple-beam/config/npm.js @@ -0,0 +1,36 @@ +/** + * npm.js: Config that conform to npm logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Default levels for the npm configuration. + * @type {Object} + */ +exports.levels = { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 +}; + +/** + * Default levels for the npm configuration. + * @type {Object} + */ +exports.colors = { + error: 'red', + warn: 'yellow', + info: 'green', + http: 'green', + verbose: 'cyan', + debug: 'blue', + silly: 'magenta' +}; diff --git a/build/node_modules/triple-beam/config/syslog.js b/build/node_modules/triple-beam/config/syslog.js new file mode 100644 index 00000000..9c7b82f5 --- /dev/null +++ b/build/node_modules/triple-beam/config/syslog.js @@ -0,0 +1,38 @@ +/** + * syslog.js: Config that conform to syslog logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * Default levels for the syslog configuration. + * @type {Object} + */ +exports.levels = { + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 +}; + +/** + * Default levels for the syslog configuration. + * @type {Object} + */ +exports.colors = { + emerg: 'red', + alert: 'yellow', + crit: 'red', + error: 'red', + warning: 'red', + notice: 'yellow', + info: 'green', + debug: 'blue' +}; diff --git a/build/node_modules/triple-beam/index.js b/build/node_modules/triple-beam/index.js new file mode 100644 index 00000000..cf89cf06 --- /dev/null +++ b/build/node_modules/triple-beam/index.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * A shareable symbol constant that can be used + * as a non-enumerable / semi-hidden level identifier + * to allow the readable level property to be mutable for + * operations like colorization + * + * @type {Symbol} + */ +Object.defineProperty(exports, 'LEVEL', { + value: Symbol.for('level') +}); + +/** + * A shareable symbol constant that can be used + * as a non-enumerable / semi-hidden message identifier + * to allow the final message property to not have + * side effects on another. + * + * @type {Symbol} + */ +Object.defineProperty(exports, 'MESSAGE', { + value: Symbol.for('message') +}); + +/** + * A shareable symbol constant that can be used + * as a non-enumerable / semi-hidden message identifier + * to allow the extracted splat property be hidden + * + * @type {Symbol} + */ +Object.defineProperty(exports, 'SPLAT', { + value: Symbol.for('splat') +}); + +/** + * A shareable object constant that can be used + * as a standard configuration for winston@3. + * + * @type {Object} + */ +Object.defineProperty(exports, 'configs', { + value: require('./config') +}); diff --git a/build/node_modules/triple-beam/package.json b/build/node_modules/triple-beam/package.json new file mode 100644 index 00000000..53bb4c71 --- /dev/null +++ b/build/node_modules/triple-beam/package.json @@ -0,0 +1,66 @@ +{ + "_from": "triple-beam@^1.3.0", + "_id": "triple-beam@1.3.0", + "_inBundle": false, + "_integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==", + "_location": "/triple-beam", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "triple-beam@^1.3.0", + "name": "triple-beam", + "escapedName": "triple-beam", + "rawSpec": "^1.3.0", + "saveSpec": null, + "fetchSpec": "^1.3.0" + }, + "_requiredBy": [ + "/logform", + "/winston", + "/winston-transport" + ], + "_resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.3.0.tgz", + "_shasum": "a595214c7298db8339eeeee083e4d10bd8cb8dd9", + "_spec": "triple-beam@^1.3.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "bugs": { + "url": "https://github.com/winstonjs/triple-beam/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Definitions of levels for logging purposes & shareable Symbol constants.", + "devDependencies": { + "assume": "^2.0.1", + "eslint-config-populist": "^4.1.0", + "mocha": "^5.1.1", + "nyc": "^11.7.1" + }, + "homepage": "https://github.com/winstonjs/triple-beam#readme", + "keywords": [ + "winstonjs", + "winston", + "logging", + "logform", + "symbols", + "logs", + "levels" + ], + "license": "MIT", + "main": "index.js", + "name": "triple-beam", + "repository": { + "type": "git", + "url": "git+https://github.com/winstonjs/triple-beam.git" + }, + "scripts": { + "lint": "populist config/*.js index.js", + "pretest": "npm run lint", + "test": "nyc mocha test.js" + }, + "version": "1.3.0" +} diff --git a/build/node_modules/triple-beam/test.js b/build/node_modules/triple-beam/test.js new file mode 100644 index 00000000..e13d4fe4 --- /dev/null +++ b/build/node_modules/triple-beam/test.js @@ -0,0 +1,98 @@ +const assume = require('assume'); +const tripleBeam = require('./'); + +describe('triple-beam', function () { + describe('LEVEL constant', function () { + it('is exposed', function () { + assume(tripleBeam.LEVEL); + }); + + it('is a Symbol', function () { + assume(tripleBeam.LEVEL).is.a('symbol'); + }); + + it('is not mutable', function () { + // + // Assert that the symbol does not change + // even though the operation does not throw. + // + const OVERWRITE = Symbol('overwrite'); + const LEVEL = tripleBeam.LEVEL; + + assume(LEVEL).not.equals(OVERWRITE); + tripleBeam.LEVEL = OVERWRITE; + assume(tripleBeam.LEVEL).equals(LEVEL); + }); + }); + + describe('MESSAGE constant', function () { + it('is exposed', function () { + assume(tripleBeam.MESSAGE); + }); + + it('is a Symbol', function () { + assume(tripleBeam.MESSAGE).is.a('symbol'); + }); + + it('is not mutable', function () { + // + // Assert that the symbol does not change + // even though the operation does not throw. + // + const OVERWRITE = Symbol('overwrite'); + const MESSAGE = tripleBeam.MESSAGE; + + assume(MESSAGE).not.equals(OVERWRITE); + tripleBeam.MESSAGE = OVERWRITE; + assume(tripleBeam.MESSAGE).equals(MESSAGE); + }); + }); + + describe('SPLAT constant', function () { + it('is exposed', function () { + assume(tripleBeam.SPLAT); + }); + + it('is a Symbol', function () { + assume(tripleBeam.SPLAT).is.a('symbol'); + }); + + it('is not mutable', function () { + // + // Assert that the symbol does not change + // even though the operation does not throw. + // + const OVERWRITE = Symbol('overwrite'); + const SPLAT = tripleBeam.SPLAT; + + assume(SPLAT).not.equals(OVERWRITE); + tripleBeam.SPLAT = OVERWRITE; + assume(tripleBeam.SPLAT).equals(SPLAT); + }); + }); + + describe('configs constant', function () { + it('is exposed', function () { + assume(tripleBeam.configs); + }); + + it('is a Symbol', function () { + assume(tripleBeam.configs).is.an('Object'); + }); + + it('is not mutable', function () { + // + // Assert that the object does not change + // even though the operation does not throw. + // + const overwrite = { + overwrite: 'overwrite' + }; + const configs = tripleBeam.configs; + + assume(configs).not.equals(overwrite); + tripleBeam.configs = overwrite; + assume(tripleBeam.configs).equals(configs); + }); + }); +}); diff --git a/build/node_modules/util-deprecate/package.json b/build/node_modules/util-deprecate/package.json index 12ecad16..77d05cd1 100644 --- a/build/node_modules/util-deprecate/package.json +++ b/build/node_modules/util-deprecate/package.json @@ -18,7 +18,8 @@ "_requiredBy": [ "/browserify-sign/readable-stream", "/hash-base/readable-stream", - "/readable-stream" + "/readable-stream", + "/winston/readable-stream" ], "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", diff --git a/build/node_modules/winston-transport/.babelrc b/build/node_modules/winston-transport/.babelrc new file mode 100644 index 00000000..002b4aa0 --- /dev/null +++ b/build/node_modules/winston-transport/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["env"] +} diff --git a/build/node_modules/winston-transport/.eslintrc b/build/node_modules/winston-transport/.eslintrc new file mode 100644 index 00000000..9dafa5ab --- /dev/null +++ b/build/node_modules/winston-transport/.eslintrc @@ -0,0 +1,7 @@ +{ + "extends": "populist", + "rules": { + "one-var": ["error", { var: "never", let: "never", const: "never" }], + "strict": 0 + } +} diff --git a/build/node_modules/winston-transport/.gitattributes b/build/node_modules/winston-transport/.gitattributes new file mode 100644 index 00000000..1a6bd458 --- /dev/null +++ b/build/node_modules/winston-transport/.gitattributes @@ -0,0 +1 @@ +package-lock.json binary diff --git a/build/node_modules/winston-transport/.nyc_output/1c69f3e4-4c25-457d-9df5-dfa761729528.json b/build/node_modules/winston-transport/.nyc_output/1c69f3e4-4c25-457d-9df5-dfa761729528.json new file mode 100644 index 00000000..85e1d408 --- /dev/null +++ b/build/node_modules/winston-transport/.nyc_output/1c69f3e4-4c25-457d-9df5-dfa761729528.json @@ -0,0 +1 @@ +{"/home/dabh/winston-transport/index.js":{"path":"/home/dabh/winston-transport/index.js","statementMap":{"0":{"start":{"line":3,"column":13},"end":{"line":3,"column":28}},"1":{"start":{"line":4,"column":17},"end":{"line":4,"column":52}},"2":{"start":{"line":5,"column":18},"end":{"line":5,"column":40}},"3":{"start":{"line":18,"column":24},"end":{"line":54,"column":1}},"4":{"start":{"line":19,"column":2},"end":{"line":19,"column":82}},"5":{"start":{"line":21,"column":2},"end":{"line":21,"column":31}},"6":{"start":{"line":22,"column":2},"end":{"line":22,"column":29}},"7":{"start":{"line":23,"column":2},"end":{"line":23,"column":51}},"8":{"start":{"line":24,"column":2},"end":{"line":24,"column":51}},"9":{"start":{"line":25,"column":2},"end":{"line":25,"column":31}},"10":{"start":{"line":27,"column":2},"end":{"line":27,"column":42}},"11":{"start":{"line":27,"column":19},"end":{"line":27,"column":42}},"12":{"start":{"line":28,"column":2},"end":{"line":28,"column":45}},"13":{"start":{"line":28,"column":20},"end":{"line":28,"column":45}},"14":{"start":{"line":29,"column":2},"end":{"line":29,"column":48}},"15":{"start":{"line":29,"column":21},"end":{"line":29,"column":48}},"16":{"start":{"line":32,"column":2},"end":{"line":39,"column":5}},"17":{"start":{"line":37,"column":4},"end":{"line":37,"column":32}},"18":{"start":{"line":38,"column":4},"end":{"line":38,"column":25}},"19":{"start":{"line":42,"column":2},"end":{"line":53,"column":5}},"20":{"start":{"line":47,"column":4},"end":{"line":52,"column":5}},"21":{"start":{"line":48,"column":6},"end":{"line":48,"column":25}},"22":{"start":{"line":49,"column":6},"end":{"line":51,"column":7}},"23":{"start":{"line":50,"column":8},"end":{"line":50,"column":21}},"24":{"start":{"line":59,"column":0},"end":{"line":59,"column":41}},"25":{"start":{"line":69,"column":0},"end":{"line":107,"column":2}},"26":{"start":{"line":70,"column":2},"end":{"line":72,"column":3}},"27":{"start":{"line":71,"column":4},"end":{"line":71,"column":26}},"28":{"start":{"line":78,"column":16},"end":{"line":78,"column":64}},"29":{"start":{"line":80,"column":2},"end":{"line":104,"column":3}},"30":{"start":{"line":81,"column":4},"end":{"line":83,"column":5}},"31":{"start":{"line":82,"column":6},"end":{"line":82,"column":38}},"32":{"start":{"line":90,"column":4},"end":{"line":94,"column":5}},"33":{"start":{"line":91,"column":6},"end":{"line":91,"column":88}},"34":{"start":{"line":93,"column":6},"end":{"line":93,"column":21}},"35":{"start":{"line":96,"column":4},"end":{"line":101,"column":5}},"36":{"start":{"line":98,"column":6},"end":{"line":98,"column":17}},"37":{"start":{"line":99,"column":6},"end":{"line":99,"column":35}},"38":{"start":{"line":99,"column":20},"end":{"line":99,"column":35}},"39":{"start":{"line":100,"column":6},"end":{"line":100,"column":13}},"40":{"start":{"line":103,"column":4},"end":{"line":103,"column":43}},"41":{"start":{"line":106,"column":2},"end":{"line":106,"column":24}},"42":{"start":{"line":117,"column":0},"end":{"line":166,"column":2}},"43":{"start":{"line":118,"column":2},"end":{"line":128,"column":3}},"44":{"start":{"line":119,"column":18},"end":{"line":119,"column":51}},"45":{"start":{"line":120,"column":4},"end":{"line":122,"column":5}},"46":{"start":{"line":121,"column":6},"end":{"line":121,"column":28}},"47":{"start":{"line":127,"column":4},"end":{"line":127,"column":38}},"48":{"start":{"line":130,"column":2},"end":{"line":163,"column":3}},"49":{"start":{"line":130,"column":15},"end":{"line":130,"column":16}},"50":{"start":{"line":131,"column":4},"end":{"line":131,"column":43}},"51":{"start":{"line":131,"column":34},"end":{"line":131,"column":43}},"52":{"start":{"line":133,"column":4},"end":{"line":136,"column":5}},"53":{"start":{"line":134,"column":6},"end":{"line":134,"column":52}},"54":{"start":{"line":135,"column":6},"end":{"line":135,"column":15}},"55":{"start":{"line":143,"column":4},"end":{"line":150,"column":5}},"56":{"start":{"line":144,"column":6},"end":{"line":147,"column":8}},"57":{"start":{"line":149,"column":6},"end":{"line":149,"column":21}},"58":{"start":{"line":152,"column":4},"end":{"line":162,"column":5}},"59":{"start":{"line":154,"column":6},"end":{"line":154,"column":27}},"60":{"start":{"line":155,"column":6},"end":{"line":159,"column":7}},"61":{"start":{"line":157,"column":8},"end":{"line":157,"column":23}},"62":{"start":{"line":158,"column":8},"end":{"line":158,"column":23}},"63":{"start":{"line":161,"column":6},"end":{"line":161,"column":48}},"64":{"start":{"line":165,"column":2},"end":{"line":165,"column":24}},"65":{"start":{"line":177,"column":0},"end":{"line":202,"column":2}},"66":{"start":{"line":178,"column":15},"end":{"line":178,"column":26}},"67":{"start":{"line":179,"column":2},"end":{"line":181,"column":3}},"68":{"start":{"line":180,"column":4},"end":{"line":180,"column":17}},"69":{"start":{"line":185,"column":16},"end":{"line":185,"column":64}},"70":{"start":{"line":188,"column":2},"end":{"line":199,"column":3}},"71":{"start":{"line":196,"column":4},"end":{"line":198,"column":5}},"72":{"start":{"line":197,"column":6},"end":{"line":197,"column":18}},"73":{"start":{"line":201,"column":2},"end":{"line":201,"column":15}},"74":{"start":{"line":208,"column":0},"end":{"line":211,"column":2}},"75":{"start":{"line":210,"column":2},"end":{"line":210,"column":24}},"76":{"start":{"line":215,"column":0},"end":{"line":215,"column":59}}},"fnMap":{"0":{"name":"TransportStream","decl":{"start":{"line":18,"column":50},"end":{"line":18,"column":65}},"loc":{"start":{"line":18,"column":80},"end":{"line":54,"column":1}},"line":18},"1":{"name":"(anonymous_1)","decl":{"start":{"line":32,"column":20},"end":{"line":32,"column":21}},"loc":{"start":{"line":32,"column":30},"end":{"line":39,"column":3}},"line":32},"2":{"name":"(anonymous_2)","decl":{"start":{"line":42,"column":22},"end":{"line":42,"column":23}},"loc":{"start":{"line":42,"column":29},"end":{"line":53,"column":3}},"line":42},"3":{"name":"_write","decl":{"start":{"line":69,"column":44},"end":{"line":69,"column":50}},"loc":{"start":{"line":69,"column":72},"end":{"line":107,"column":1}},"line":69},"4":{"name":"_writev","decl":{"start":{"line":117,"column":45},"end":{"line":117,"column":52}},"loc":{"start":{"line":117,"column":71},"end":{"line":166,"column":1}},"line":117},"5":{"name":"_accept","decl":{"start":{"line":177,"column":45},"end":{"line":177,"column":52}},"loc":{"start":{"line":177,"column":60},"end":{"line":202,"column":1}},"line":177},"6":{"name":"_nop","decl":{"start":{"line":208,"column":42},"end":{"line":208,"column":46}},"loc":{"start":{"line":208,"column":49},"end":{"line":211,"column":1}},"line":208}},"branchMap":{"0":{"loc":{"start":{"line":18,"column":66},"end":{"line":18,"column":78}},"type":"default-arg","locations":[{"start":{"line":18,"column":76},"end":{"line":18,"column":78}}],"line":18},"1":{"loc":{"start":{"line":27,"column":2},"end":{"line":27,"column":42}},"type":"if","locations":[{"start":{"line":27,"column":2},"end":{"line":27,"column":42}},{"start":{"line":27,"column":2},"end":{"line":27,"column":42}}],"line":27},"2":{"loc":{"start":{"line":28,"column":2},"end":{"line":28,"column":45}},"type":"if","locations":[{"start":{"line":28,"column":2},"end":{"line":28,"column":45}},{"start":{"line":28,"column":2},"end":{"line":28,"column":45}}],"line":28},"3":{"loc":{"start":{"line":29,"column":2},"end":{"line":29,"column":48}},"type":"if","locations":[{"start":{"line":29,"column":2},"end":{"line":29,"column":48}},{"start":{"line":29,"column":2},"end":{"line":29,"column":48}}],"line":29},"4":{"loc":{"start":{"line":47,"column":4},"end":{"line":52,"column":5}},"type":"if","locations":[{"start":{"line":47,"column":4},"end":{"line":52,"column":5}},{"start":{"line":47,"column":4},"end":{"line":52,"column":5}}],"line":47},"5":{"loc":{"start":{"line":49,"column":6},"end":{"line":51,"column":7}},"type":"if","locations":[{"start":{"line":49,"column":6},"end":{"line":51,"column":7}},{"start":{"line":49,"column":6},"end":{"line":51,"column":7}}],"line":49},"6":{"loc":{"start":{"line":70,"column":2},"end":{"line":72,"column":3}},"type":"if","locations":[{"start":{"line":70,"column":2},"end":{"line":72,"column":3}},{"start":{"line":70,"column":2},"end":{"line":72,"column":3}}],"line":70},"7":{"loc":{"start":{"line":70,"column":6},"end":{"line":70,"column":72}},"type":"binary-expr","locations":[{"start":{"line":70,"column":6},"end":{"line":70,"column":17}},{"start":{"line":70,"column":22},"end":{"line":70,"column":45}},{"start":{"line":70,"column":49},"end":{"line":70,"column":71}}],"line":70},"8":{"loc":{"start":{"line":78,"column":16},"end":{"line":78,"column":64}},"type":"binary-expr","locations":[{"start":{"line":78,"column":16},"end":{"line":78,"column":26}},{"start":{"line":78,"column":31},"end":{"line":78,"column":42}},{"start":{"line":78,"column":46},"end":{"line":78,"column":63}}],"line":78},"9":{"loc":{"start":{"line":80,"column":2},"end":{"line":104,"column":3}},"type":"if","locations":[{"start":{"line":80,"column":2},"end":{"line":104,"column":3}},{"start":{"line":80,"column":2},"end":{"line":104,"column":3}}],"line":80},"10":{"loc":{"start":{"line":80,"column":6},"end":{"line":80,"column":62}},"type":"binary-expr","locations":[{"start":{"line":80,"column":6},"end":{"line":80,"column":12}},{"start":{"line":80,"column":16},"end":{"line":80,"column":62}}],"line":80},"11":{"loc":{"start":{"line":81,"column":4},"end":{"line":83,"column":5}},"type":"if","locations":[{"start":{"line":81,"column":4},"end":{"line":83,"column":5}},{"start":{"line":81,"column":4},"end":{"line":83,"column":5}}],"line":81},"12":{"loc":{"start":{"line":81,"column":8},"end":{"line":81,"column":28}},"type":"binary-expr","locations":[{"start":{"line":81,"column":8},"end":{"line":81,"column":12}},{"start":{"line":81,"column":16},"end":{"line":81,"column":28}}],"line":81},"13":{"loc":{"start":{"line":96,"column":4},"end":{"line":101,"column":5}},"type":"if","locations":[{"start":{"line":96,"column":4},"end":{"line":101,"column":5}},{"start":{"line":96,"column":4},"end":{"line":101,"column":5}}],"line":96},"14":{"loc":{"start":{"line":96,"column":8},"end":{"line":96,"column":32}},"type":"binary-expr","locations":[{"start":{"line":96,"column":8},"end":{"line":96,"column":16}},{"start":{"line":96,"column":20},"end":{"line":96,"column":32}}],"line":96},"15":{"loc":{"start":{"line":99,"column":6},"end":{"line":99,"column":35}},"type":"if","locations":[{"start":{"line":99,"column":6},"end":{"line":99,"column":35}},{"start":{"line":99,"column":6},"end":{"line":99,"column":35}}],"line":99},"16":{"loc":{"start":{"line":118,"column":2},"end":{"line":128,"column":3}},"type":"if","locations":[{"start":{"line":118,"column":2},"end":{"line":128,"column":3}},{"start":{"line":118,"column":2},"end":{"line":128,"column":3}}],"line":118},"17":{"loc":{"start":{"line":120,"column":4},"end":{"line":122,"column":5}},"type":"if","locations":[{"start":{"line":120,"column":4},"end":{"line":122,"column":5}},{"start":{"line":120,"column":4},"end":{"line":122,"column":5}}],"line":120},"18":{"loc":{"start":{"line":131,"column":4},"end":{"line":131,"column":43}},"type":"if","locations":[{"start":{"line":131,"column":4},"end":{"line":131,"column":43}},{"start":{"line":131,"column":4},"end":{"line":131,"column":43}}],"line":131},"19":{"loc":{"start":{"line":133,"column":4},"end":{"line":136,"column":5}},"type":"if","locations":[{"start":{"line":133,"column":4},"end":{"line":136,"column":5}},{"start":{"line":133,"column":4},"end":{"line":136,"column":5}}],"line":133},"20":{"loc":{"start":{"line":133,"column":8},"end":{"line":133,"column":39}},"type":"binary-expr","locations":[{"start":{"line":133,"column":8},"end":{"line":133,"column":23}},{"start":{"line":133,"column":27},"end":{"line":133,"column":39}}],"line":133},"21":{"loc":{"start":{"line":152,"column":4},"end":{"line":162,"column":5}},"type":"if","locations":[{"start":{"line":152,"column":4},"end":{"line":162,"column":5}},{"start":{"line":152,"column":4},"end":{"line":162,"column":5}}],"line":152},"22":{"loc":{"start":{"line":152,"column":8},"end":{"line":152,"column":32}},"type":"binary-expr","locations":[{"start":{"line":152,"column":8},"end":{"line":152,"column":16}},{"start":{"line":152,"column":20},"end":{"line":152,"column":32}}],"line":152},"23":{"loc":{"start":{"line":155,"column":6},"end":{"line":159,"column":7}},"type":"if","locations":[{"start":{"line":155,"column":6},"end":{"line":159,"column":7}},{"start":{"line":155,"column":6},"end":{"line":159,"column":7}}],"line":155},"24":{"loc":{"start":{"line":179,"column":2},"end":{"line":181,"column":3}},"type":"if","locations":[{"start":{"line":179,"column":2},"end":{"line":181,"column":3}},{"start":{"line":179,"column":2},"end":{"line":181,"column":3}}],"line":179},"25":{"loc":{"start":{"line":185,"column":16},"end":{"line":185,"column":64}},"type":"binary-expr","locations":[{"start":{"line":185,"column":16},"end":{"line":185,"column":26}},{"start":{"line":185,"column":31},"end":{"line":185,"column":42}},{"start":{"line":185,"column":46},"end":{"line":185,"column":63}}],"line":185},"26":{"loc":{"start":{"line":188,"column":2},"end":{"line":199,"column":3}},"type":"if","locations":[{"start":{"line":188,"column":2},"end":{"line":199,"column":3}},{"start":{"line":188,"column":2},"end":{"line":199,"column":3}}],"line":188},"27":{"loc":{"start":{"line":189,"column":4},"end":{"line":191,"column":50}},"type":"binary-expr","locations":[{"start":{"line":189,"column":4},"end":{"line":189,"column":27}},{"start":{"line":190,"column":4},"end":{"line":190,"column":10}},{"start":{"line":191,"column":4},"end":{"line":191,"column":50}}],"line":189},"28":{"loc":{"start":{"line":196,"column":4},"end":{"line":198,"column":5}},"type":"if","locations":[{"start":{"line":196,"column":4},"end":{"line":198,"column":5}},{"start":{"line":196,"column":4},"end":{"line":198,"column":5}}],"line":196},"29":{"loc":{"start":{"line":196,"column":8},"end":{"line":196,"column":56}},"type":"binary-expr","locations":[{"start":{"line":196,"column":8},"end":{"line":196,"column":29}},{"start":{"line":196,"column":33},"end":{"line":196,"column":56}}],"line":196}},"s":{"0":1,"1":1,"2":1,"3":1,"4":51,"5":51,"6":51,"7":51,"8":51,"9":51,"10":51,"11":22,"12":51,"13":1,"14":51,"15":0,"16":51,"17":5,"18":5,"19":51,"20":2,"21":2,"22":2,"23":1,"24":1,"25":1,"26":49,"27":10,"28":39,"29":39,"30":33,"31":20,"32":13,"33":13,"34":1,"35":13,"36":8,"37":8,"38":1,"39":7,"40":5,"41":6,"42":1,"43":6,"44":1,"45":1,"46":0,"47":1,"48":5,"49":5,"50":584,"51":15,"52":569,"53":400,"54":400,"55":169,"56":169,"57":1,"58":169,"59":8,"60":8,"61":1,"62":1,"63":161,"64":4,"65":1,"66":1425,"67":1425,"68":32,"69":1393,"70":1393,"71":1240,"72":1232,"73":161,"74":1,"75":416,"76":1},"f":{"0":51,"1":5,"2":2,"3":49,"4":6,"5":1425,"6":416},"b":{"0":[1],"1":[22,29],"2":[1,50],"3":[0,51],"4":[2,0],"5":[1,1],"6":[10,39],"7":[49,48,10],"8":[39,29,4],"9":[33,6],"10":[39,14],"11":[20,13],"12":[33,33],"13":[8,5],"14":[13,12],"15":[1,7],"16":[1,5],"17":[0,1],"18":[15,569],"19":[400,169],"20":[569,569],"21":[8,161],"22":[169,168],"23":[1,7],"24":[32,1393],"25":[1393,969,0],"26":[1240,153],"27":[1393,1377,408],"28":[1232,8],"29":[1240,1232]},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"a85d7d4cbe3ecd07d2a6541af717c353a56e5329","contentHash":"e10b7db1276ab5d64f307ec419edb576b7dbf449aa7e62ac6e42cce22e9c72a4"},"/home/dabh/winston-transport/legacy.js":{"path":"/home/dabh/winston-transport/legacy.js","statementMap":{"0":{"start":{"line":3,"column":13},"end":{"line":3,"column":28}},"1":{"start":{"line":4,"column":18},"end":{"line":4,"column":40}},"2":{"start":{"line":5,"column":24},"end":{"line":5,"column":37}},"3":{"start":{"line":15,"column":30},"end":{"line":39,"column":1}},"4":{"start":{"line":16,"column":2},"end":{"line":16,"column":38}},"5":{"start":{"line":17,"column":2},"end":{"line":19,"column":3}},"6":{"start":{"line":18,"column":4},"end":{"line":18,"column":79}},"7":{"start":{"line":21,"column":2},"end":{"line":21,"column":37}},"8":{"start":{"line":22,"column":2},"end":{"line":22,"column":53}},"9":{"start":{"line":23,"column":2},"end":{"line":23,"column":86}},"10":{"start":{"line":26,"column":2},"end":{"line":26,"column":21}},"11":{"start":{"line":32,"column":4},"end":{"line":32,"column":44}},"12":{"start":{"line":35,"column":2},"end":{"line":38,"column":3}},"13":{"start":{"line":36,"column":4},"end":{"line":36,"column":62}},"14":{"start":{"line":37,"column":4},"end":{"line":37,"column":62}},"15":{"start":{"line":44,"column":0},"end":{"line":44,"column":54}},"16":{"start":{"line":54,"column":0},"end":{"line":66,"column":2}},"17":{"start":{"line":55,"column":2},"end":{"line":57,"column":3}},"18":{"start":{"line":56,"column":4},"end":{"line":56,"column":26}},"19":{"start":{"line":61,"column":2},"end":{"line":63,"column":3}},"20":{"start":{"line":62,"column":4},"end":{"line":62,"column":67}},"21":{"start":{"line":65,"column":2},"end":{"line":65,"column":17}},"22":{"start":{"line":76,"column":0},"end":{"line":90,"column":2}},"23":{"start":{"line":77,"column":2},"end":{"line":87,"column":3}},"24":{"start":{"line":77,"column":15},"end":{"line":77,"column":16}},"25":{"start":{"line":78,"column":4},"end":{"line":86,"column":5}},"26":{"start":{"line":79,"column":6},"end":{"line":84,"column":8}},"27":{"start":{"line":85,"column":6},"end":{"line":85,"column":27}},"28":{"start":{"line":89,"column":2},"end":{"line":89,"column":24}},"29":{"start":{"line":97,"column":0},"end":{"line":103,"column":2}},"30":{"start":{"line":99,"column":2},"end":{"line":102,"column":16}},"31":{"start":{"line":110,"column":0},"end":{"line":119,"column":2}},"32":{"start":{"line":111,"column":2},"end":{"line":113,"column":3}},"33":{"start":{"line":112,"column":4},"end":{"line":112,"column":27}},"34":{"start":{"line":115,"column":2},"end":{"line":118,"column":3}},"35":{"start":{"line":116,"column":4},"end":{"line":116,"column":74}},"36":{"start":{"line":117,"column":4},"end":{"line":117,"column":41}}},"fnMap":{"0":{"name":"LegacyTransportStream","decl":{"start":{"line":15,"column":56},"end":{"line":15,"column":77}},"loc":{"start":{"line":15,"column":92},"end":{"line":39,"column":1}},"line":15},"1":{"name":"transportError","decl":{"start":{"line":31,"column":11},"end":{"line":31,"column":25}},"loc":{"start":{"line":31,"column":31},"end":{"line":33,"column":3}},"line":31},"2":{"name":"_write","decl":{"start":{"line":54,"column":50},"end":{"line":54,"column":56}},"loc":{"start":{"line":54,"column":78},"end":{"line":66,"column":1}},"line":54},"3":{"name":"_writev","decl":{"start":{"line":76,"column":51},"end":{"line":76,"column":58}},"loc":{"start":{"line":76,"column":77},"end":{"line":90,"column":1}},"line":76},"4":{"name":"_deprecated","decl":{"start":{"line":97,"column":55},"end":{"line":97,"column":66}},"loc":{"start":{"line":97,"column":69},"end":{"line":103,"column":1}},"line":97},"5":{"name":"close","decl":{"start":{"line":110,"column":49},"end":{"line":110,"column":54}},"loc":{"start":{"line":110,"column":57},"end":{"line":119,"column":1}},"line":110}},"branchMap":{"0":{"loc":{"start":{"line":15,"column":78},"end":{"line":15,"column":90}},"type":"default-arg","locations":[{"start":{"line":15,"column":88},"end":{"line":15,"column":90}}],"line":15},"1":{"loc":{"start":{"line":17,"column":2},"end":{"line":19,"column":3}},"type":"if","locations":[{"start":{"line":17,"column":2},"end":{"line":19,"column":3}},{"start":{"line":17,"column":2},"end":{"line":19,"column":3}}],"line":17},"2":{"loc":{"start":{"line":17,"column":6},"end":{"line":17,"column":71}},"type":"binary-expr","locations":[{"start":{"line":17,"column":6},"end":{"line":17,"column":24}},{"start":{"line":17,"column":28},"end":{"line":17,"column":71}}],"line":17},"3":{"loc":{"start":{"line":22,"column":15},"end":{"line":22,"column":52}},"type":"binary-expr","locations":[{"start":{"line":22,"column":15},"end":{"line":22,"column":25}},{"start":{"line":22,"column":29},"end":{"line":22,"column":52}}],"line":22},"4":{"loc":{"start":{"line":23,"column":26},"end":{"line":23,"column":85}},"type":"binary-expr","locations":[{"start":{"line":23,"column":26},"end":{"line":23,"column":47}},{"start":{"line":23,"column":51},"end":{"line":23,"column":85}}],"line":23},"5":{"loc":{"start":{"line":35,"column":2},"end":{"line":38,"column":3}},"type":"if","locations":[{"start":{"line":35,"column":2},"end":{"line":38,"column":3}},{"start":{"line":35,"column":2},"end":{"line":38,"column":3}}],"line":35},"6":{"loc":{"start":{"line":55,"column":2},"end":{"line":57,"column":3}},"type":"if","locations":[{"start":{"line":55,"column":2},"end":{"line":57,"column":3}},{"start":{"line":55,"column":2},"end":{"line":57,"column":3}}],"line":55},"7":{"loc":{"start":{"line":55,"column":6},"end":{"line":55,"column":72}},"type":"binary-expr","locations":[{"start":{"line":55,"column":6},"end":{"line":55,"column":17}},{"start":{"line":55,"column":22},"end":{"line":55,"column":45}},{"start":{"line":55,"column":49},"end":{"line":55,"column":71}}],"line":55},"8":{"loc":{"start":{"line":61,"column":2},"end":{"line":63,"column":3}},"type":"if","locations":[{"start":{"line":61,"column":2},"end":{"line":63,"column":3}},{"start":{"line":61,"column":2},"end":{"line":63,"column":3}}],"line":61},"9":{"loc":{"start":{"line":61,"column":6},"end":{"line":61,"column":72}},"type":"binary-expr","locations":[{"start":{"line":61,"column":6},"end":{"line":61,"column":17}},{"start":{"line":61,"column":21},"end":{"line":61,"column":72}}],"line":61},"10":{"loc":{"start":{"line":78,"column":4},"end":{"line":86,"column":5}},"type":"if","locations":[{"start":{"line":78,"column":4},"end":{"line":86,"column":5}},{"start":{"line":78,"column":4},"end":{"line":86,"column":5}}],"line":78},"11":{"loc":{"start":{"line":111,"column":2},"end":{"line":113,"column":3}},"type":"if","locations":[{"start":{"line":111,"column":2},"end":{"line":113,"column":3}},{"start":{"line":111,"column":2},"end":{"line":113,"column":3}}],"line":111},"12":{"loc":{"start":{"line":115,"column":2},"end":{"line":118,"column":3}},"type":"if","locations":[{"start":{"line":115,"column":2},"end":{"line":118,"column":3}},{"start":{"line":115,"column":2},"end":{"line":118,"column":3}}],"line":115}},"s":{"0":1,"1":1,"2":1,"3":1,"4":23,"5":23,"6":2,"7":21,"8":21,"9":21,"10":21,"11":1,"12":21,"13":18,"14":18,"15":1,"16":1,"17":29,"18":10,"19":19,"20":16,"21":19,"22":1,"23":2,"24":2,"25":415,"26":400,"27":400,"28":2,"29":1,"30":1,"31":1,"32":2,"33":2,"34":2,"35":2,"36":2},"f":{"0":23,"1":1,"2":29,"3":2,"4":1,"5":2},"b":{"0":[2],"1":[2,21],"2":[23,21],"3":[21,19],"4":[21,20],"5":[18,3],"6":[10,19],"7":[29,28,10],"8":[16,3],"9":[19,8],"10":[400,15],"11":[2,0],"12":[2,0]},"_coverageSchema":"1a1c01bbd47fc00a2c39e90264f33305004495a9","hash":"74c6fb144cc5b67d716fb0ae982125dceb920513","contentHash":"517957434acef870444e5fff09c471fe325ea34ebf5b2de92bfc012f10b13270"}} \ No newline at end of file diff --git a/build/node_modules/winston-transport/.nyc_output/processinfo/1c69f3e4-4c25-457d-9df5-dfa761729528.json b/build/node_modules/winston-transport/.nyc_output/processinfo/1c69f3e4-4c25-457d-9df5-dfa761729528.json new file mode 100644 index 00000000..20f41617 --- /dev/null +++ b/build/node_modules/winston-transport/.nyc_output/processinfo/1c69f3e4-4c25-457d-9df5-dfa761729528.json @@ -0,0 +1 @@ +{"parent":null,"pid":1693914,"argv":["/home/dabh/n/bin/node","/home/dabh/winston-transport/node_modules/.bin/mocha","test/index.test.js","test/inheritance.test.js","test/legacy.test.js"],"execArgv":[],"cwd":"/home/dabh/winston-transport","time":1592727997158,"ppid":1693903,"coverageFilename":"/home/dabh/winston-transport/.nyc_output/1c69f3e4-4c25-457d-9df5-dfa761729528.json","externalId":"","uuid":"1c69f3e4-4c25-457d-9df5-dfa761729528","files":["/home/dabh/winston-transport/index.js","/home/dabh/winston-transport/legacy.js"]} \ No newline at end of file diff --git a/build/node_modules/winston-transport/.nyc_output/processinfo/index.json b/build/node_modules/winston-transport/.nyc_output/processinfo/index.json new file mode 100644 index 00000000..a4281a60 --- /dev/null +++ b/build/node_modules/winston-transport/.nyc_output/processinfo/index.json @@ -0,0 +1 @@ +{"processes":{"1c69f3e4-4c25-457d-9df5-dfa761729528":{"parent":null,"children":[]}},"files":{"/home/dabh/winston-transport/index.js":["1c69f3e4-4c25-457d-9df5-dfa761729528"],"/home/dabh/winston-transport/legacy.js":["1c69f3e4-4c25-457d-9df5-dfa761729528"]},"externalIds":{}} \ No newline at end of file diff --git a/build/node_modules/winston-transport/.travis.yml b/build/node_modules/winston-transport/.travis.yml new file mode 100644 index 00000000..f7e50624 --- /dev/null +++ b/build/node_modules/winston-transport/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +language: node_js +node_js: + - "10" + - "12" + - "14" + +before_install: + - travis_retry npm install + +script: + - npm test + +notifications: + email: + - travis@nodejitsu.com + irc: "irc.freenode.org#nodejitsu" diff --git a/build/node_modules/winston-transport/CHANGELOG.md b/build/node_modules/winston-transport/CHANGELOG.md new file mode 100644 index 00000000..c99adb4d --- /dev/null +++ b/build/node_modules/winston-transport/CHANGELOG.md @@ -0,0 +1,115 @@ +# CHANGELOG + +### 4.4.0 (2018/12/23) + +- [#41] Support handleRejections option. +- [#42] Expose LegacyTransportStream from the base module. +- Update dependencies. + +### 4.3.0 (2018/12/23) + +- [#30] Precompile before publishing to `npm`. +- [#32] Add new option to increase default `highWaterMark` value. + +### 4.2.0 (2018/06/11) + +- [#26] Do not use copy-by-value for `this.level`. +- [#25] Wrap calls to `format.transform` with try / catch. +- [#24] Use `readable-stream` package to get the _final semantics across all versions of Node. + +### 4.1.0 (2018/05/31) + +- [#23] Revert to prototypal-based syntax for backwards compatibility. + +### 4.0.0 (2018/05/24) + +- **BREAKING** Update transports to use ES6 classes. Creation of +`TransportStream` and `LegacyTransportStream` now requires the `new` keyword. + +**No longer works** +``` js +const Transport = require('winston-transport'); +const transport = Transport({ + log: (info, callback) => { /* log something */ } +}); +``` + +**Do this instead** +``` js +const Transport = require('winston-transport'); +const transport = new Transport({ + log: (info, callback) => { /* log something */ } +}); +``` + +### 3.3.0 (2018/05/24) +**Unpublished:** overlooked that 26f816e introduced a breaking change. + +- [#21] Do not log when there is no info object. +- [#20] Add silent options to typings. +- [#19] Refactor test fixtures to use es6-classes. +- [#18] Use triple-beam for info object constants. +- [#17] Add linting and Node v10 to the travis build of the project. + +### 3.2.1 (2018/04/25) + +- [#16] Reorder in TS defs: namespace must come after class in order for delcaration merging to work as expected. + +### 3.2.0 (2018/04/22) + +- [#13] Add silent support to LegacyTransportStream. Fixes [#8]. +- [#14] Ensure that if a Transport-specific format is provided it is invoked on each chunk before passing it to `.log`. Fixes [#12]. +- [#11] Revice `d.ts` +- Add `.travis.yml`. +- Documentation updates: + - [#5] Update deprecated link. + - [#7] Correct `this` reference in `README.md` by using an arrow function. + +### 3.1.0 (2018/04/06) + +- [#10] Add `silent` option to `TransportStream`. Still needs to be implemented + for `LegacyTransportStream`. +- Bump `mocha` to `^5.0.5`. +- Bump `nyc` to `^11.6.0`. + +### 3.0.1 (2017/10/01) + +- [#4] Use ES6-class for defining Transport in `README.md`. +- [#4] Do not overwrite prototypal methods unless they are provided in the options. + +### 3.0.0 (2017/09/29) + +- Use `Symbol.for('level')` to lookup immutable `level` on `info` objects. + +### 2.1.1 (2017/09/29) + +- Properly interact with the `{ format }`, if provided. + +### 2.1.0 (2017/09/27) + +- If a format is defined use it to mutate the info. + +### 2.0.0 (2017/04/11) + +- [#2] Final semantics for `winston-transport` base implementations: + - `TransportStream`: the new `objectMode` Writable stream which should be the base for all future Transports after `winston >= 3`. + - `LegacyTransportStream`: the backwards compatible wrap to Transports written for `winston < 3`. There isn't all that much different for those implementors except that `log(level, message, meta, callback)` is now `log(info, callback)` where `info` is the object being plumbed along the objectMode pipe-chain. This was absolutely critical to not "break the ecosystem" and give [the over 500 Transport package authors](https://www.npmjs.com/search?q=winston) an upgrade path. + - Along with all the code coverage & `WritableStream` goodies: + - 100% code coverage for `TransportStream` + - 100% code coverage for `LegacyTransportStream` + - Implementation of `_writev` for `TransportStream` + - Implementation of `_writev` for `LegacyTransportStream` + +### 1.0.2 (2015/11/30) + +- Pass the write stream callback so that we can communicate backpressure up the chain of streams. + +### 1.0.1 (2015/11/22) + +- First `require`-able version. + +### 1.0.0 (2015/11/22) + +- Initial version. + +[#2]: https://github.com/winstonjs/winston-transport/pull/2 diff --git a/build/node_modules/winston-transport/LICENSE b/build/node_modules/winston-transport/LICENSE new file mode 100644 index 00000000..64e5d87d --- /dev/null +++ b/build/node_modules/winston-transport/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Charlie Robbins & the 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. + diff --git a/build/node_modules/winston-transport/README.md b/build/node_modules/winston-transport/README.md new file mode 100644 index 00000000..1b7591eb --- /dev/null +++ b/build/node_modules/winston-transport/README.md @@ -0,0 +1,50 @@ +# winston-transport + +The base `TransportStream` implementation for `winston >= 3`. Use these to +write ecosystem Transports for `winston`. + +## Usage + +``` js +const Transport = require('winston-transport'); +const util = require('util'); + +// +// Inherit from `winston-transport` so you can take advantage +// of the base functionality and `.exceptions.handle()`. +// +module.exports = class CustomTransport extends Transport { + constructor(opts) { + super(opts); + + // + // Consume any custom options here. e.g.: + // - Connection information for databases + // - Authentication information for APIs (e.g. loggly, papertrail, + // logentries, etc.). + // + } + + log(info, callback) { + setImmediate(() => { + this.emit('logged', info); + }); + + // Perform the writing to the remote service + + callback(); + } +}; +``` + +## Tests + +Tests are written with `mocha`, `nyc`, `assume`, and +`abstract-winston-transport`. They can be run with `npm`: + +``` bash +npm test +``` + +##### Author: [Charlie Robbins](https://github.com/indexzero) +##### LICENSE: MIT diff --git a/build/node_modules/winston-transport/dist/index.js b/build/node_modules/winston-transport/dist/index.js new file mode 100644 index 00000000..2376a253 --- /dev/null +++ b/build/node_modules/winston-transport/dist/index.js @@ -0,0 +1,215 @@ +'use strict'; + +var util = require('util'); +var Writable = require('readable-stream/writable'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL; + +/** + * Constructor function for the TransportStream. This is the base prototype + * that all `winston >= 3` transports should inherit from. + * @param {Object} options - Options for this TransportStream instance + * @param {String} options.level - Highest level according to RFC5424. + * @param {Boolean} options.handleExceptions - If true, info with + * { exception: true } will be written. + * @param {Function} options.log - Custom log function for simple Transport + * creation + * @param {Function} options.close - Called on "unpipe" from parent. + */ + + +var TransportStream = module.exports = function TransportStream() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + + this.format = options.format; + this.level = options.level; + this.handleExceptions = options.handleExceptions; + this.handleRejections = options.handleRejections; + this.silent = options.silent; + + if (options.log) this.log = options.log; + if (options.logv) this.logv = options.logv; + if (options.close) this.close = options.close; + + // Get the levels from the source we are piped from. + this.once('pipe', function (logger) { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + _this.levels = logger.levels; + _this.parent = logger; + }); + + // If and/or when the transport is removed from this instance + this.once('unpipe', function (src) { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + if (src === _this.parent) { + _this.parent = null; + if (_this.close) { + _this.close(); + } + } + }); +}; + +/* + * Inherit from Writeable using Node.js built-ins + */ +util.inherits(TransportStream, Writable); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +TransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. We always + // prefer any explicit level set on the Transport itself falling back to + // any level set on the parent. + var level = this.level || this.parent && this.parent.level; + + if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (info && !this.format) { + return this.log(info, callback); + } + + var errState = void 0; + var transformed = void 0; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform(Object.assign({}, info), this.format.options); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + callback(); + if (errState) throw errState; + return; + } + + return this.log(transformed, callback); + } + + return callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +TransportStream.prototype._writev = function _writev(chunks, callback) { + if (this.logv) { + var infos = chunks.filter(this._accept, this); + if (!infos.length) { + return callback(null); + } + + // Remark (indexzero): from a performance perspective if Transport + // implementers do choose to implement logv should we make it their + // responsibility to invoke their format? + return this.logv(infos, callback); + } + + for (var i = 0; i < chunks.length; i++) { + if (!this._accept(chunks[i])) continue; + + if (chunks[i].chunk && !this.format) { + this.log(chunks[i].chunk, chunks[i].callback); + continue; + } + + var errState = void 0; + var transformed = void 0; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform(Object.assign({}, chunks[i].chunk), this.format.options); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + chunks[i].callback(); + if (errState) { + // eslint-disable-next-line callback-return + callback(null); + throw errState; + } + } else { + this.log(transformed, chunks[i].callback); + } + } + + return callback(null); +}; + +/** + * Predicate function that returns true if the specfied `info` on the + * WriteReq, `write`, should be passed down into the derived + * TransportStream's I/O via `.log(info, callback)`. + * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object + * representing the log message. + * @returns {Boolean} - Value indicating if the `write` should be accepted & + * logged. + */ +TransportStream.prototype._accept = function _accept(write) { + var info = write.chunk; + if (this.silent) { + return false; + } + + // We always prefer any explicit level set on the Transport itself + // falling back to any level set on the parent. + var level = this.level || this.parent && this.parent.level; + + // Immediately check the average case: log level filtering. + if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) { + // Ensure the info object is valid based on `{ exception }`: + // 1. { handleExceptions: true }: all `info` objects are valid + // 2. { exception: false }: accepted by all transports. + if (this.handleExceptions || info.exception !== true) { + return true; + } + } + + return false; +}; + +/** + * _nop is short for "No operation" + * @returns {Boolean} Intentionally false. + */ +TransportStream.prototype._nop = function _nop() { + // eslint-disable-next-line no-undefined + return void undefined; +}; + +// Expose legacy stream +module.exports.LegacyTransportStream = require('./legacy'); \ No newline at end of file diff --git a/build/node_modules/winston-transport/dist/legacy.js b/build/node_modules/winston-transport/dist/legacy.js new file mode 100644 index 00000000..347d6e3a --- /dev/null +++ b/build/node_modules/winston-transport/dist/legacy.js @@ -0,0 +1,116 @@ +'use strict'; + +var util = require('util'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL; + +var TransportStream = require('./'); + +/** + * Constructor function for the LegacyTransportStream. This is an internal + * wrapper `winston >= 3` uses to wrap older transports implementing + * log(level, message, meta). + * @param {Object} options - Options for this TransportStream instance. + * @param {Transpot} options.transport - winston@2 or older Transport to wrap. + */ + +var LegacyTransportStream = module.exports = function LegacyTransportStream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + TransportStream.call(this, options); + if (!options.transport || typeof options.transport.log !== 'function') { + throw new Error('Invalid transport, must be an object with a log method.'); + } + + this.transport = options.transport; + this.level = this.level || options.transport.level; + this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; + + // Display our deprecation notice. + this._deprecated(); + + // Properly bubble up errors from the transport to the + // LegacyTransportStream instance, but only once no matter how many times + // this transport is shared. + function transportError(err) { + this.emit('error', err, this.transport); + } + + if (!this.transport.__winstonError) { + this.transport.__winstonError = transportError.bind(this); + this.transport.on('error', this.transport.__winstonError); + } +}; + +/* + * Inherit from TransportStream using Node.js built-ins + */ +util.inherits(LegacyTransportStream, TransportStream); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +LegacyTransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. + if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { + this.transport.log(info[LEVEL], info.message, info, this._nop); + } + + callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { + for (var i = 0; i < chunks.length; i++) { + if (this._accept(chunks[i])) { + this.transport.log(chunks[i].chunk[LEVEL], chunks[i].chunk.message, chunks[i].chunk, this._nop); + chunks[i].callback(); + } + } + + return callback(null); +}; + +/** + * Displays a deprecation notice. Defined as a function so it can be + * overriden in tests. + * @returns {undefined} + */ +LegacyTransportStream.prototype._deprecated = function _deprecated() { + // eslint-disable-next-line no-console + console.error([this.transport.name + ' is a legacy winston transport. Consider upgrading: ', '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'].join('\n')); +}; + +/** + * Clean up error handling state on the legacy transport associated + * with this instance. + * @returns {undefined} + */ +LegacyTransportStream.prototype.close = function close() { + if (this.transport.close) { + this.transport.close(); + } + + if (this.transport.__winstonError) { + this.transport.removeListener('error', this.transport.__winstonError); + this.transport.__winstonError = null; + } +}; \ No newline at end of file diff --git a/build/node_modules/winston-transport/index.d.ts b/build/node_modules/winston-transport/index.d.ts new file mode 100644 index 00000000..ca43d6b7 --- /dev/null +++ b/build/node_modules/winston-transport/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for winston-transport 3.0 +// Project: https://github.com/winstonjs/winston-transport +// Definitions by: DABH +// Definitions: https://github.com/winstonjs/winston-transport + +/// + +import * as stream from 'stream'; +import * as logform from 'logform'; + +declare class TransportStream extends stream.Writable { + public format?: logform.Format; + public level?: string; + public silent?: boolean; + public handleExceptions?: boolean; + + constructor(opts?: TransportStream.TransportStreamOptions); + + public log?(info: any, next: () => void): any; + public logv?(info: any, next: () => void): any; + public close?(): void; +} + +declare namespace TransportStream { + interface TransportStreamOptions { + format?: logform.Format; + level?: string; + silent?: boolean; + handleExceptions?: boolean; + + log?(info: any, next: () => void): any; + logv?(info: any, next: () => void): any; + close?(): void; + } +} + +export = TransportStream; diff --git a/build/node_modules/winston-transport/index.js b/build/node_modules/winston-transport/index.js new file mode 100644 index 00000000..46531bd3 --- /dev/null +++ b/build/node_modules/winston-transport/index.js @@ -0,0 +1,215 @@ +'use strict'; + +const util = require('util'); +const Writable = require('readable-stream/writable'); +const { LEVEL } = require('triple-beam'); + +/** + * Constructor function for the TransportStream. This is the base prototype + * that all `winston >= 3` transports should inherit from. + * @param {Object} options - Options for this TransportStream instance + * @param {String} options.level - Highest level according to RFC5424. + * @param {Boolean} options.handleExceptions - If true, info with + * { exception: true } will be written. + * @param {Function} options.log - Custom log function for simple Transport + * creation + * @param {Function} options.close - Called on "unpipe" from parent. + */ +const TransportStream = module.exports = function TransportStream(options = {}) { + Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + + this.format = options.format; + this.level = options.level; + this.handleExceptions = options.handleExceptions; + this.handleRejections = options.handleRejections; + this.silent = options.silent; + + if (options.log) this.log = options.log; + if (options.logv) this.logv = options.logv; + if (options.close) this.close = options.close; + + // Get the levels from the source we are piped from. + this.once('pipe', logger => { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + this.levels = logger.levels; + this.parent = logger; + }); + + // If and/or when the transport is removed from this instance + this.once('unpipe', src => { + // Remark (indexzero): this bookkeeping can only support multiple + // Logger parents with the same `levels`. This comes into play in + // the `winston.Container` code in which `container.add` takes + // a fully realized set of options with pre-constructed TransportStreams. + if (src === this.parent) { + this.parent = null; + if (this.close) { + this.close(); + } + } + }); +}; + +/* + * Inherit from Writeable using Node.js built-ins + */ +util.inherits(TransportStream, Writable); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +TransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || (info.exception === true && !this.handleExceptions)) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. We always + // prefer any explicit level set on the Transport itself falling back to + // any level set on the parent. + const level = this.level || (this.parent && this.parent.level); + + if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (info && !this.format) { + return this.log(info, callback); + } + + let errState; + let transformed; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform(Object.assign({}, info), this.format.options); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + callback(); + if (errState) throw errState; + return; + } + + return this.log(transformed, callback); + } + + return callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +TransportStream.prototype._writev = function _writev(chunks, callback) { + if (this.logv) { + const infos = chunks.filter(this._accept, this); + if (!infos.length) { + return callback(null); + } + + // Remark (indexzero): from a performance perspective if Transport + // implementers do choose to implement logv should we make it their + // responsibility to invoke their format? + return this.logv(infos, callback); + } + + for (let i = 0; i < chunks.length; i++) { + if (!this._accept(chunks[i])) continue; + + if (chunks[i].chunk && !this.format) { + this.log(chunks[i].chunk, chunks[i].callback); + continue; + } + + let errState; + let transformed; + + // We trap(and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + transformed = this.format.transform( + Object.assign({}, chunks[i].chunk), + this.format.options + ); + } catch (err) { + errState = err; + } + + if (errState || !transformed) { + // eslint-disable-next-line callback-return + chunks[i].callback(); + if (errState) { + // eslint-disable-next-line callback-return + callback(null); + throw errState; + } + } else { + this.log(transformed, chunks[i].callback); + } + } + + return callback(null); +}; + +/** + * Predicate function that returns true if the specfied `info` on the + * WriteReq, `write`, should be passed down into the derived + * TransportStream's I/O via `.log(info, callback)`. + * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object + * representing the log message. + * @returns {Boolean} - Value indicating if the `write` should be accepted & + * logged. + */ +TransportStream.prototype._accept = function _accept(write) { + const info = write.chunk; + if (this.silent) { + return false; + } + + // We always prefer any explicit level set on the Transport itself + // falling back to any level set on the parent. + const level = this.level || (this.parent && this.parent.level); + + // Immediately check the average case: log level filtering. + if ( + info.exception === true || + !level || + this.levels[level] >= this.levels[info[LEVEL]] + ) { + // Ensure the info object is valid based on `{ exception }`: + // 1. { handleExceptions: true }: all `info` objects are valid + // 2. { exception: false }: accepted by all transports. + if (this.handleExceptions || info.exception !== true) { + return true; + } + } + + return false; +}; + +/** + * _nop is short for "No operation" + * @returns {Boolean} Intentionally false. + */ +TransportStream.prototype._nop = function _nop() { + // eslint-disable-next-line no-undefined + return void undefined; +}; + + +// Expose legacy stream +module.exports.LegacyTransportStream = require('./legacy'); diff --git a/build/node_modules/winston-transport/legacy.js b/build/node_modules/winston-transport/legacy.js new file mode 100644 index 00000000..8025bc9f --- /dev/null +++ b/build/node_modules/winston-transport/legacy.js @@ -0,0 +1,119 @@ +'use strict'; + +const util = require('util'); +const { LEVEL } = require('triple-beam'); +const TransportStream = require('./'); + +/** + * Constructor function for the LegacyTransportStream. This is an internal + * wrapper `winston >= 3` uses to wrap older transports implementing + * log(level, message, meta). + * @param {Object} options - Options for this TransportStream instance. + * @param {Transpot} options.transport - winston@2 or older Transport to wrap. + */ + +const LegacyTransportStream = module.exports = function LegacyTransportStream(options = {}) { + TransportStream.call(this, options); + if (!options.transport || typeof options.transport.log !== 'function') { + throw new Error('Invalid transport, must be an object with a log method.'); + } + + this.transport = options.transport; + this.level = this.level || options.transport.level; + this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; + + // Display our deprecation notice. + this._deprecated(); + + // Properly bubble up errors from the transport to the + // LegacyTransportStream instance, but only once no matter how many times + // this transport is shared. + function transportError(err) { + this.emit('error', err, this.transport); + } + + if (!this.transport.__winstonError) { + this.transport.__winstonError = transportError.bind(this); + this.transport.on('error', this.transport.__winstonError); + } +}; + +/* + * Inherit from TransportStream using Node.js built-ins + */ +util.inherits(LegacyTransportStream, TransportStream); + +/** + * Writes the info object to our transport instance. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + * @private + */ +LegacyTransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || (info.exception === true && !this.handleExceptions)) { + return callback(null); + } + + // Remark: This has to be handled in the base transport now because we + // cannot conditionally write to our pipe targets as stream. + if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { + this.transport.log(info[LEVEL], info.message, info, this._nop); + } + + callback(null); +}; + +/** + * Writes the batch of info objects (i.e. "object chunks") to our transport + * instance after performing any necessary filtering. + * @param {mixed} chunks - TODO: add params description. + * @param {function} callback - TODO: add params description. + * @returns {mixed} - TODO: add returns description. + * @private + */ +LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { + for (let i = 0; i < chunks.length; i++) { + if (this._accept(chunks[i])) { + this.transport.log( + chunks[i].chunk[LEVEL], + chunks[i].chunk.message, + chunks[i].chunk, + this._nop + ); + chunks[i].callback(); + } + } + + return callback(null); +}; + +/** + * Displays a deprecation notice. Defined as a function so it can be + * overriden in tests. + * @returns {undefined} + */ +LegacyTransportStream.prototype._deprecated = function _deprecated() { + // eslint-disable-next-line no-console + console.error([ + `${this.transport.name} is a legacy winston transport. Consider upgrading: `, + '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md' + ].join('\n')); +}; + +/** + * Clean up error handling state on the legacy transport associated + * with this instance. + * @returns {undefined} + */ +LegacyTransportStream.prototype.close = function close() { + if (this.transport.close) { + this.transport.close(); + } + + if (this.transport.__winstonError) { + this.transport.removeListener('error', this.transport.__winstonError); + this.transport.__winstonError = null; + } +}; diff --git a/build/node_modules/winston-transport/package.json b/build/node_modules/winston-transport/package.json new file mode 100644 index 00000000..520120f7 --- /dev/null +++ b/build/node_modules/winston-transport/package.json @@ -0,0 +1,78 @@ +{ + "_from": "winston-transport@^4.4.0", + "_id": "winston-transport@4.4.0", + "_inBundle": false, + "_integrity": "sha512-Lc7/p3GtqtqPBYYtS6KCN3c77/2QCev51DvcJKbkFPQNoj1sinkGwLGFDxkXY9J6p9+EPnYs+D90uwbnaiURTw==", + "_location": "/winston-transport", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "winston-transport@^4.4.0", + "name": "winston-transport", + "escapedName": "winston-transport", + "rawSpec": "^4.4.0", + "saveSpec": null, + "fetchSpec": "^4.4.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.4.0.tgz", + "_shasum": "17af518daa690d5b2ecccaa7acf7b20ca7925e59", + "_spec": "winston-transport@^4.4.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "browser": "dist/index.js", + "bugs": { + "url": "https://github.com/winstonjs/winston-transport/issues" + }, + "bundleDependencies": false, + "dependencies": { + "readable-stream": "^2.3.7", + "triple-beam": "^1.2.0" + }, + "deprecated": false, + "description": "Base stream implementations for winston@3 and up.", + "devDependencies": { + "@types/node": "^14.0.13", + "abstract-winston-transport": ">= 0.3.0", + "assume": "^2.2.0", + "babel-cli": "^6.26.0", + "babel-preset-env": "^1.7.0", + "eslint-config-populist": "^4.2.0", + "logform": "^2.2.0", + "mocha": "^8.0.1", + "nyc": "^15.1.0", + "rimraf": "^3.0.2", + "winston-compat": "^0.1.5" + }, + "engines": { + "node": ">= 6.4.0" + }, + "homepage": "https://github.com/winstonjs/winston-transport#readme", + "keywords": [ + "winston", + "transport", + "winston3" + ], + "license": "MIT", + "main": "index.js", + "name": "winston-transport", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/winstonjs/winston-transport.git" + }, + "scripts": { + "build": "rimraf dist && babel *.js -d ./dist", + "lint": "populist config/*.js index.js", + "prepublishOnly": "npm run build", + "pretest": "npm run lint && npm run build", + "report": "nyc report --reporter=lcov", + "test": "nyc mocha test/*.test.js" + }, + "version": "4.4.0" +} diff --git a/build/node_modules/winston-transport/tsconfig.json b/build/node_modules/winston-transport/tsconfig.json new file mode 100644 index 00000000..0afc8931 --- /dev/null +++ b/build/node_modules/winston-transport/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "./", + "typeRoots": [ + "./node_modules/@types", + "./node_modules" + ], + "types": ["node", "logform"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/build/node_modules/winston/CHANGELOG.md b/build/node_modules/winston/CHANGELOG.md new file mode 100644 index 00000000..828e0c77 --- /dev/null +++ b/build/node_modules/winston/CHANGELOG.md @@ -0,0 +1,560 @@ +# CHANGELOG + +## v3.3.3 / 2020-06-23 + +- [#1820] Revert [#1807] to resolve breaking changes for Typescript users. + +## v3.3.2 / 2020-06-22 + +- [#1814] Use a fork of `diagnostics` published to NPM to avoid git dependency. + +## v3.3.1 / 2020-06-21 + +- [#1803], [#1807] Fix TypeScript bugs. +- [#1740] Add space between `info.message` and `meta.message`. +- [#1813] Avoid indirect storage-engine dependency. +- [#1810] README updates. + +## v3.3.0 / 2020-06-21 + +- [#1779] Fix property name in rejection handler. +- [#1768] Exclude extraneous files from NPM package. +- [#1364], [#1714] Don't remove transport from logger when transport error + occurs. +- [#1603] Expose `child` property on default logger. +- [#1777] Allow HTTP transport to pass options to request. +- [#1662] Add bearer auth capabilities to HTTP transport. +- [#1612] Remove no-op in file transport. +- [#1622], [#1623], [#1625] Typescript fixes. +- (Minor) [#1647], [#1793] Update CI settings. +- (Minor) [#1600], [#1605], [#1593], [#1610], [#1654], [#1656], [#1661], + [#1651], [#1652], [#1677], [#1683], [#1684], [#1700], [#1697], [#1650], + [#1705], [#1723], [#1737], [#1733], [#1743], [#1750], [#1754], [#1780], + [#1778] README, Transports.md, other docs changes. +- [#1672], [#1686], [#1772] Update dependencies. + +## v3.2.1 / 2019-01-29 +### UNBOUND PROTOTYPE AD INFINITUM EDITION + +- #[1579], (@indexzero) Fallback to the "root" instance **always** created by + `createLogger` for level convenience methods (e.g. `.info()`, `.silly()`). + (Fixes [#1577]). +- [#1539], (@indexzero) Assume message is the empty string when level-helper + methods are invoked with no arguments (Fixed [#1501]). +- [#1583], (@kibertoad) Add typings for defaultMeta (Fixes [#1582]) +- [#1586], (@kibertoad) Update dependencies. + +## v3.2.0 / 2019-01-26 +### SORRY IT TOO SO LONG EDITION + +> **NOTE:** this was our first release using Github Projects. See the +> [3.2.0 Release Project](https://github.com/orgs/winstonjs/projects/3). + +### New Features! + +- [#1471], (@kibertoad) Implement child loggers. +- [#1462], (@drazisil) Add handleRejection support. + - [#1555], (@DABH) Add fixes from [#1355] to unhandled rejection handler. +- [#1418], (@mfrisbey) Precompile ES6 syntax before publishing to npm. + - [#1533], (@kibertoad) Update to Babel 7. +- [#1562], (@indexzero) [fix] Better handling of `new Error(string)` + throughout the pipeline(s). (Fixes [#1338], [#1486]). + +### Bug Fixes + +- [#1355], (@DABH) Fix issues with ExceptionHandler (Fixes [#1289]). +- [#1463], (@SerayaEryn) Bubble transport `warn` events up to logger in + addition to `error`s. +- [#1480], [#1503], (@SerayaEryn) File tailrolling fix. +- [#1483], (@soldair) Assign log levels to un-bound functions. +- [#1513], (@TilaTheHun0) Set maxListeners for Console transport. +- [#1521], (@jamesbechet) Fix Transform from `readable-stream` using CRA. +- [#1434], (@Kouzukii) Fixes logger.query function (regression from `3.0.0`) +- [#1526], (@pixtron) Log file without .gz for tailable (Fixes [#1525]). +- [#1559], (@eubnara) Fix typo related to `exitOnError`. +- [#1556], (@adoyle-h) Support to create log directory if it doesn't exist + for FileTransport. + +#### New `splat` behavior + +- [#1552], (@indexzero) Consistent handling of meta with (and without) + interpolation in `winston` and `logform`. +- [#1499], (@DABH) Provide all of `SPLAT` to formats (Fixes [#1485]). +- [#1485], (@mpabst) Fixing off-by-one when using both meta and splat. + +Previously `splat` would have added a `meta` property for any additional +`info[SPLAT]` beyond the expected number of tokens. + +**As of `logform@2.0.0`,** `format.splat` assumes additional splat paramters +(aka "metas") are objects and merges enumerable properties into the `info`. +e.g. **BE ADVISED** previous "metas" that _were not objects_ will very likely +lead to odd behavior. e.g. + +``` js +const { createLogger, format, transports } = require('winston'); +const { splat } = format; +const { MESSAGE, LEVEL, SPLAT } = require('triple-beam'); + +const logger = createLogger({ + format: format.combine( + format.splat(), + format.json() + ), + transports: [new transports.Console()] +}); + +// Expects two tokens, but four splat parameters provided. +logger.info( + 'Let us %s for %j', // message + 'objects', // used for %s + { label: 'sure' }, // used for %j + 'lol', ['ok', 'why'] // Multiple additional meta values +); + +// winston < 3.2.0 && logform@1.x behavior: +// Added "meta" property. +// +// { level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// meta: ['lol', ['ok', 'why']], +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } + +// winston >= 3.2.0 && logform@2.x behavior: Enumerable properties +// assigned into `info`. Since **strings and Arrays only have NUMERIC +// enumerable properties we get this behavior!** +// +// { '0': 'ok', +// '1': 'why', +// '2': 'l', +// level: 'info', +// message: 'Let us objects for {"label":"sure"}', +// [Symbol(level)]: 'info', +// [Symbol(message)]: 'Let us %s for %j', +// [Symbol(splat)]: [ 'objects', { label: 'sure' } ] } +``` + +## Maintenance & Documentation + +- Documentation Updates + - [#1410], (@hakanostrom) Add docs reference to transport for Cloudant. + - [#1467], (@SeryaEryn) Add fast-file-rotate transport to transport.md. + - [#1488], (@adamcohen) Fix multi logger documentation. + - [#1531], (@mapleeit) Add links to transports. + - [#1548], (@ejmartin504) Fix `README.md` for awaiting logs. + - [#1554], (@indexzero) Document the solution to [#1486] as by design. + - Other small improvements: [#1509]. +- Improved TypeScript support + - [#1470], (@jd-carroll) Export all transport options (Fixes [#1469]). + - [#1474], (@jd-carroll) Correct import to avoid conflict (Fixed [#1472]). + - [#1546], (@alewiahmed) Add consoleWarnLevels field to the + `ConsoleTransportOptions` interface type definition. + - [#1557], (@negezor) Add missing `child()` method. +- Dependency management + - [#1560], (@kibertoad) Update dependencies. + - [#1512], (@SerayaEryn) Add node@11 and disallow failures on node@10. + - [#1516], (@SerayaEryn) Update `readable-stream` to `v3.0.6`. + - [#1534], (@kibertoad) Update `@types/node`, `nyc`, and `through2`. + +## v3.1.0 / 2018-08-22 +### RELEASES ON A PLANE EDITION + +- Minor TypeScript fixes [#1362], [#1395], [#1440] +- Fix minor typos [#1359], [#1363], [#1372], [#1378], [#1390] +- [#1373], (@revik): Add `consoleWarnLevels` property to console transport options for `console.warn` browser support. +- [#1394], (@bzoz): Fix tests on Windows. +- [#1447], (@dboshardy): Support transport name option to override default names for built-in transports. +- [#1420], (@ledbit): Fix file rotation with `tailing: true` (Fixes [#1450], [#1194]). +- [#1352], (@lutovich): Add `isLevelEnabled(string)` & `isXXXEnabled()` to `Logger` class. +- Dependency management + - Regenerate `package-lock.json`. + - Upgrade to `colors@^1.3.2` (Fixes [#1439]). + - Upgrade to `logform@^1.9.1`. + - Upgrade to `diagnostics@^1.1.1`. + - Upgrade to `@types/node@^10.9.3`. + - Upgrade to `assume@^2.1.0`. + - Upgrade to `hock@^1.3.3`. + - Upgrade to `mocha@^5.2.0`. + - Upgrade to `nyc@^13.0.1`. + - Upgrade to `split2@^3.0.0`. + +## v3.0.0 / 2018-06-12 +### GET IN THE CHOPPA EDITION + +- [#1332], (@DABH): logger.debug is sent to stderr (Fixed [#1024]) +- [#1328], (@ChrisAlderson): Logger level doesn't update transports level (Fixes [#1191]). +- [#1356], (@indexzero) Move splat functionality into logform. (Fixes [#1298]). +- [#1340], (@indexzero): Check log.length when evaluating "legacyness" of transports (Fixes [#1280]). +- [#1346], (@indexzero): Implement `_final` from Node.js streams. (Related to winston-transport#24, Fixes [#1250]). +- [#1347], (@indexzero): Wrap calls to `format.transform` with try / catch (Fixes [#1261]). +- [#1357], (@indexzero): Remove paddings as we have no use for it in the current API. +- [TODO]: REMAINS OPEN, NO PR (Fixes [#1289]) +- Documentation + - [#1301], (@westonpace) Cleaned up some of the documentation on `colorize` + to address concerns in [#1095]. + - First pass at a heavy refactor of `docs/transports.md`. +- Dependency management + - Regenerate `package-lock.json`. + - Upgrade to `logform@^1.9.0`. + +## v3.0.0-rc6 / 2018-05-30 +### T-MINUS 6-DAY TO WINSTON@3 EDITION + +- **Document that we are pushing for a June 5th, 2018 release of `winston@3.0.0`** +- [#1287], (@DABH) Added types for Typescript. + - [#1335] Typescript: silent is boolean. + - [#1323] Add level method to default logger. +- [#1286], (@ChrisAlderson) Migrate codebase to ES6 + - [#1324], (@ChrisAlderson) Fix regression introduced by ES6 migration for + exception handling. + - [#1333], (@ChrisAlderson) Fix removing all loggers from a container. +- [#1291], [#1294], [#1318], (@indexzero, @ChrisAlderson, @mempf) Improvements + to `File` transport core functionality. Fixes [#1194]. +- [#1311], (@ChrisAlderson) Add `eol` option to `Stream` transport. +- [#1297], (@ChrisAlderson) Move `winston.config` to `triple-beam`. Expose + for backwards compatibility. +- [#1320], (@ChrisAlderson) Enhance tests to run on Windows. +- Internal project maintenance + - Bump to `winston-transport@4.0.0` which may cause incompatibilities if + your custom transport does not explicitly require `winston-transport` + itself. + - [#1292], (@ChrisAlderson) Add node v10 to TravisCI build matrix. + - [#1296], (@indexzero) Improve `UPGRADE-3.0.md`. Add Github Issue Template. + - Remove "npm run report" in favor of reports being automatically generate. + - Update `logform`, `triple-beam`, and `winston-transport` to latest. + +> Special thanks to our newest `winston` core team member – @ChrisAlderson for +> helping make `winston@3.0.0` a reality next week! + +## v3.0.0-rc5 / 2018-04-20 +### UNOFFICIAL NATIONAL HOLIDAY EDITION + +- [#1281] Use `Buffer.alloc` and `Buffer.from` instead of `new Buffer`. +- Better browser support + - [#1142] Move common tailFile to a separate file + - [#1279] Use feature detection to be safer for browser usage. +- MOAR Docs! + - **Document that we are pushing for a May 29th, 2018 release of `winston@3.0.0`** + - **Add David Hyde as official contributor.** + - [#1278] Final Draft of Upgrade Guide in `UPGRADE-3.0.md` + - Merge Roadmap from `3.0.0.md` into `CONTRIBUTING.md` and other + improvements to `CONTRIBUTING.md` +- Improve & expand examples + - [#1175] Add more copy about printf formats based on issue feedback. + - [#1134] Add sampleto document timestamps more clearly as an example. + - [#1273] Add example using multiple formats. + - [#1250] Add an example illustrating the "finish" event for AWS Lambda scenarios. + - Use simple format to better show that `humanReadableUnhandledException` is now the default message format. + - Add example to illustrate that example code from winston-transport + `README.md` is correct. +- Update `devDependencies` + - Bump `assume` to `^2.0.1`. + - Bump `winston-compat` to `^0.1.1`. + +## v3.0.0-rc4 / 2018-04-06 +### IF A TREE FALLS IN THE FORREST DOES IT MAKE A LOG EDITION + +- (@indexzero, @dabh) Add support for `{ silent }` option to +``` js +require('winston').Logger; +require('winston-transport').TransportStream; +``` +- Better browser support + - [#1145], (@Jasu) Replace `isstream` with `is-stream` to make stream detection work in browser. + - [#1146], (@Jasu) Rename query to different than function name, to support Babel 6.26. +- Better Typescript support in all supporting libraries + - `logform@1.4.1` +- Update documentation + - (@indexzero) Correct link to upgrade guide. Fixes #1255. + - [#1258], (@morenoh149) Document how to colorize levels. Fixes #1135. + - [#1246], (@KlemenPlazar) Update colors argument when adding custom colors + - Update `CONTRIBUTING.md` + - [#1239], (@dabh) Add changelog entries for `v3.0.0-rc3` + - Add example showing that `{ level }` can be deleted from info objects because `Symbol.for('level')` is what `winston` uses internally. Fixes #1184. + +## v3.0.0-rc3 / 2018-03-16 +### I GOT NOTHING EDITION + +- [#1195], (@Nilegfx) Fix type error when creating `new stream.Stream()` +- [#1109], (@vsetka) Fix file transprot bug where `self.filename` was not being updated on `ENOENT` +- [#1153], (@wizardnet972) Make prototype methods return like the original method +- [#1234], (@guiguan, @indexzero) Add tests for properly handling logging of `undefined`, `null` and `Error` values +- [#1235], (@indexzero) Add example demonstrating how `meta` objects BECOME the `info` object +- Minor fixes to docs & examples: [#1232], [#1185] + +## v3.0.0-rc2 / 2018-03-09 +### MAINTENANCE RESUMES EDITION + +- [#1209], (@dabh) Use new version of colors, solving a number of issues. +- [#1197], (@indexzero) Roadmap & guidelines for contributors. +- [#1100] Require the package.json by its full name. +- [#1149] Updates `async` to latest (`2.6.0`) +- [#1228], (@mcollina) Always pass a function to `fs.close`. +- Minor fixes to docs & examples: [#1177], [#1182], [#1208], [#1198], [#1165], [#1110], [#1117], [#1097], [#1155], [#1084], [#1141], [#1210], [#1223]. + +## v3.0.0-rc1 / 2017-10-19 +### OMG THEY FORGOT TO NAME IT EDITION + + - Fix file transport improper binding of `_onDrain` and `_onError` [#1104](https://github.com/winstonjs/winston/pull/1104) + +## v3.0.0-rc0 / 2017-10-02 +### IT'S-DONE.GIF EDITION + +**See [UPGRADE-3.0.md](UPGRADE-3.0.md) for a complete & living upgrade guide.** + +**See [3.0.0.md](3.0.0.md) for a list of remaining RC tasks.** + +- **Rewrite of core logging internals:** `Logger` & `Transport` are now implemented using Node.js `objectMode` streams. +- **Your transports _should_ not break:** Special attention has been given to ensure backwards compatibility with existing transports. You will likely see this: +``` +YourTransport is a legacy winston transport. Consider upgrading to winston@3: +- Upgrade docs: https://github.com/winstonjs/winston/tree/master/UPGRADE.md +``` +- **`filters`, `rewriters`, and `common.log` are now _formats_:** `winston.format` offers a simple mechanism for user-land formatting & style features. The organic & frankly messy growth of `common.log` is of the past; these feature requests can be implemented entirely outside of `winston` itself. +``` js +const { createLogger, format, transports } = require('winston'); +const { combine, timestamp, label, printf } = format; + +const myFormat = printf(info => { + return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`; +}); + +const logger = createLogger({ + combine( + label({ label: 'right meow!' }), + timestamp(), + myFormat + ), + transports: [new transports.Console()] +}); +``` +- **Increased modularity:** several subsystems are now stand-alone packages: + - [logform] exposed as `winston.format` + - [winston-transport] exposed as `winston.Transport` + - [abstract-winston-transport] used for reusable unit test suites for transport authors. +- **`2.x` branch will get little to no maintenance:** no feature requests will be accepted – only a limited number of open PRs will be merged. Hoping the [significant performance benefits][perf-bench] incentivizes folks to upgrade quickly. Don't agree? Say something! +- **No guaranteed support for `node@4` or below:** all code will be migrated to ES6 over time. This release was started when ES5 was still a hard requirement due to the current LTS needs. + +## v2.4.0 / 2017-10-01 +### ZOMFG WINSTON@3.0.0-RC0 EDITION + +- [#1036] Container.add() 'filters' and 'rewriters' option passing to logger. +- [#1066] Fixed working of "humanReadableUnhandledException" parameter when additional data is added in meta. +- [#1040] Added filtering by log level +- [#1042] Fix regressions brought by `2.3.1`. + - Fix regression on array printing. + - Fix regression on falsy value. +- [#977] Always decycle objects before cloning. + - Fixes [#862] + - Fixes [#474] + - Fixes [#914] +- [57af38a] Missing context in `.lazyDrain` of `File` transport. +- [178935f] Suppress excessive Node warning from `fs.unlink`. +- [fcf04e1] Add `label` option to `File` transport docs. +- [7e736b4], [24300e2] Added more info about undocumented `winston.startTimer()` method. +- [#1076], [#1082], [#1029], [#989], [e1e7188] Minor grammatical & style updates to `README.md`. + +## v2.3.1 / 2017-01-20 +### WELCOME TO THE APOCALYPSE EDITION + +- [#868](https://github.com/winstonjs/winston/pull/868), Fix 'Maximum call stack size exceeded' error with custom formatter. + +## v2.3.0 / 2016-11-02 +### ZOMG WHY WOULD YOU ASK EDITION + +- Full `CHANGELOG.md` entry forthcoming. See [the `git` diff for `2.3.0`](https://github.com/winstonjs/winston/compare/2.2.0...2.3.0) for now. + +## v2.2.0 / 2016-02-25 +### LEAVING CALIFORNIA EDITION + +- Full `CHANGELOG.md` entry forthcoming. See [the `git` diff for `2.2.0`](https://github.com/winstonjs/winston/compare/2.1.1...2.2.0) for now. + +## v2.1.1 / 2015-11-18 +### COLOR ME IMPRESSED EDITION + +- [#751](https://github.com/winstonjs/winston/pull/751), Fix colors not appearing in non-tty environments. Fixes [#609](https://github.com/winstonjs/winston/issues/609), [#616](https://github.com/winstonjs/winston/issues/616), [#669](https://github.com/winstonjs/winston/issues/669), [#648](https://github.com/winstonjs/winston/issues/648) (`fiznool`). +- [#752](https://github.com/winstonjs/winston/pull/752) Correct syslog RFC number. 5424 instead of 524. (`jbenoit2011`) + +## v2.1.0 / 2015-11-03 +### TEST ALL THE ECOSYSTEM EDITION + +- [#742](https://github.com/winstonjs/winston/pull/742), [32d52b7](https://github.com/winstonjs/winston/commit/32d52b7) Distribute common test files used by transports in the `winston` ecosystem. + +## v2.0.1 / 2015-11-02 +### BUGS ALWAYS HAPPEN OK EDITION + +- [#739](https://github.com/winstonjs/winston/issues/739), [1f16861](https://github.com/winstonjs/winston/commit/1f16861) Ensure that `logger.log("info", undefined)` does not throw. + +## v2.0.0 / 2015-10-29 +### OMG IT'S MY SISTER'S BIRTHDAY EDITION + +#### Breaking changes + +**Most important** +- **[0f82204](https://github.com/winstonjs/winston/commit/0f82204) Move `winston.transports.DailyRotateFile` [into a separate module](https://github.com/winstonjs/winston-daily-rotate-file)**: `require('winston-daily-rotate-file');` +- **[fb9eec0](https://github.com/winstonjs/winston/commit/fb9eec0) Reverse log levels in `npm` and `cli` configs to conform to [RFC524](https://tools.ietf.org/html/rfc5424). Fixes [#424](https://github.com/winstonjs/winston/pull/424) [#406](https://github.com/winstonjs/winston/pull/406) [#290](https://github.com/winstonjs/winston/pull/290)** +- **[8cd8368](https://github.com/winstonjs/winston/commit/8cd8368) Change the method signature to a `filter` function to be consistent with `rewriter` and log functions:** +``` js +function filter (level, msg, meta, inst) { + // Filter logic goes here... +} +``` + +**Other breaking changes** +- [e0c9dde](https://github.com/winstonjs/winston/commit/e0c9dde) Remove `winston.transports.Webhook`. Use `winston.transports.Http` instead. +- [f71e638](https://github.com/winstonjs/winston/commit/f71e638) Remove `Logger.prototype.addRewriter` and `Logger.prototype.addFilter` since they just push to an Array of functions. Use `logger.filters.push` or `logger.rewriters.push` explicitly instead. +- [a470ab5](https://github.com/winstonjs/winston/commit/a470ab5) No longer respect the `handleExceptions` option to `new winston.Logger`. Instead just pass in the `exceptionHandlers` option itself. +- [8cb7048](https://github.com/winstonjs/winston/commit/8cb7048) Removed `Logger.prototype.extend` functionality + +#### New features +- [3aa990c](https://github.com/winstonjs/winston/commit/3aa990c) Added `Logger.prototype.configure` which now contains all logic previously in the `winston.Logger` constructor function. (`indexzero`) +- [#726](https://github.com/winstonjs/winston/pull/726) Update .npmignore (`coreybutler`) +- [#700](https://github.com/winstonjs/winston/pull/700) Add an `eol` option to the `Console` transport. (`aquavitae`) +- [#731](https://github.com/winstonjs/winston/pull/731) Update `lib/transports.js` for better static analysis. (`indexzero`) + +#### Fixes, refactoring, and optimizations. OH MY! +- [#632](https://github.com/winstonjs/winston/pull/632) Allow `File` transport to be an `objectMode` writable stream. (`stambata`) +- [#527](https://github.com/winstonjs/winston/issues/527), [163f4f9](https://github.com/winstonjs/winston/commit/163f4f9), [3747ccf](https://github.com/winstonjs/winston/commit/3747ccf) Performance optimizations and string interpolation edge cases (`indexzero`) +- [f0edafd](https://github.com/winstonjs/winston/commit/f0edafd) Code cleanup for reability, ad-hoc styleguide enforcement (`indexzero`) + +## v1.1.1 - v1.1.2 / 2015-10 +### MINOR FIXES EDITION + +#### Notable changes + * [727](https://github.com/winstonjs/winston/pull/727) Fix "raw" mode (`jcrugzz`) + * [703](https://github.com/winstonjs/winston/pull/703) Do not modify Error or Date objects when logging. Fixes #610 (`harriha`). + +## v1.1.0 / 2015-10-09 +### GREETINGS FROM CARTAGENA EDITION + +#### Notable Changes + * [#721](https://github.com/winstonjs/winston/pull/721) Fixed octal literal to work with node 4 strict mode (`wesleyeff`) + * [#630](https://github.com/winstonjs/winston/pull/630) Add stderrLevels option to Console Transport and update docs (`paulhroth`) + * [#626](https://github.com/winstonjs/winston/pull/626) Add the logger (this) in the fourth argument in the rewriters and filters functions (`christophehurpeau `) + * [#623](https://github.com/winstonjs/winston/pull/623) Fix Console Transport's align option tests (`paulhroth`, `kikobeats`) + * [#692](https://github.com/winstonjs/winston/pull/692) Adding winston-aws-cloudwatch to transport docs (`timdp`) + +## v1.0.2 2015-09-25 +### LET'S TALK ON GITTER EDITION + +#### Notable Changes + * [de80160](https://github.com/winstonjs/winston/commit/de80160) Add Gitter badge (`The Gitter Badger`) + * [44564de](https://github.com/winstonjs/winston/commit/44564de) [fix] Correct listeners in `logException`. Fixes [#218](https://github.com/winstonjs/winston/issues/218) [#213](https://github.com/winstonjs/winston/issues/213) [#327](https://github.com/winstonjs/winston/issues/327). (`indexzero`) + * [45b1eeb](https://github.com/winstonjs/winston/commit/45b1eeb) [fix] Get `tailFile` function working on latest/all node versions (`Christopher Jeffrey`) + * [c6d45f9](https://github.com/winstonjs/winston/commit/c6d45f9) Fixed event subscription on close (`Roman Stetsyshin`) + +#### Other changes + * TravisCI updates & best practices [87b97cc](https://github.com/winstonjs/winston/commit/87b97cc) [91a5bc4](https://github.com/winstonjs/winston/commit/91a5bc4), [cf24e6a](https://github.com/winstonjs/winston/commit/cf24e6a) (`indexzero`) + * [d5397e7](https://github.com/winstonjs/winston/commit/d5397e7) Bump async version (`Roderick Hsiao`) + * Documentation updates & fixes [86d7527](https://github.com/winstonjs/winston/commit/86d7527), [38254c1](https://github.com/winstonjs/winston/commit/38254c1), [04e2928](https://github.com/winstonjs/winston/commit/04e2928), [61c8a89](https://github.com/winstonjs/winston/commit/61c8a89), [c42a783](https://github.com/winstonjs/winston/commit/c42a783), [0688a22](https://github.com/winstonjs/winston/commit/0688a22), [eabc113](https://github.com/winstonjs/winston/commit/eabc113) [c9506b7](https://github.com/winstonjs/winston/commit/c9506b7), [17534d2](https://github.com/winstonjs/winston/commit/17534d2), [b575e7b](https://github.com/winstonjs/winston/commit/b575e7b) (`Stefan Thies`, `charukiewicz`, `unLucio`, `Adam Cohen`, `Denis Gorbachev`, `Frederik Ring`, `Luigi Pinca`, `jeffreypriebe`) + * Documentation refactor & cleanup [a19607e](https://github.com/winstonjs/winston/commit/a19607e), [d1932b4](https://github.com/winstonjs/winston/commit/d1932b4), [7a13132](https://github.com/winstonjs/winston/commit/7a13132) (`indexzero`) + + +## v1.0.1 / 2015-06-26 +### YAY DOCS EDITION + + * [#639](https://github.com/winstonjs/winston/pull/639) Fix for [#213](https://github.com/winstonjs/winston/issues/213): More than 10 containers triggers EventEmitter memory leak warning (`marcus`) + * Documentation and `package.json` updates [cec892c](https://github.com/winstonjs/winston/commit/cec892c), [2f13b4f](https://github.com/winstonjs/winston/commit/2f13b4f), [b246efd](https://github.com/winstonjs/winston/commit/b246efd), [22a5f5a](https://github.com/winstonjs/winston/commit/22a5f5a), [5868b78](https://github.com/winstonjs/winston/commit/5868b78), [99b6b44](https://github.com/winstonjs/winston/commit/99b6b44), [447a813](https://github.com/winstonjs/winston/commit/447a813), [7f75b48](https://github.com/winstonjs/winston/commit/7f75b48) (`peteward44`, `Gilad Peleg`, `Anton Ian Sipos`, `nimrod-becker`, `LarsTi`, `indexzero`) + +## v1.0.0 / 2015-04-07 +### OMG 1.0.0 FINALLY EDITION + +#### Breaking Changes + * [#587](https://github.com/winstonjs/winston/pull/587) Do not extend `String` prototypes as a side effect of using `colors`. (`kenperkins`) + * [#581](https://github.com/winstonjs/winston/pull/581) File transports now emit `error` on error of the underlying streams after `maxRetries` attempts. (`ambbell`). + * [#583](https://github.com/winstonjs/winston/pull/583), [92729a](https://github.com/winstonjs/winston/commit/92729a68d71d07715501c35d94d2ac06ac03ca08) Use `os.EOL` for all file writing by default. (`Mik13`, `indexzero`) + * [#532](https://github.com/winstonjs/winston/pull/532) Delete logger instance from `Container` when `close` event is emitted. (`snater`) + * [#380](https://github.com/winstonjs/winston/pull/380) Rename `duration` to `durationMs`, which is now a number a not a string ending in `ms`. (`neoziro`) + * [#253](https://github.com/winstonjs/winston/pull/253) Do not set a default level. When `level` is falsey on any `Transport` instance, any `Logger` instance uses the configured level (instead of the Transport level) (`jstamerj`). + +#### Other changes + + * [b83de62](https://github.com/winstonjs/winston/commit/b83de62) Fix rendering of stack traces. + * [c899cc](https://github.com/winstonjs/winston/commit/c899cc1f0719e49b26ec933e0fa263578168ea3b) Update documentation (Fixes [#549](https://github.com/winstonjs/winston/issues/549)) + * [#551](https://github.com/winstonjs/winston/pull/551) Filter metadata along with messages + * [#578](https://github.com/winstonjs/winston/pull/578) Fixes minor issue with `maxFiles` in `File` transport (Fixes [#556](https://github.com/winstonjs/winston/issues/556)). + * [#560](https://github.com/winstonjs/winston/pull/560) Added `showLevel` support to `File` transport. + * [#558](https://github.com/winstonjs/winston/pull/558) Added `showLevel` support to `Console` transport. + +## v0.9.0 / 2015-02-03 + + * [#496](https://github.com/flatiron/winston/pull/496) Updated default option handling for CLI (`oojacoboo`). + * [f37634b](https://github.com/flatiron/winston/commit/f37634b) [dist] Only support `node >= 0.8.0`. (`indexzero`) + * [91a1e90](https://github.com/flatiron/winston/commit/91a1e90), [50163a0](https://github.com/flatiron/winston/commit/50163a0) Fix #84 [Enable a better unhandled exception experience](https://github.com/flatiron/winston/issues/84) (`samz`) + * [8b5fbcd](https://github.com/flatiron/winston/commit/8b5fbcd) #448 Added tailable option to file transport which rolls files backwards instead of creating incrementing appends. Implements #268 (`neouser99`) + * [a34f7d2](https://github.com/flatiron/winston/commit/a34f7d2) Custom log formatter functionality were added. (`Melnyk Andii`) + * [4c08191](https://github.com/flatiron/winston/commit/4c08191) Added showLevel flag to common.js, file*, memory and console transports. (`Tony Germaneri`) + * [64ed8e0](https://github.com/flatiron/winston/commit/64ed8e0) Adding custom pretty print function test. (`Alberto Pose`) + * [3872dfb](https://github.com/flatiron/winston/commit/3872dfb) Adding prettyPrint parameter as function example. (`Alberto Pose`) + * [2b96eee](https://github.com/flatiron/winston/commit/2b96eee) implemented filters #526 (`Chris Oloff`) + * [72273b1](https://github.com/flatiron/winston/commit/72273b1) Added the options to colorize only the level, only the message or all. Default behavior is kept. Using true will only colorize the level and false will not colorize anything. (`Michiel De Mey`) + * [178e8a6](https://github.com/flatiron/winston/commit/178e8a6) Prevent message from meta input being overwritten (`Leonard Martin`) + * [270be86](https://github.com/flatiron/winston/commit/270be86) [api] Allow for transports to be removed by their string name [test fix] Add test coverage for multiple transports of the same type added in #187. [doc] Document using multiple transports of the same type (`indexzero`) + * [0a848fa](https://github.com/flatiron/winston/commit/0a848fa) Add depth options for meta pretty print (`Loïc Mahieu`) + * [106b670](https://github.com/flatiron/winston/commit/106b670) Allow debug messages to be sent to stdout (`John Frizelle`) + * [ad2d5e1](https://github.com/flatiron/winston/commit/ad2d5e1) [fix] Handle Error instances in a sane way since their properties are non-enumerable __by default.__ Fixes #280. (`indexzero`) + * [5109dd0](https://github.com/flatiron/winston/commit/5109dd0) [fix] Have a default `until` before a default `from`. Fixes #478. (`indexzero`) + * [d761960](https://github.com/flatiron/winston/commit/d761960) Fix logging regular expression objects (`Chasen Le Hara`) + * [2632eb8](https://github.com/flatiron/winston/commit/2632eb8) Add option for EOL chars on FileTransport (`José F. Romaniello`) + * [bdecce7](https://github.com/flatiron/winston/commit/bdecce7) Remove duplicate logstash option (`José F. Romaniello`) + * [7a01f9a](https://github.com/flatiron/winston/commit/7a01f9a) Update declaration block according to project's style guide (`Ricardo Torres`) + * [ae27a19](https://github.com/flatiron/winston/commit/ae27a19) Fixes #306: Can't set customlevels to my loggers (RangeError: Maximum call stack size exceeded) (`Alberto Pose`) + * [1ba4f51](https://github.com/flatiron/winston/commit/1ba4f51) [fix] Call `res.resume()` in HttpTransport to get around known issues in streams2. (`indexzero`) + * [39e0258](https://github.com/flatiron/winston/commit/39e0258) Updated default option handling for CLI (`Jacob Thomason`) + * [8252801](https://github.com/flatiron/winston/commit/8252801) Added logstash support to console transport (`Ramon Snir`) + * [18aa301](https://github.com/flatiron/winston/commit/18aa301) Module isStream should be isstream (`Michael Neil`) + * [2f5f296](https://github.com/flatiron/winston/commit/2f5f296) options.prettyPrint can now be a function (`Matt Zukowski`) + * [a87a876](https://github.com/flatiron/winston/commit/a87a876) Adding rotationFormat prop to file.js (`orcaman`) + * [ff187f4](https://github.com/flatiron/winston/commit/ff187f4) Allow custom exception level (`jupiter`) + +## 0.8.3 / 2014-11-04 + +* [fix lowercase issue (`jcrugzz`)](https://github.com/flatiron/winston/commit/b3ffaa10b5fe9d2a510af5348cf4fb3870534123) + +## 0.8.2 / 2014-11-04 + +* [Full fix for #296 with proper streams2 detection with `isstream` for file transport (`jcrugzz`)](https://github.com/flatiron/winston/commit/5c4bd4191468570e46805ed399cad63cfb1856cc) +* [Add isstream module (`jcrugzz`)](https://github.com/flatiron/winston/commit/498b216d0199aebaef72ee4d8659a00fb737b9ae) +* [Partially fix #296 with streams2 detection for file transport (`indexzero`)](https://github.com/flatiron/winston/commit/b0227b6c27cf651ffa8b8192ef79ab24296362e3) +* [add stress test for issue #288 (`indexzero`)](https://github.com/flatiron/winston/commit/e08e504b5b3a00f0acaade75c5ba69e6439c84a6) +* [lessen timeouts to check test sanity (`indexzero`)](https://github.com/flatiron/winston/commit/e925f5bc398a88464f3e796545ff88912aff7568) +* [update winston-graylog2 documentation (`unlucio`)](https://github.com/flatiron/winston/commit/49fa86c31baf12c8ac3adced3bdba6deeea2e363) +* [fix test formatting (`indexzero`)](https://github.com/flatiron/winston/commit/8e2225799520a4598044cdf93006d216812a27f9) +* [fix so options are not redefined (`indexzero`)](https://github.com/flatiron/winston/commit/d1d146e8a5bb73dcb01579ad433f6d4f70b668ea) +* [fix self/this issue that broke `http` transport (`indexzero`)](https://github.com/flatiron/winston/commit/d10cbc07755c853b60729ab0cd14aa665da2a63b) + + +## 0.8.1 / 2014-10-06 + +* [Add label option for DailyRotateFile transport (`francoisTemasys`)](https://github.com/flatiron/winston/pull/459) +* [fix Logger#transports length check upon Logger#log (`adriano-di-giovanni`, `indexzero`)](https://github.com/flatiron/winston/pull/404) +* [err can be a string. (`gdw2`, `indexzero`)](https://github.com/flatiron/winston/pull/396) +* [Added color for pre-defined cli set. (`danilo1105`, `indexzero`)](https://github.com/flatiron/winston/pull/365) +* [Fix dates on transport test (`revington`)](https://github.com/flatiron/winston/pull/346) +* [Included the label from options to the output in JSON mode. (`arxony`)](https://github.com/flatiron/winston/pull/326) +* [Allow using logstash option with the File transport (`gmajoulet`)](https://github.com/flatiron/winston/pull/299) +* [Be more defensive when working with `query` methods from Transports. Fixes #356. (indexzero)](https://github.com/flatiron/winston/commit/b80638974057f74b521dbe6f43fef2105110afa2) +* [Catch exceptions for file transport unlinkSync (`calvinfo`)](https://github.com/flatiron/winston/pull/266) +* [Adding the 'addRewriter' to winston (`machadogj`)](https://github.com/flatiron/winston/pull/258) +* [Updates to transport documentation (`pose`)](https://github.com/flatiron/winston/pull/262) +* [fix typo in "Extending another object with Logging" section.](https://github.com/flatiron/winston/pull/281) +* [Updated README.md - Replaced properties with those listed in winston-mongodb module](https://github.com/flatiron/winston/pull/264) + +## 0.8.0 / 2014-09-15 + * [Fixes for HTTP Transport](https://github.com/flatiron/winston/commit/a876a012641f8eba1a976eada15b6687d4a03f82) + * Removing [jsonquest](https://github.com/flatiron/winston/commit/4f088382aeda28012b7a0498829ceb243ed74ac1) and [request](https://github.com/flatiron/winston/commit/a5676313b4e9744802cc3b8e1468e4af48830876) dependencies. + * Configuration is now [shalow cloned](https://github.com/flatiron/winston/commit/08fccc81d18536d33050496102d98bde648853f2). + * [Added logstash support](https://github.com/flatiron/winston/pull/445/files) + * Fix for ["flush" event should always fire after "flush" call bug](https://github.com/flatiron/winston/pull/446/files) + * Added tests for file: [open and stress](https://github.com/flatiron/winston/commit/47d885797a2dd0d3cd879305ca813a0bd951c378). + * [Test fixes](https://github.com/flatiron/winston/commit/9e39150e0018f43d198ca4c160acef2af9860bf4) + * [Fix ")" on string interpolation](https://github.com/flatiron/winston/pull/394/files) + +## 0.6.2 / 2012-07-08 + + * Added prettyPrint option for console logging + * Multi-line values for conditional returns are not allowed + * Added acceptance of `stringify` option + * Fixed padding for log levels + diff --git a/build/node_modules/winston/LICENSE b/build/node_modules/winston/LICENSE new file mode 100644 index 00000000..948d80dd --- /dev/null +++ b/build/node_modules/winston/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Charlie Robbins + +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. \ No newline at end of file diff --git a/build/node_modules/winston/README.md b/build/node_modules/winston/README.md new file mode 100644 index 00000000..91ae12a7 --- /dev/null +++ b/build/node_modules/winston/README.md @@ -0,0 +1,1230 @@ +# winston + +A logger for just about everything. + +[![Version npm](https://img.shields.io/npm/v/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston)[![npm Downloads](https://img.shields.io/npm/dm/winston.svg?style=flat-square)](https://npmcharts.com/compare/winston?minimal=true)[![Build Status](https://img.shields.io/travis/winstonjs/winston/master.svg?style=flat-square)](https://travis-ci.org/winstonjs/winston)[![Dependencies](https://img.shields.io/david/winstonjs/winston.svg?style=flat-square)](https://david-dm.org/winstonjs/winston) + +[![NPM](https://nodei.co/npm/winston.png?downloads=true&downloadRank=true)](https://nodei.co/npm/winston/) + +[![Join the chat at https://gitter.im/winstonjs/winston](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/winstonjs/winston?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +## winston@3 + +See the [Upgrade Guide](UPGRADE-3.0.md) for more information. Bug reports and +PRs welcome! + +## Looking for `winston@2.x` documentation? + +Please note that the documentation below is for `winston@3`. +[Read the `winston@2.x` documentation]. + +## Motivation + +`winston` is designed to be a simple and universal logging library with +support for multiple transports. A transport is essentially a storage device +for your logs. Each `winston` logger can have multiple transports (see: +[Transports]) configured at different levels (see: [Logging levels]). For +example, one may want error logs to be stored in a persistent remote location +(like a database), but all logs output to the console or a local file. + +`winston` aims to decouple parts of the logging process to make it more +flexible and extensible. Attention is given to supporting flexibility in log +formatting (see: [Formats]) & levels (see: [Using custom logging levels]), and +ensuring those APIs decoupled from the implementation of transport logging +(i.e. how the logs are stored / indexed, see: [Adding Custom Transports]) to +the API that they exposed to the programmer. + +## Quick Start + +TL;DR? Check out the [quick start example][quick-example] in `./examples/`. +There are a number of other examples in [`./examples/*.js`][examples]. +Don't see an example you think should be there? Submit a pull request +to add it! + +## Usage + +The recommended way to use `winston` is to create your own logger. The +simplest way to do this is using `winston.createLogger`: + +``` js +const winston = require('winston'); + +const logger = winston.createLogger({ + level: 'info', + format: winston.format.json(), + defaultMeta: { service: 'user-service' }, + transports: [ + // + // - Write all logs with level `error` and below to `error.log` + // - Write all logs with level `info` and below to `combined.log` + // + new winston.transports.File({ filename: 'error.log', level: 'error' }), + new winston.transports.File({ filename: 'combined.log' }), + ], +}); + +// +// If we're not in production then log to the `console` with the format: +// `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` +// +if (process.env.NODE_ENV !== 'production') { + logger.add(new winston.transports.Console({ + format: winston.format.simple(), + })); +} +``` + +You may also log directly via the default logger exposed by +`require('winston')`, but this merely intended to be a convenient shared +logger to use throughout your application if you so choose. + +## Table of contents + +* [Motivation](#motivation) +* [Quick Start](#quick-start) +* [Usage](#usage) +* [Table of Contents](#table-of-contents) +* [Logging](#logging) + * [Creating your logger](#creating-your-own-logger) + * [Streams, `objectMode`, and `info` objects](#streams-objectmode-and-info-objects) +* [Formats] + * [Combining formats](#combining-formats) + * [String interpolation](#string-interpolation) + * [Filtering `info` Objects](#filtering-info-objects) + * [Creating custom formats](#creating-custom-formats) +* [Logging levels] + * [Using logging levels](#using-logging-levels) + * [Using custom logging levels](#using-custom-logging-levels) +* [Transports] + * [Multiple transports of the same type](#multiple-transports-of-the-same-type) + * [Adding Custom Transports](#adding-custom-transports) + * [Common Transport options](#common-transport-options) +* [Exceptions](#exceptions) + * [Handling Uncaught Exceptions with winston](#handling-uncaught-exceptions-with-winston) + * [To Exit or Not to Exit](#to-exit-or-not-to-exit) +* [Rejections](#rejections) + * [Handling Uncaught Promise Rejections with winston](#handling-uncaught-promise-rejections-with-winston) +* [Profiling](#profiling) +* [Streaming Logs](#streaming-logs) +* [Querying Logs](#querying-logs) +* [Further Reading](#further-reading) + * [Using the default logger](#using-the-default-logger) + * [Awaiting logs to be written in `winston`](#awaiting-logs-to-be-written-in-winston) + * [Working with multiple Loggers in `winston`](#working-with-multiple-loggers-in-winston) +* [Installation](#installation) +* [Run Tests](#run-tests) + +## Logging + +Logging levels in `winston` conform to the severity ordering specified by +[RFC5424]: _severity of all levels is assumed to be numerically **ascending** +from most important to least important._ + +``` js +const levels = { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 +}; +``` + +### Creating your own Logger +You get started by creating a logger using `winston.createLogger`: + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.Console(), + new winston.transports.File({ filename: 'combined.log' }) + ] +}); +``` + +A logger accepts the following parameters: + +| Name | Default | Description | +| ------------- | --------------------------- | --------------- | +| `level` | `'info'` | Log only if [`info.level`](#streams-objectmode-and-info-objects) less than or equal to this level | +| `levels` | `winston.config.npm.levels` | Levels (and colors) representing log priorities | +| `format` | `winston.format.json` | Formatting for `info` messages (see: [Formats]) | +| `transports` | `[]` _(No transports)_ | Set of logging targets for `info` messages | +| `exitOnError` | `true` | If false, handled exceptions will not cause `process.exit` | +| `silent` | `false` | If true, all logs are suppressed | + +The levels provided to `createLogger` will be defined as convenience methods +on the `logger` returned. + +``` js +// +// Logging +// +logger.log({ + level: 'info', + message: 'Hello distributed log files!' +}); + +logger.info('Hello again distributed logs'); +``` + +You can add or remove transports from the `logger` once it has been provided +to you from `winston.createLogger`: + +``` js +const files = new winston.transports.File({ filename: 'combined.log' }); +const console = new winston.transports.Console(); + +logger + .clear() // Remove all transports + .add(console) // Add console transport + .add(files) // Add file transport + .remove(console); // Remove console transport +``` + +You can also wholesale reconfigure a `winston.Logger` instance using the +`configure` method: + +``` js +const logger = winston.createLogger({ + level: 'info', + transports: [ + new winston.transports.Console(), + new winston.transports.File({ filename: 'combined.log' }) + ] +}); + +// +// Replaces the previous transports with those in the +// new configuration wholesale. +// +const DailyRotateFile = require('winston-daily-rotate-file'); +logger.configure({ + level: 'verbose', + transports: [ + new DailyRotateFile(opts) + ] +}); +``` + +### Creating child loggers + +You can create child loggers from existing loggers to pass metadata overrides: + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.Console(), + ] +}); + +const childLogger = logger.child({ requestId: '451' }); +``` + +### Streams, `objectMode`, and `info` objects + +In `winston`, both `Logger` and `Transport` instances are treated as +[`objectMode`](https://nodejs.org/api/stream.html#stream_object_mode) +streams that accept an `info` object. + +The `info` parameter provided to a given format represents a single log +message. The object itself is mutable. Every `info` must have at least the +`level` and `message` properties: + +``` js +const info = { + level: 'info', // Level of the logging message + message: 'Hey! Log something?' // Descriptive message being logged. +}; +``` + +Properties **besides level and message** are considered as "`meta`". i.e.: + +``` js +const { level, message, ...meta } = info; +``` + +Several of the formats in `logform` itself add additional properties: + +| Property | Format added by | Description | +| ----------- | --------------- | ----------- | +| `splat` | `splat()` | String interpolation splat for `%d %s`-style messages. | +| `timestamp` | `timestamp()` | timestamp the message was received. | +| `label` | `label()` | Custom label associated with each message. | +| `ms` | `ms()` | Number of milliseconds since the previous log message. | + +As a consumer you may add whatever properties you wish – _internal state is +maintained by `Symbol` properties:_ + +- `Symbol.for('level')` _**(READ-ONLY)**:_ equal to `level` property. + **Is treated as immutable by all code.** +- `Symbol.for('message'):` complete string message set by "finalizing formats": + - `json` + - `logstash` + - `printf` + - `prettyPrint` + - `simple` +- `Symbol.for('splat')`: additional string interpolation arguments. _Used + exclusively by `splat()` format._ + +These Symbols are stored in another package: `triple-beam` so that all +consumers of `logform` can have the same Symbol reference. i.e.: + +``` js +const { LEVEL, MESSAGE, SPLAT } = require('triple-beam'); + +console.log(LEVEL === Symbol.for('level')); +// true + +console.log(MESSAGE === Symbol.for('message')); +// true + +console.log(SPLAT === Symbol.for('splat')); +// true +``` + +> **NOTE:** any `{ message }` property in a `meta` object provided will +> automatically be concatenated to any `msg` already provided: For +> example the below will concatenate 'world' onto 'hello': +> +> ``` js +> logger.log('error', 'hello', { message: 'world' }); +> logger.info('hello', { message: 'world' }); +> ``` + +## Formats + +Formats in `winston` can be accessed from `winston.format`. They are +implemented in [`logform`](https://github.com/winstonjs/logform), a separate +module from `winston`. This allows flexibility when writing your own transports +in case you wish to include a default format with your transport. + +In modern versions of `node` template strings are very performant and are the +recommended way for doing most end-user formatting. If you want to bespoke +format your logs, `winston.format.printf` is for you: + +``` js +const { createLogger, format, transports } = require('winston'); +const { combine, timestamp, label, printf } = format; + +const myFormat = printf(({ level, message, label, timestamp }) => { + return `${timestamp} [${label}] ${level}: ${message}`; +}); + +const logger = createLogger({ + format: combine( + label({ label: 'right meow!' }), + timestamp(), + myFormat + ), + transports: [new transports.Console()] +}); +``` + +To see what built-in formats are available and learn more about creating your +own custom logging formats, see [`logform`][logform]. + +### Combining formats + +Any number of formats may be combined into a single format using +`format.combine`. Since `format.combine` takes no `opts`, as a convenience it +returns pre-created instance of the combined format. + +``` js +const { createLogger, format, transports } = require('winston'); +const { combine, timestamp, label, prettyPrint } = format; + +const logger = createLogger({ + format: combine( + label({ label: 'right meow!' }), + timestamp(), + prettyPrint() + ), + transports: [new transports.Console()] +}) + +logger.log({ + level: 'info', + message: 'What time is the testing at?' +}); +// Outputs: +// { level: 'info', +// message: 'What time is the testing at?', +// label: 'right meow!', +// timestamp: '2017-09-30T03:57:26.875Z' } +``` + +### String interpolation + +The `log` method provides the string interpolation using [util.format]. **It +must be enabled using `format.splat()`.** + +Below is an example that defines a format with string interpolation of +messages using `format.splat` and then serializes the entire `info` message +using `format.simple`. + +``` js +const { createLogger, format, transports } = require('winston'); +const logger = createLogger({ + format: format.combine( + format.splat(), + format.simple() + ), + transports: [new transports.Console()] +}); + +// info: test message my string {} +logger.log('info', 'test message %s', 'my string'); + +// info: test message 123 {} +logger.log('info', 'test message %d', 123); + +// info: test message first second {number: 123} +logger.log('info', 'test message %s, %s', 'first', 'second', { number: 123 }); +``` + +### Filtering `info` Objects + +If you wish to filter out a given `info` Object completely when logging then +simply return a falsey value. + +``` js +const { createLogger, format, transports } = require('winston'); + +// Ignore log messages if they have { private: true } +const ignorePrivate = format((info, opts) => { + if (info.private) { return false; } + return info; +}); + +const logger = createLogger({ + format: format.combine( + ignorePrivate(), + format.json() + ), + transports: [new transports.Console()] +}); + +// Outputs: {"level":"error","message":"Public error to share"} +logger.log({ + level: 'error', + message: 'Public error to share' +}); + +// Messages with { private: true } will not be written when logged. +logger.log({ + private: true, + level: 'error', + message: 'This is super secret - hide it.' +}); +``` + +Use of `format.combine` will respect any falsey values return and stop +evaluation of later formats in the series. For example: + +``` js +const { format } = require('winston'); +const { combine, timestamp, label } = format; + +const willNeverThrow = format.combine( + format(info => { return false })(), // Ignores everything + format(info => { throw new Error('Never reached') })() +); +``` + +### Creating custom formats + +Formats are prototypal objects (i.e. class instances) that define a single +method: `transform(info, opts)` and return the mutated `info`: + +- `info`: an object representing the log message. +- `opts`: setting specific to the current instance of the format. + +They are expected to return one of two things: + +- **An `info` Object** representing the modified `info` argument. Object +references need not be preserved if immutability is preferred. All current +built-in formats consider `info` mutable, but [immutablejs] is being +considered for future releases. +- **A falsey value** indicating that the `info` argument should be ignored by the +caller. (See: [Filtering `info` Objects](#filtering-info-objects)) below. + +`winston.format` is designed to be as simple as possible. To define a new +format simple pass it a `transform(info, opts)` function to get a new +`Format`. + +The named `Format` returned can be used to create as many copies of the given +`Format` as desired: + +``` js +const { format } = require('winston'); + +const volume = format((info, opts) => { + if (opts.yell) { + info.message = info.message.toUpperCase(); + } else if (opts.whisper) { + info.message = info.message.toLowerCase(); + } + + return info; +}); + +// `volume` is now a function that returns instances of the format. +const scream = volume({ yell: true }); +console.dir(scream.transform({ + level: 'info', + message: `sorry for making you YELL in your head!` +}, scream.options)); +// { +// level: 'info' +// message: 'SORRY FOR MAKING YOU YELL IN YOUR HEAD!' +// } + +// `volume` can be used multiple times to create different formats. +const whisper = volume({ whisper: true }); +console.dir(whisper.transform({ + level: 'info', + message: `WHY ARE THEY MAKING US YELL SO MUCH!` +}, whisper.options)); +// { +// level: 'info' +// message: 'why are they making us yell so much!' +// } +``` + +## Logging Levels + +Logging levels in `winston` conform to the severity ordering specified by +[RFC5424]: _severity of all levels is assumed to be numerically **ascending** +from most important to least important._ + +Each `level` is given a specific integer priority. The higher the priority the +more important the message is considered to be, and the lower the +corresponding integer priority. For example, as specified exactly in RFC5424 +the `syslog` levels are prioritized from 0 to 7 (highest to lowest). + +```js +{ + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 +} +``` + +Similarly, `npm` logging levels are prioritized from 0 to 6 (highest to +lowest): + +``` js +{ + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 +} +``` + +If you do not explicitly define the levels that `winston` should use, the +`npm` levels above will be used. + +### Using Logging Levels + +Setting the level for your logging message can be accomplished in one of two +ways. You can pass a string representing the logging level to the log() method +or use the level specified methods defined on every winston Logger. + +``` js +// +// Any logger instance +// +logger.log('silly', "127.0.0.1 - there's no place like home"); +logger.log('debug', "127.0.0.1 - there's no place like home"); +logger.log('verbose', "127.0.0.1 - there's no place like home"); +logger.log('info', "127.0.0.1 - there's no place like home"); +logger.log('warn', "127.0.0.1 - there's no place like home"); +logger.log('error', "127.0.0.1 - there's no place like home"); +logger.info("127.0.0.1 - there's no place like home"); +logger.warn("127.0.0.1 - there's no place like home"); +logger.error("127.0.0.1 - there's no place like home"); + +// +// Default logger +// +winston.log('info', "127.0.0.1 - there's no place like home"); +winston.info("127.0.0.1 - there's no place like home"); +``` + +`winston` allows you to define a `level` property on each transport which +specifies the **maximum** level of messages that a transport should log. For +example, using the `syslog` levels you could log only `error` messages to the +console and everything `info` and below to a file (which includes `error` +messages): + +``` js +const logger = winston.createLogger({ + levels: winston.config.syslog.levels, + transports: [ + new winston.transports.Console({ level: 'error' }), + new winston.transports.File({ + filename: 'combined.log', + level: 'info' + }) + ] +}); +``` + +You may also dynamically change the log level of a transport: + +``` js +const transports = { + console: new winston.transports.Console({ level: 'warn' }), + file: new winston.transports.File({ filename: 'combined.log', level: 'error' }) +}; + +const logger = winston.createLogger({ + transports: [ + transports.console, + transports.file + ] +}); + +logger.info('Will not be logged in either transport!'); +transports.console.level = 'info'; +transports.file.level = 'info'; +logger.info('Will be logged in both transports!'); +``` + +`winston` supports customizable logging levels, defaulting to npm style +logging levels. Levels must be specified at the time of creating your logger. + +### Using Custom Logging Levels + +In addition to the predefined `npm`, `syslog`, and `cli` levels available in +`winston`, you can also choose to define your own: + +``` js +const myCustomLevels = { + levels: { + foo: 0, + bar: 1, + baz: 2, + foobar: 3 + }, + colors: { + foo: 'blue', + bar: 'green', + baz: 'yellow', + foobar: 'red' + } +}; + +const customLevelLogger = winston.createLogger({ + levels: myCustomLevels.levels +}); + +customLevelLogger.foobar('some foobar level-ed message'); +``` + +Although there is slight repetition in this data structure, it enables simple +encapsulation if you do not want to have colors. If you do wish to have +colors, in addition to passing the levels to the Logger itself, you must make +winston aware of them: + +``` js +winston.addColors(myCustomLevels.colors); +``` + +This enables loggers using the `colorize` formatter to appropriately color and style +the output of custom levels. + +Additionally, you can also change background color and font style. +For example, +``` js +baz: 'italic yellow', +foobar: 'bold red cyanBG' +``` + +Possible options are below. + +* Font styles: `bold`, `dim`, `italic`, `underline`, `inverse`, `hidden`, + `strikethrough`. + +* Font foreground colors: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, + `cyan`, `white`, `gray`, `grey`. + +* Background colors: `blackBG`, `redBG`, `greenBG`, `yellowBG`, `blueBG` + `magentaBG`, `cyanBG`, `whiteBG` + +### Colorizing Standard logging levels + +To colorize the standard logging level add +```js +winston.format.combine( + winston.format.colorize(), + winston.format.json() +); +``` +where `winston.format.json()` is whatever other formatter you want to use. The `colorize` formatter must come before any formatters adding text you wish to color. + +## Transports + +There are several [core transports] included in `winston`, which leverage the +built-in networking and file I/O offered by Node.js core. In addition, there +are [additional transports] written by members of the community. + +## Multiple transports of the same type + +It is possible to use multiple transports of the same type e.g. +`winston.transports.File` when you construct the transport. + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.File({ + filename: 'combined.log', + level: 'info' + }), + new winston.transports.File({ + filename: 'errors.log', + level: 'error' + }) + ] +}); +``` + +If you later want to remove one of these transports you can do so by using the +transport itself. e.g.: + +``` js +const combinedLogs = logger.transports.find(transport => { + return transport.filename === 'combined.log' +}); + +logger.remove(combinedLogs); +``` + +## Adding Custom Transports + +Adding a custom transport is easy. All you need to do is accept any options +you need, implement a log() method, and consume it with `winston`. + +``` js +const Transport = require('winston-transport'); +const util = require('util'); + +// +// Inherit from `winston-transport` so you can take advantage +// of the base functionality and `.exceptions.handle()`. +// +module.exports = class YourCustomTransport extends Transport { + constructor(opts) { + super(opts); + // + // Consume any custom options here. e.g.: + // - Connection information for databases + // - Authentication information for APIs (e.g. loggly, papertrail, + // logentries, etc.). + // + } + + log(info, callback) { + setImmediate(() => { + this.emit('logged', info); + }); + + // Perform the writing to the remote service + callback(); + } +}; +``` + +## Common Transport options + +As every transport inherits from [winston-transport], it's possible to set +a custom format and a custom log level on each transport separately: + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.File({ + filename: 'error.log', + level: 'error', + format: winston.format.json() + }), + new transports.Http({ + level: 'warn', + format: winston.format.json() + }), + new transports.Console({ + level: 'info', + format: winston.format.combine( + winston.format.colorize(), + winston.format.simple() + ) + }) + ] +}); +``` + +## Exceptions + +### Handling Uncaught Exceptions with winston + +With `winston`, it is possible to catch and log `uncaughtException` events +from your process. With your own logger instance you can enable this behavior +when it's created or later on in your applications lifecycle: + +``` js +const { createLogger, transports } = require('winston'); + +// Enable exception handling when you create your logger. +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ], + exceptionHandlers: [ + new transports.File({ filename: 'exceptions.log' }) + ] +}); + +// Or enable it later on by adding a transport or using `.exceptions.handle` +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ] +}); + +// Call exceptions.handle with a transport to handle exceptions +logger.exceptions.handle( + new transports.File({ filename: 'exceptions.log' }) +); +``` + +If you want to use this feature with the default logger, simply call +`.exceptions.handle()` with a transport instance. + +``` js +// +// You can add a separate exception logger by passing it to `.exceptions.handle` +// +winston.exceptions.handle( + new winston.transports.File({ filename: 'path/to/exceptions.log' }) +); + +// +// Alternatively you can set `handleExceptions` to true when adding transports +// to winston. +// +winston.add(new winston.transports.File({ + filename: 'path/to/combined.log', + handleExceptions: true +})); +``` + +### To Exit or Not to Exit + +By default, winston will exit after logging an uncaughtException. If this is +not the behavior you want, set `exitOnError = false` + +``` js +const logger = winston.createLogger({ exitOnError: false }); + +// +// or, like this: +// +logger.exitOnError = false; +``` + +When working with custom logger instances, you can pass in separate transports +to the `exceptionHandlers` property or set `handleExceptions` on any +transport. + +##### Example 1 + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.File({ filename: 'path/to/combined.log' }) + ], + exceptionHandlers: [ + new winston.transports.File({ filename: 'path/to/exceptions.log' }) + ] +}); +``` + +##### Example 2 + +``` js +const logger = winston.createLogger({ + transports: [ + new winston.transports.Console({ + handleExceptions: true + }) + ], + exitOnError: false +}); +``` + +The `exitOnError` option can also be a function to prevent exit on only +certain types of errors: + +``` js +function ignoreEpipe(err) { + return err.code !== 'EPIPE'; +} + +const logger = winston.createLogger({ exitOnError: ignoreEpipe }); + +// +// or, like this: +// +logger.exitOnError = ignoreEpipe; +``` + +## Rejections + +### Handling Uncaught Promise Rejections with winston + +With `winston`, it is possible to catch and log `uncaughtRejection` events +from your process. With your own logger instance you can enable this behavior +when it's created or later on in your applications lifecycle: + +``` js +const { createLogger, transports } = require('winston'); + +// Enable rejection handling when you create your logger. +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ], + rejectionHandlers: [ + new transports.File({ filename: 'rejections.log' }) + ] +}); + +// Or enable it later on by adding a transport or using `.rejections.handle` +const logger = createLogger({ + transports: [ + new transports.File({ filename: 'combined.log' }) + ] +}); + +// Call rejections.handle with a transport to handle rejections +logger.rejections.handle( + new transports.File({ filename: 'rejections.log' }) +); +``` + +If you want to use this feature with the default logger, simply call +`.rejections.handle()` with a transport instance. + +``` js +// +// You can add a separate rejection logger by passing it to `.rejections.handle` +// +winston.rejections.handle( + new winston.transports.File({ filename: 'path/to/rejections.log' }) +); + +// +// Alternatively you can set `handleRejections` to true when adding transports +// to winston. +// +winston.add(new winston.transports.File({ + filename: 'path/to/combined.log', + handleRejections: true +})); +``` + +## Profiling + +In addition to logging messages and metadata, `winston` also has a simple +profiling mechanism implemented for any logger: + +``` js +// +// Start profile of 'test' +// +logger.profile('test'); + +setTimeout(function () { + // + // Stop profile of 'test'. Logging will now take place: + // '17 Jan 21:00:00 - info: test duration=1000ms' + // + logger.profile('test'); +}, 1000); +``` + +Also you can start a timer and keep a reference that you can call `.done()`` +on: + +``` js + // Returns an object corresponding to a specific timing. When done + // is called the timer will finish and log the duration. e.g.: + // + const profiler = logger.startTimer(); + setTimeout(function () { + profiler.done({ message: 'Logging message' }); + }, 1000); +``` + +All profile messages are set to 'info' level by default, and both message and +metadata are optional. For individual profile messages, you can override the default log level by supplying a metadata object with a `level` property: + +```js +logger.profile('test', { level: 'debug' }); +``` + +## Querying Logs + +`winston` supports querying of logs with Loggly-like options. [See Loggly +Search API](https://www.loggly.com/docs/api-retrieving-data/). Specifically: +`File`, `Couchdb`, `Redis`, `Loggly`, `Nssocket`, and `Http`. + +``` js +const options = { + from: new Date() - (24 * 60 * 60 * 1000), + until: new Date(), + limit: 10, + start: 0, + order: 'desc', + fields: ['message'] +}; + +// +// Find items logged between today and yesterday. +// +logger.query(options, function (err, results) { + if (err) { + /* TODO: handle me */ + throw err; + } + + console.log(results); +}); +``` + +## Streaming Logs +Streaming allows you to stream your logs back from your chosen transport. + +``` js +// +// Start at the end. +// +winston.stream({ start: -1 }).on('log', function(log) { + console.log(log); +}); +``` + +## Further Reading + +### Using the Default Logger + +The default logger is accessible through the `winston` module directly. Any +method that you could call on an instance of a logger is available on the +default logger: + +``` js +const winston = require('winston'); + +winston.log('info', 'Hello distributed log files!'); +winston.info('Hello again distributed logs'); + +winston.level = 'debug'; +winston.log('debug', 'Now my debug messages are written to console!'); +``` + +By default, no transports are set on the default logger. You must +add or remove transports via the `add()` and `remove()` methods: + +``` js +const files = new winston.transports.File({ filename: 'combined.log' }); +const console = new winston.transports.Console(); + +winston.add(console); +winston.add(files); +winston.remove(console); +``` + +Or do it with one call to configure(): + +``` js +winston.configure({ + transports: [ + new winston.transports.File({ filename: 'somefile.log' }) + ] +}); +``` + +For more documentation about working with each individual transport supported +by `winston` see the [`winston` Transports](docs/transports.md) document. + +### Awaiting logs to be written in `winston` + +Often it is useful to wait for your logs to be written before exiting the +process. Each instance of `winston.Logger` is also a [Node.js stream]. A +`finish` event will be raised when all logs have flushed to all transports +after the stream has been ended. + +``` js +const transport = new winston.transports.Console(); +const logger = winston.createLogger({ + transports: [transport] +}); + +logger.on('finish', function (info) { + // All `info` log messages has now been logged +}); + +logger.info('CHILL WINSTON!', { seriously: true }); +logger.end(); +``` + +It is also worth mentioning that the logger also emits an 'error' event which +you should handle or suppress if you don't want unhandled exceptions: + +``` js +// +// Handle errors +// +logger.on('error', function (err) { /* Do Something */ }); +``` + +### Working with multiple Loggers in winston + +Often in larger, more complex, applications it is necessary to have multiple +logger instances with different settings. Each logger is responsible for a +different feature area (or category). This is exposed in `winston` in two +ways: through `winston.loggers` and instances of `winston.Container`. In fact, +`winston.loggers` is just a predefined instance of `winston.Container`: + +``` js +const winston = require('winston'); +const { format } = winston; +const { combine, label, json } = format; + +// +// Configure the logger for `category1` +// +winston.loggers.add('category1', { + format: combine( + label({ label: 'category one' }), + json() + ), + transports: [ + new winston.transports.Console({ level: 'silly' }), + new winston.transports.File({ filename: 'somefile.log' }) + ] +}); + +// +// Configure the logger for `category2` +// +winston.loggers.add('category2', { + format: combine( + label({ label: 'category two' }), + json() + ), + transports: [ + new winston.transports.Http({ host: 'localhost', port:8080 }) + ] +}); +``` + +Now that your loggers are setup, you can require winston _in any file in your +application_ and access these pre-configured loggers: + +``` js +const winston = require('winston'); + +// +// Grab your preconfigured loggers +// +const category1 = winston.loggers.get('category1'); +const category2 = winston.loggers.get('category2'); + +category1.info('logging to file and console transports'); +category2.info('logging to http transport'); +``` + +If you prefer to manage the `Container` yourself, you can simply instantiate one: + +``` js +const winston = require('winston'); +const { format } = winston; +const { combine, label, json } = format; + +const container = new winston.Container(); + +container.add('category1', { + format: combine( + label({ label: 'category one' }), + json() + ), + transports: [ + new winston.transports.Console({ level: 'silly' }), + new winston.transports.File({ filename: 'somefile.log' }) + ] +}); + +const category1 = container.get('category1'); +category1.info('logging to file and console transports'); +``` + +## Installation + +``` bash +npm install winston +``` + +``` bash +yarn add winston +``` + +## Run Tests + +All of the winston tests are written with [`mocha`][mocha], [`nyc`][nyc], and +[`assume`][assume]. They can be run with `npm`. + +``` bash +npm test +``` + +#### Author: [Charlie Robbins] +#### Contributors: [Jarrett Cruger], [David Hyde], [Chris Alderson] + +[Transports]: #transports +[Logging levels]: #logging-levels +[Formats]: #formats +[Using custom logging levels]: #using-custom-logging-levels +[Adding Custom Transports]: #adding-custom-transports +[core transports]: docs/transports.md#winston-core +[additional transports]: docs/transports.md#additional-transports + +[RFC5424]: https://tools.ietf.org/html/rfc5424 +[util.format]: https://nodejs.org/dist/latest/docs/api/util.html#util_util_format_format_args +[mocha]: https://mochajs.org +[nyc]: https://github.com/istanbuljs/nyc +[assume]: https://github.com/bigpipe/assume +[logform]: https://github.com/winstonjs/logform#readme +[winston-transport]: https://github.com/winstonjs/winston-transport + +[Read the `winston@2.x` documentation]: https://github.com/winstonjs/winston/tree/2.x + +[quick-example]: https://github.com/winstonjs/winston/blob/master/examples/quick-start.js +[examples]: https://github.com/winstonjs/winston/tree/master/examples + +[Charlie Robbins]: http://github.com/indexzero +[Jarrett Cruger]: https://github.com/jcrugzz +[David Hyde]: https://github.com/dabh +[Chris Alderson]: https://github.com/chrisalderson diff --git a/build/node_modules/winston/dist/winston.js b/build/node_modules/winston/dist/winston.js new file mode 100644 index 00000000..f037f59b --- /dev/null +++ b/build/node_modules/winston/dist/winston.js @@ -0,0 +1,172 @@ +/** + * winston.js: Top-level include defining Winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +var logform = require('logform'); + +var _require = require('./winston/common'), + warn = _require.warn; +/** + * Setup to expose. + * @type {Object} + */ + + +var winston = exports; +/** + * Expose version. Use `require` method for `webpack` support. + * @type {string} + */ + +winston.version = require('../package.json').version; +/** + * Include transports defined by default by winston + * @type {Array} + */ + +winston.transports = require('./winston/transports'); +/** + * Expose utility methods + * @type {Object} + */ + +winston.config = require('./winston/config'); +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ + +winston.addColors = logform.levels; +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ + +winston.format = logform.format; +/** + * Expose core Logging-related prototypes. + * @type {function} + */ + +winston.createLogger = require('./winston/create-logger'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ + +winston.ExceptionHandler = require('./winston/exception-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ + +winston.RejectionHandler = require('./winston/rejection-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Container} + */ + +winston.Container = require('./winston/container'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ + +winston.Transport = require('winston-transport'); +/** + * We create and expose a default `Container` to `winston.loggers` so that the + * programmer may manage multiple `winston.Logger` instances without any + * additional overhead. + * @example + * // some-file1.js + * const logger = require('winston').loggers.get('something'); + * + * // some-file2.js + * const logger = require('winston').loggers.get('something'); + */ + +winston.loggers = new winston.Container(); +/** + * We create and expose a 'defaultLogger' so that the programmer may do the + * following without the need to create an instance of winston.Logger directly: + * @example + * const winston = require('winston'); + * winston.log('info', 'some message'); + * winston.error('some error'); + */ + +var defaultLogger = winston.createLogger(); // Pass through the target methods onto `winston. + +Object.keys(winston.config.npm.levels).concat(['log', 'query', 'stream', 'add', 'remove', 'clear', 'profile', 'startTimer', 'handleExceptions', 'unhandleExceptions', 'handleRejections', 'unhandleRejections', 'configure', 'child']).forEach(function (method) { + return winston[method] = function () { + return defaultLogger[method].apply(defaultLogger, arguments); + }; +}); +/** + * Define getter / setter for the default logger level which need to be exposed + * by winston. + * @type {string} + */ + +Object.defineProperty(winston, 'level', { + get: function get() { + return defaultLogger.level; + }, + set: function set(val) { + defaultLogger.level = val; + } +}); +/** + * Define getter for `exceptions` which replaces `handleExceptions` and + * `unhandleExceptions`. + * @type {Object} + */ + +Object.defineProperty(winston, 'exceptions', { + get: function get() { + return defaultLogger.exceptions; + } +}); +/** + * Define getters / setters for appropriate properties of the default logger + * which need to be exposed by winston. + * @type {Logger} + */ + +['exitOnError'].forEach(function (prop) { + Object.defineProperty(winston, prop, { + get: function get() { + return defaultLogger[prop]; + }, + set: function set(val) { + defaultLogger[prop] = val; + } + }); +}); +/** + * The default transports and exceptionHandlers for the default winston logger. + * @type {Object} + */ + +Object.defineProperty(winston, 'default', { + get: function get() { + return { + exceptionHandlers: defaultLogger.exceptionHandlers, + rejectionHandlers: defaultLogger.rejectionHandlers, + transports: defaultLogger.transports + }; + } +}); // Have friendlier breakage notices for properties that were exposed by default +// on winston < 3.0. + +warn.deprecated(winston, 'setLevels'); +warn.forFunctions(winston, 'useFormat', ['cli']); +warn.forProperties(winston, 'useFormat', ['padLevels', 'stripColors']); +warn.forFunctions(winston, 'deprecated', ['addRewriter', 'addFilter', 'clone', 'extend']); +warn.forProperties(winston, 'deprecated', ['emitErrs', 'levelLength']); // Throw a useful error when users attempt to run `new winston.Logger`. + +warn.moved(winston, 'createLogger', 'Logger'); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/common.js b/build/node_modules/winston/dist/winston/common.js new file mode 100644 index 00000000..31aa7111 --- /dev/null +++ b/build/node_modules/winston/dist/winston/common.js @@ -0,0 +1,56 @@ +/** + * common.js: Internal helper and utility functions for winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +var _require = require('util'), + format = _require.format; +/** + * Set of simple deprecation notices and a way to expose them for a set of + * properties. + * @type {Object} + * @private + */ + + +exports.warn = { + deprecated: function deprecated(prop) { + return function () { + throw new Error(format('{ %s } was removed in winston@3.0.0.', prop)); + }; + }, + useFormat: function useFormat(prop) { + return function () { + throw new Error([format('{ %s } was removed in winston@3.0.0.', prop), 'Use a custom winston.format = winston.format(function) instead.'].join('\n')); + }; + }, + forFunctions: function forFunctions(obj, type, props) { + props.forEach(function (prop) { + obj[prop] = exports.warn[type](prop); + }); + }, + moved: function moved(obj, movedTo, prop) { + function movedNotice() { + return function () { + throw new Error([format('winston.%s was moved in winston@3.0.0.', prop), format('Use a winston.%s instead.', movedTo)].join('\n')); + }; + } + + Object.defineProperty(obj, prop, { + get: movedNotice, + set: movedNotice + }); + }, + forProperties: function forProperties(obj, type, props) { + props.forEach(function (prop) { + var notice = exports.warn[type](prop); + Object.defineProperty(obj, prop, { + get: notice, + set: notice + }); + }); + } +}; \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/config/index.js b/build/node_modules/winston/dist/winston/config/index.js new file mode 100644 index 00000000..0eb13f34 --- /dev/null +++ b/build/node_modules/winston/dist/winston/config/index.js @@ -0,0 +1,37 @@ +/** + * index.js: Default settings for all levels that winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +var logform = require('logform'); + +var _require = require('triple-beam'), + configs = _require.configs; +/** + * Export config set for the CLI. + * @type {Object} + */ + + +exports.cli = logform.levels(configs.cli); +/** + * Export config set for npm. + * @type {Object} + */ + +exports.npm = logform.levels(configs.npm); +/** + * Export config set for the syslog. + * @type {Object} + */ + +exports.syslog = logform.levels(configs.syslog); +/** + * Hoist addColors from logform where it was refactored into in winston@3. + * @type {Object} + */ + +exports.addColors = logform.levels; \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/container.js b/build/node_modules/winston/dist/winston/container.js new file mode 100644 index 00000000..a1d329b4 --- /dev/null +++ b/build/node_modules/winston/dist/winston/container.js @@ -0,0 +1,147 @@ +/** + * container.js: Inversion of control container for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var createLogger = require('./create-logger'); +/** + * Inversion of control container for winston logger instances. + * @type {Container} + */ + + +module.exports = /*#__PURE__*/function () { + /** + * Constructor function for the Container object responsible for managing a + * set of `winston.Logger` instances based on string ids. + * @param {!Object} [options={}] - Default pass-thru options for Loggers. + */ + function Container() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, Container); + + this.loggers = new Map(); + this.options = options; + } + /** + * Retreives a `winston.Logger` instance for the specified `id`. If an + * instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + + + _createClass(Container, [{ + key: "add", + value: function add(id, options) { + var _this = this; + + if (!this.loggers.has(id)) { + // Remark: Simple shallow clone for configuration options in case we pass + // in instantiated protoypal objects + options = Object.assign({}, options || this.options); + var existing = options.transports || this.options.transports; // Remark: Make sure if we have an array of transports we slice it to + // make copies of those references. + + options.transports = existing ? existing.slice() : []; + var logger = createLogger(options); + logger.on('close', function () { + return _this._delete(id); + }); + this.loggers.set(id, logger); + } + + return this.loggers.get(id); + } + /** + * Retreives a `winston.Logger` instance for the specified `id`. If + * an instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + + }, { + key: "get", + value: function get(id, options) { + return this.add(id, options); + } + /** + * Check if the container has a logger with the id. + * @param {?string} id - The id of the Logger instance to find. + * @returns {boolean} - Boolean value indicating if this instance has a + * logger with the specified `id`. + */ + + }, { + key: "has", + value: function has(id) { + return !!this.loggers.has(id); + } + /** + * Closes a `Logger` instance with the specified `id` if it exists. + * If no `id` is supplied then all Loggers are closed. + * @param {?string} id - The id of the Logger instance to close. + * @returns {undefined} + */ + + }, { + key: "close", + value: function close(id) { + var _this2 = this; + + if (id) { + return this._removeLogger(id); + } + + this.loggers.forEach(function (val, key) { + return _this2._removeLogger(key); + }); + } + /** + * Remove a logger based on the id. + * @param {!string} id - The id of the logger to remove. + * @returns {undefined} + * @private + */ + + }, { + key: "_removeLogger", + value: function _removeLogger(id) { + if (!this.loggers.has(id)) { + return; + } + + var logger = this.loggers.get(id); + logger.close(); + + this._delete(id); + } + /** + * Deletes a `Logger` instance with the specified `id`. + * @param {!string} id - The id of the Logger instance to delete from + * container. + * @returns {undefined} + * @private + */ + + }, { + key: "_delete", + value: function _delete(id) { + this.loggers["delete"](id); + } + }]); + + return Container; +}(); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/create-logger.js b/build/node_modules/winston/dist/winston/create-logger.js new file mode 100644 index 00000000..8ba07bc3 --- /dev/null +++ b/build/node_modules/winston/dist/winston/create-logger.js @@ -0,0 +1,141 @@ +/** + * create-logger.js: Logger factory for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL; + +var config = require('./config'); + +var Logger = require('./logger'); + +var debug = require('@dabh/diagnostics')('winston:create-logger'); + +function isLevelEnabledFunctionName(level) { + return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled'; +} +/** + * Create a new instance of a winston Logger. Creates a new + * prototype for each instance. + * @param {!Object} opts - Options for the created logger. + * @returns {Logger} - A newly created logger instance. + */ + + +module.exports = function () { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + // + // Default levels: npm + // + opts.levels = opts.levels || config.npm.levels; + /** + * DerivedLogger to attach the logs level methods. + * @type {DerivedLogger} + * @extends {Logger} + */ + + var DerivedLogger = /*#__PURE__*/function (_Logger) { + _inherits(DerivedLogger, _Logger); + + var _super = _createSuper(DerivedLogger); + + /** + * Create a new class derived logger for which the levels can be attached to + * the prototype of. This is a V8 optimization that is well know to increase + * performance of prototype functions. + * @param {!Object} options - Options for the created logger. + */ + function DerivedLogger(options) { + _classCallCheck(this, DerivedLogger); + + return _super.call(this, options); + } + + return DerivedLogger; + }(Logger); + + var logger = new DerivedLogger(opts); // + // Create the log level methods for the derived logger. + // + + Object.keys(opts.levels).forEach(function (level) { + debug('Define prototype method for "%s"', level); + + if (level === 'log') { + // eslint-disable-next-line no-console + console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + return; + } // + // Define prototype methods for each log level e.g.: + // logger.log('info', msg) implies these methods are defined: + // - logger.info(msg) + // - logger.isInfoEnabled() + // + // Remark: to support logger.child this **MUST** be a function + // so it'll always be called on the instance instead of a fixed + // place in the prototype chain. + // + + + DerivedLogger.prototype[level] = function () { + // Prefer any instance scope, but default to "root" logger + var self = this || logger; // Optimize the hot-path which is the single object. + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (args.length === 1) { + var msg = args[0]; + var info = msg && msg.message && msg || { + message: msg + }; + info.level = info[LEVEL] = level; + + self._addDefaultMeta(info); + + self.write(info); + return this || logger; + } // When provided nothing assume the empty string + + + if (args.length === 0) { + self.log(level, ''); + return self; + } // Otherwise build argument list which could potentially conform to + // either: + // . v3 API: log(obj) + // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback]) + + + return self.log.apply(self, [level].concat(args)); + }; + + DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () { + return (this || logger).isLevelEnabled(level); + }; + }); + return logger; +}; \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/exception-handler.js b/build/node_modules/winston/dist/winston/exception-handler.js new file mode 100644 index 00000000..e275e40d --- /dev/null +++ b/build/node_modules/winston/dist/winston/exception-handler.js @@ -0,0 +1,288 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var os = require('os'); + +var asyncForEach = require('async/forEach'); + +var debug = require('@dabh/diagnostics')('winston:exception'); + +var once = require('one-time'); + +var stackTrace = require('stack-trace'); + +var ExceptionStream = require('./exception-stream'); +/** + * Object for handling uncaughtException events. + * @type {ExceptionHandler} + */ + + +module.exports = /*#__PURE__*/function () { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + function ExceptionHandler(logger) { + _classCallCheck(this, ExceptionHandler); + + if (!logger) { + throw new Error('Logger is required to handle exceptions'); + } + + this.logger = logger; + this.handlers = new Map(); + } + /** + * Handles `uncaughtException` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + + + _createClass(ExceptionHandler, [{ + key: "handle", + value: function handle() { + var _this = this; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + args.forEach(function (arg) { + if (Array.isArray(arg)) { + return arg.forEach(function (handler) { + return _this._addHandler(handler); + }); + } + + _this._addHandler(arg); + }); + + if (!this.catcher) { + this.catcher = this._uncaughtException.bind(this); + process.on('uncaughtException', this.catcher); + } + } + /** + * Removes any handlers to `uncaughtException` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + + }, { + key: "unhandle", + value: function unhandle() { + var _this2 = this; + + if (this.catcher) { + process.removeListener('uncaughtException', this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach(function (wrapper) { + return _this2.logger.unpipe(wrapper); + }); + } + } + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getAllInfo", + value: function getAllInfo(err) { + var message = err.message; + + if (!message && typeof err === 'string') { + message = err; + } + + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: ["uncaughtException: ".concat(message || '(no error message)'), err.stack || ' No stack trace'].join('\n'), + stack: err.stack, + exception: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getProcessInfo", + value: function getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getOsInfo", + value: function getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getTrace", + value: function getTrace(err) { + var trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(function (site) { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + "function": site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + "native": site.isNative() + }; + }); + } + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + + }, { + key: "_addHandler", + value: function _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleExceptions = true; + var wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + + }, { + key: "_uncaughtException", + value: function _uncaughtException(err) { + var info = this.getAllInfo(err); + + var handlers = this._getExceptionHandlers(); // Calculate if we should exit on this error + + + var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError; + var timeout; + + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no exception handlers.'); // eslint-disable-next-line no-console + + console.warn('winston: not exiting process.'); + doExit = false; + } + + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + + if (doExit && !process._exiting) { + // Remark: Currently ignoring any exceptions from transports when + // catching uncaught exceptions. + if (timeout) { + clearTimeout(timeout); + } // eslint-disable-next-line no-process-exit + + + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } // Log to all transports attempting to listen for when they are completed. + + + asyncForEach(handlers, function (handler, next) { + var done = once(next); + var transport = handler.transport || handler; // Debug wrapping so that we can inspect what's going on under the covers. + + function onDone(event) { + return function () { + debug(event); + done(); + }; + } + + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, function () { + return doExit && gracefulExit(); + }); + this.logger.log(info); // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + + }, { + key: "_getExceptionHandlers", + value: function _getExceptionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleExceptions: true` + return this.logger.transports.filter(function (wrap) { + var transport = wrap.transport || wrap; + return transport.handleExceptions; + }); + } + }]); + + return ExceptionHandler; +}(); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/exception-stream.js b/build/node_modules/winston/dist/winston/exception-stream.js new file mode 100644 index 00000000..6e097dc4 --- /dev/null +++ b/build/node_modules/winston/dist/winston/exception-stream.js @@ -0,0 +1,94 @@ +/** + * exception-stream.js: TODO: add file header handler. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var _require = require('readable-stream'), + Writable = _require.Writable; +/** + * TODO: add class description. + * @type {ExceptionStream} + * @extends {Writable} + */ + + +module.exports = /*#__PURE__*/function (_Writable) { + _inherits(ExceptionStream, _Writable); + + var _super = _createSuper(ExceptionStream); + + /** + * Constructor function for the ExceptionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.exception` set to true. + * @param {!TransportStream} transport - Stream to filter to exceptions + */ + function ExceptionStream(transport) { + var _this; + + _classCallCheck(this, ExceptionStream); + + _this = _super.call(this, { + objectMode: true + }); + + if (!transport) { + throw new Error('ExceptionStream requires a TransportStream instance.'); + } // Remark (indexzero): we set `handleExceptions` here because it's the + // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers + + + _this.handleExceptions = true; + _this.transport = transport; + return _this; + } + /** + * Writes the info object to our transport instance if (and only if) the + * `exception` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + + + _createClass(ExceptionStream, [{ + key: "_write", + value: function _write(info, enc, callback) { + if (info.exception) { + return this.transport.log(info, callback); + } + + callback(); + return true; + } + }]); + + return ExceptionStream; +}(Writable); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/logger.js b/build/node_modules/winston/dist/winston/logger.js new file mode 100644 index 00000000..7741799e --- /dev/null +++ b/build/node_modules/winston/dist/winston/logger.js @@ -0,0 +1,752 @@ +/** + * logger.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var _require = require('readable-stream'), + Stream = _require.Stream, + Transform = _require.Transform; + +var asyncForEach = require('async/forEach'); + +var _require2 = require('triple-beam'), + LEVEL = _require2.LEVEL, + SPLAT = _require2.SPLAT; + +var isStream = require('is-stream'); + +var ExceptionHandler = require('./exception-handler'); + +var RejectionHandler = require('./rejection-handler'); + +var LegacyTransportStream = require('winston-transport/legacy'); + +var Profiler = require('./profiler'); + +var _require3 = require('./common'), + warn = _require3.warn; + +var config = require('./config'); +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ + + +var formatRegExp = /%[scdjifoO%]/g; +/** + * TODO: add class description. + * @type {Logger} + * @extends {Transform} + */ + +var Logger = /*#__PURE__*/function (_Transform) { + _inherits(Logger, _Transform); + + var _super = _createSuper(Logger); + + /** + * Constructor function for the Logger object responsible for persisting log + * messages and metadata to one or more transports. + * @param {!Object} options - foo + */ + function Logger(options) { + var _this; + + _classCallCheck(this, Logger); + + _this = _super.call(this, { + objectMode: true + }); + + _this.configure(options); + + return _this; + } + + _createClass(Logger, [{ + key: "child", + value: function child(defaultRequestMetadata) { + var logger = this; + return Object.create(logger, { + write: { + value: function value(info) { + var infoClone = Object.assign({}, defaultRequestMetadata, info); // Object.assign doesn't copy inherited Error + // properties so we have to do that explicitly + // + // Remark (indexzero): we should remove this + // since the errors format will handle this case. + // + + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + } + + logger.write(infoClone); + } + } + }); + } + /** + * This will wholesale reconfigure this instance by: + * 1. Resetting all transports. Older transports will be removed implicitly. + * 2. Set all other options including levels, colors, rewriters, filters, + * exceptionHandlers, etc. + * @param {!Object} options - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "configure", + value: function configure() { + var _this2 = this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + silent = _ref.silent, + format = _ref.format, + defaultMeta = _ref.defaultMeta, + levels = _ref.levels, + _ref$level = _ref.level, + level = _ref$level === void 0 ? 'info' : _ref$level, + _ref$exitOnError = _ref.exitOnError, + exitOnError = _ref$exitOnError === void 0 ? true : _ref$exitOnError, + transports = _ref.transports, + colors = _ref.colors, + emitErrs = _ref.emitErrs, + formatters = _ref.formatters, + padLevels = _ref.padLevels, + rewriters = _ref.rewriters, + stripColors = _ref.stripColors, + exceptionHandlers = _ref.exceptionHandlers, + rejectionHandlers = _ref.rejectionHandlers; + + // Reset transports if we already have them + if (this.transports.length) { + this.clear(); + } + + this.silent = silent; + this.format = format || this.format || require('logform/json')(); + this.defaultMeta = defaultMeta || null; // Hoist other options onto this instance. + + this.levels = levels || this.levels || config.npm.levels; + this.level = level; + this.exceptions = new ExceptionHandler(this); + this.rejections = new RejectionHandler(this); + this.profilers = {}; + this.exitOnError = exitOnError; // Add all transports we have been provided. + + if (transports) { + transports = Array.isArray(transports) ? transports : [transports]; + transports.forEach(function (transport) { + return _this2.add(transport); + }); + } + + if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) { + throw new Error(['{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', 'Use a custom winston.format(function) instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n')); + } + + if (exceptionHandlers) { + this.exceptions.handle(exceptionHandlers); + } + + if (rejectionHandlers) { + this.rejections.handle(rejectionHandlers); + } + } + }, { + key: "isLevelEnabled", + value: function isLevelEnabled(level) { + var _this3 = this; + + var givenLevelValue = getLevelValue(this.levels, level); + + if (givenLevelValue === null) { + return false; + } + + var configuredLevelValue = getLevelValue(this.levels, this.level); + + if (configuredLevelValue === null) { + return false; + } + + if (!this.transports || this.transports.length === 0) { + return configuredLevelValue >= givenLevelValue; + } + + var index = this.transports.findIndex(function (transport) { + var transportLevelValue = getLevelValue(_this3.levels, transport.level); + + if (transportLevelValue === null) { + transportLevelValue = configuredLevelValue; + } + + return transportLevelValue >= givenLevelValue; + }); + return index !== -1; + } + /* eslint-disable valid-jsdoc */ + + /** + * Ensure backwards compatibility with a `log` method + * @param {mixed} level - Level the log message is written at. + * @param {mixed} msg - TODO: add param description. + * @param {mixed} meta - TODO: add param description. + * @returns {Logger} - TODO: add return description. + * + * @example + * // Supports the existing API: + * logger.log('info', 'Hello world', { custom: true }); + * logger.log('info', new Error('Yo, it\'s on fire')); + * + * // Requires winston.format.splat() + * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); + * + * // And the new API with a single JSON literal: + * logger.log({ level: 'info', message: 'Hello world', custom: true }); + * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); + * + * // Also requires winston.format.splat() + * logger.log({ + * level: 'info', + * message: '%s %d%%', + * [SPLAT]: ['A string', 50], + * meta: { thisIsMeta: true } + * }); + * + */ + + /* eslint-enable valid-jsdoc */ + + }, { + key: "log", + value: function log(level, msg) { + var _Object$assign2; + + for (var _len = arguments.length, splat = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + splat[_key - 2] = arguments[_key]; + } + + // eslint-disable-line max-params + // Optimize for the hotpath of logging JSON literals + if (arguments.length === 1) { + // Yo dawg, I heard you like levels ... seriously ... + // In this context the LHS `level` here is actually the `info` so read + // this as: info[LEVEL] = info.level; + level[LEVEL] = level.level; + + this._addDefaultMeta(level); + + this.write(level); + return this; + } // Slightly less hotpath, but worth optimizing for. + + + if (arguments.length === 2) { + var _this$write; + + if (msg && _typeof(msg) === 'object') { + msg[LEVEL] = msg.level = level; + + this._addDefaultMeta(msg); + + this.write(msg); + return this; + } + + this.write((_this$write = {}, _defineProperty(_this$write, LEVEL, level), _defineProperty(_this$write, "level", level), _defineProperty(_this$write, "message", msg), _this$write)); + return this; + } + + var meta = splat[0]; + + if (_typeof(meta) === 'object' && meta !== null) { + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + var tokens = msg && msg.match && msg.match(formatRegExp); + + if (!tokens) { + var _Object$assign; + + var info = Object.assign({}, this.defaultMeta, meta, (_Object$assign = {}, _defineProperty(_Object$assign, LEVEL, level), _defineProperty(_Object$assign, SPLAT, splat), _defineProperty(_Object$assign, "level", level), _defineProperty(_Object$assign, "message", msg), _Object$assign)); + if (meta.message) info.message = "".concat(info.message, " ").concat(meta.message); + if (meta.stack) info.stack = meta.stack; + this.write(info); + return this; + } + } + + this.write(Object.assign({}, this.defaultMeta, (_Object$assign2 = {}, _defineProperty(_Object$assign2, LEVEL, level), _defineProperty(_Object$assign2, SPLAT, splat), _defineProperty(_Object$assign2, "level", level), _defineProperty(_Object$assign2, "message", msg), _Object$assign2))); + return this; + } + /** + * Pushes data so that it can be picked up by all of our pipe targets. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - Continues stream processing. + * @returns {undefined} + * @private + */ + + }, { + key: "_transform", + value: function _transform(info, enc, callback) { + if (this.silent) { + return callback(); + } // [LEVEL] is only soft guaranteed to be set here since we are a proper + // stream. It is likely that `info` came in through `.log(info)` or + // `.info(info)`. If it is not defined, however, define it. + // This LEVEL symbol is provided by `triple-beam` and also used in: + // - logform + // - winston-transport + // - abstract-winston-transport + + + if (!info[LEVEL]) { + info[LEVEL] = info.level; + } // Remark: really not sure what to do here, but this has been reported as + // very confusing by pre winston@2.0.0 users as quite confusing when using + // custom levels. + + + if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { + // eslint-disable-next-line no-console + console.error('[winston] Unknown logger level: %s', info[LEVEL]); + } // Remark: not sure if we should simply error here. + + + if (!this._readableState.pipes) { + // eslint-disable-next-line no-console + console.error('[winston] Attempt to write logs with no transports %j', info); + } // Here we write to the `format` pipe-chain, which on `readable` above will + // push the formatted `info` Object onto the buffer for this instance. We trap + // (and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + + + try { + this.push(this.format.transform(info, this.format.options)); + } catch (ex) { + throw ex; + } finally { + // eslint-disable-next-line callback-return + callback(); + } + } + /** + * Delays the 'finish' event until all transport pipe targets have + * also emitted 'finish' or are already finished. + * @param {mixed} callback - Continues stream processing. + */ + + }, { + key: "_final", + value: function _final(callback) { + var transports = this.transports.slice(); + asyncForEach(transports, function (transport, next) { + if (!transport || transport.finished) return setImmediate(next); + transport.once('finish', next); + transport.end(); + }, callback); + } + /** + * Adds the transport to this logger instance by piping to it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + + }, { + key: "add", + value: function add(transport) { + // Support backwards compatibility with all existing `winston < 3.x.x` + // transports which meet one of two criteria: + // 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream. + // 2. They expose a log method which has a length greater than 2 (i.e. more then + // just `log(info, callback)`. + var target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({ + transport: transport + }) : transport; + + if (!target._writableState || !target._writableState.objectMode) { + throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.'); + } // Listen for the `error` event and the `warn` event on the new Transport. + + + this._onEvent('error', target); + + this._onEvent('warn', target); + + this.pipe(target); + + if (transport.handleExceptions) { + this.exceptions.handle(); + } + + if (transport.handleRejections) { + this.rejections.handle(); + } + + return this; + } + /** + * Removes the transport from this logger instance by unpiping from it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + + }, { + key: "remove", + value: function remove(transport) { + if (!transport) return this; + var target = transport; + + if (!isStream(transport) || transport.log.length > 2) { + target = this.transports.filter(function (match) { + return match.transport === transport; + })[0]; + } + + if (target) { + this.unpipe(target); + } + + return this; + } + /** + * Removes all transports from this logger instance. + * @returns {Logger} - TODO: add return description. + */ + + }, { + key: "clear", + value: function clear() { + this.unpipe(); + return this; + } + /** + * Cleans up resources (streams, event listeners) for all transports + * associated with this instance (if necessary). + * @returns {Logger} - TODO: add return description. + */ + + }, { + key: "close", + value: function close() { + this.clear(); + this.emit('close'); + return this; + } + /** + * Sets the `target` levels specified on this instance. + * @param {Object} Target levels to use on this instance. + */ + + }, { + key: "setLevels", + value: function setLevels() { + warn.deprecated('setLevels'); + } + /** + * Queries the all transports for this instance with the specified `options`. + * This will aggregate each transport's results into one object containing + * a property per transport. + * @param {Object} options - Query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + */ + + }, { + key: "query", + value: function query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + var results = {}; + var queryObject = Object.assign({}, options.query || {}); // Helper function to query a single transport + + function queryTransport(transport, next) { + if (options.query && typeof transport.formatQuery === 'function') { + options.query = transport.formatQuery(queryObject); + } + + transport.query(options, function (err, res) { + if (err) { + return next(err); + } + + if (typeof transport.formatResults === 'function') { + res = transport.formatResults(res, options.format); + } + + next(null, res); + }); + } // Helper function to accumulate the results from `queryTransport` into + // the `results`. + + + function addResults(transport, next) { + queryTransport(transport, function (err, result) { + // queryTransport could potentially invoke the callback multiple times + // since Transport code can be unpredictable. + if (next) { + result = err || result; + + if (result) { + results[transport.name] = result; + } // eslint-disable-next-line callback-return + + + next(); + } + + next = null; + }); + } // Iterate over the transports in parallel setting the appropriate key in + // the `results`. + + + asyncForEach(this.transports.filter(function (transport) { + return !!transport.query; + }), addResults, function () { + return callback(null, results); + }); + } + /** + * Returns a log stream for all transports. Options object is optional. + * @param{Object} options={} - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + */ + + }, { + key: "stream", + value: function stream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var out = new Stream(); + var streams = []; + out._streams = streams; + + out.destroy = function () { + var i = streams.length; + + while (i--) { + streams[i].destroy(); + } + }; // Create a list of all transports for this instance. + + + this.transports.filter(function (transport) { + return !!transport.stream; + }).forEach(function (transport) { + var str = transport.stream(options); + + if (!str) { + return; + } + + streams.push(str); + str.on('log', function (log) { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit('log', log); + }); + str.on('error', function (err) { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit('error', err); + }); + }); + return out; + } + /** + * Returns an object corresponding to a specific timing. When done is called + * the timer will finish and log the duration. e.g.: + * @returns {Profile} - TODO: add return description. + * @example + * const timer = winston.startTimer() + * setTimeout(() => { + * timer.done({ + * message: 'Logging message' + * }); + * }, 1000); + */ + + }, { + key: "startTimer", + value: function startTimer() { + return new Profiler(this); + } + /** + * Tracks the time inbetween subsequent calls to this method with the same + * `id` parameter. The second call to this method will log the difference in + * milliseconds along with the message. + * @param {string} id Unique id of the profiler + * @returns {Logger} - TODO: add return description. + */ + + }, { + key: "profile", + value: function profile(id) { + var time = Date.now(); + + if (this.profilers[id]) { + var timeEnd = this.profilers[id]; + delete this.profilers[id]; // Attempt to be kind to users if they are still using older APIs. + + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + if (typeof args[args.length - 2] === 'function') { + // eslint-disable-next-line no-console + console.warn('Callback function no longer supported as of winston@3.0.0'); + args.pop(); + } // Set the duration property of the metadata + + + var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = time - timeEnd; + info.message = info.message || id; + return this.write(info); + } + + this.profilers[id] = time; + return this; + } + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + + }, { + key: "handleExceptions", + value: function handleExceptions() { + var _this$exceptions; + + // eslint-disable-next-line no-console + console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()'); + + (_this$exceptions = this.exceptions).handle.apply(_this$exceptions, arguments); + } + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + + }, { + key: "unhandleExceptions", + value: function unhandleExceptions() { + var _this$exceptions2; + + // eslint-disable-next-line no-console + console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()'); + + (_this$exceptions2 = this.exceptions).unhandle.apply(_this$exceptions2, arguments); + } + /** + * Throw a more meaningful deprecation notice + * @throws {Error} - TODO: add throws description. + */ + + }, { + key: "cli", + value: function cli() { + throw new Error(['Logger.cli() was removed in winston@3.0.0', 'Use a custom winston.formats.cli() instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n')); + } + /** + * Bubbles the `event` that occured on the specified `transport` up + * from this instance. + * @param {string} event - The event that occured + * @param {Object} transport - Transport on which the event occured + * @private + */ + + }, { + key: "_onEvent", + value: function _onEvent(event, transport) { + function transportEvent(err) { + // https://github.com/winstonjs/winston/issues/1364 + if (event === 'error' && !this.transports.includes(transport)) { + this.add(transport); + } + + this.emit(event, err, transport); + } + + if (!transport['__winston' + event]) { + transport['__winston' + event] = transportEvent.bind(this); + transport.on(event, transport['__winston' + event]); + } + } + }, { + key: "_addDefaultMeta", + value: function _addDefaultMeta(msg) { + if (this.defaultMeta) { + Object.assign(msg, this.defaultMeta); + } + } + }]); + + return Logger; +}(Transform); + +function getLevelValue(levels, level) { + var value = levels[level]; + + if (!value && value !== 0) { + return null; + } + + return value; +} +/** + * Represents the current readableState pipe targets for this Logger instance. + * @type {Array|Object} + */ + + +Object.defineProperty(Logger.prototype, 'transports', { + configurable: false, + enumerable: true, + get: function get() { + var pipes = this._readableState.pipes; + return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + } +}); +module.exports = Logger; \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/profiler.js b/build/node_modules/winston/dist/winston/profiler.js new file mode 100644 index 00000000..236f6e48 --- /dev/null +++ b/build/node_modules/winston/dist/winston/profiler.js @@ -0,0 +1,69 @@ +/** + * profiler.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; +/** + * TODO: add class description. + * @type {Profiler} + * @private + */ + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +module.exports = /*#__PURE__*/function () { + /** + * Constructor function for the Profiler instance used by + * `Logger.prototype.startTimer`. When done is called the timer will finish + * and log the duration. + * @param {!Logger} logger - TODO: add param description. + * @private + */ + function Profiler(logger) { + _classCallCheck(this, Profiler); + + if (!logger) { + throw new Error('Logger is required for profiling.'); + } + + this.logger = logger; + this.start = Date.now(); + } + /** + * Ends the current timer (i.e. Profiler) instance and logs the `msg` along + * with the duration since creation. + * @returns {mixed} - TODO: add return description. + * @private + */ + + + _createClass(Profiler, [{ + key: "done", + value: function done() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + if (typeof args[args.length - 1] === 'function') { + // eslint-disable-next-line no-console + console.warn('Callback function no longer supported as of winston@3.0.0'); + args.pop(); + } + + var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = Date.now() - this.start; + return this.logger.write(info); + } + }]); + + return Profiler; +}(); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/rejection-handler.js b/build/node_modules/winston/dist/winston/rejection-handler.js new file mode 100644 index 00000000..36cd3d84 --- /dev/null +++ b/build/node_modules/winston/dist/winston/rejection-handler.js @@ -0,0 +1,288 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var os = require('os'); + +var asyncForEach = require('async/forEach'); + +var debug = require('@dabh/diagnostics')('winston:rejection'); + +var once = require('one-time'); + +var stackTrace = require('stack-trace'); + +var ExceptionStream = require('./exception-stream'); +/** + * Object for handling unhandledRejection events. + * @type {RejectionHandler} + */ + + +module.exports = /*#__PURE__*/function () { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + function RejectionHandler(logger) { + _classCallCheck(this, RejectionHandler); + + if (!logger) { + throw new Error('Logger is required to handle rejections'); + } + + this.logger = logger; + this.handlers = new Map(); + } + /** + * Handles `unhandledRejection` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + + + _createClass(RejectionHandler, [{ + key: "handle", + value: function handle() { + var _this = this; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + args.forEach(function (arg) { + if (Array.isArray(arg)) { + return arg.forEach(function (handler) { + return _this._addHandler(handler); + }); + } + + _this._addHandler(arg); + }); + + if (!this.catcher) { + this.catcher = this._unhandledRejection.bind(this); + process.on('unhandledRejection', this.catcher); + } + } + /** + * Removes any handlers to `unhandledRejection` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + + }, { + key: "unhandle", + value: function unhandle() { + var _this2 = this; + + if (this.catcher) { + process.removeListener('unhandledRejection', this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach(function (wrapper) { + return _this2.logger.unpipe(wrapper); + }); + } + } + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getAllInfo", + value: function getAllInfo(err) { + var message = err.message; + + if (!message && typeof err === 'string') { + message = err; + } + + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: ["unhandledRejection: ".concat(message || '(no error message)'), err.stack || ' No stack trace'].join('\n'), + stack: err.stack, + exception: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getProcessInfo", + value: function getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getOsInfo", + value: function getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "getTrace", + value: function getTrace(err) { + var trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(function (site) { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + "function": site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + "native": site.isNative() + }; + }); + } + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + + }, { + key: "_addHandler", + value: function _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleRejections = true; + var wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + + }, { + key: "_unhandledRejection", + value: function _unhandledRejection(err) { + var info = this.getAllInfo(err); + + var handlers = this._getRejectionHandlers(); // Calculate if we should exit on this error + + + var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError; + var timeout; + + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no rejection handlers.'); // eslint-disable-next-line no-console + + console.warn('winston: not exiting process.'); + doExit = false; + } + + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + + if (doExit && !process._exiting) { + // Remark: Currently ignoring any rejections from transports when + // catching unhandled rejections. + if (timeout) { + clearTimeout(timeout); + } // eslint-disable-next-line no-process-exit + + + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } // Log to all transports attempting to listen for when they are completed. + + + asyncForEach(handlers, function (handler, next) { + var done = once(next); + var transport = handler.transport || handler; // Debug wrapping so that we can inspect what's going on under the covers. + + function onDone(event) { + return function () { + debug(event); + done(); + }; + } + + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, function () { + return doExit && gracefulExit(); + }); + this.logger.log(info); // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + + }, { + key: "_getRejectionHandlers", + value: function _getRejectionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleRejections: true` + return this.logger.transports.filter(function (wrap) { + var transport = wrap.transport || wrap; + return transport.handleRejections; + }); + } + }]); + + return RejectionHandler; +}(); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/tail-file.js b/build/node_modules/winston/dist/winston/tail-file.js new file mode 100644 index 00000000..5a6b9fc8 --- /dev/null +++ b/build/node_modules/winston/dist/winston/tail-file.js @@ -0,0 +1,135 @@ +/** + * tail-file.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +var fs = require('fs'); + +var _require = require('string_decoder'), + StringDecoder = _require.StringDecoder; + +var _require2 = require('readable-stream'), + Stream = _require2.Stream; +/** + * Simple no-op function. + * @returns {undefined} + */ + + +function noop() {} +/** + * TODO: add function description. + * @param {Object} options - Options for tail. + * @param {function} iter - Iterator function to execute on every line. +* `tail -f` a file. Options must include file. + * @returns {mixed} - TODO: add return description. + */ + + +module.exports = function (options, iter) { + var buffer = Buffer.alloc(64 * 1024); + var decode = new StringDecoder('utf8'); + var stream = new Stream(); + var buff = ''; + var pos = 0; + var row = 0; + + if (options.start === -1) { + delete options.start; + } + + stream.readable = true; + + stream.destroy = function () { + stream.destroyed = true; + stream.emit('end'); + stream.emit('close'); + }; + + fs.open(options.file, 'a+', '0644', function (err, fd) { + if (err) { + if (!iter) { + stream.emit('error', err); + } else { + iter(err); + } + + stream.destroy(); + return; + } + + (function read() { + if (stream.destroyed) { + fs.close(fd, noop); + return; + } + + return fs.read(fd, buffer, 0, buffer.length, pos, function (error, bytes) { + if (error) { + if (!iter) { + stream.emit('error', error); + } else { + iter(error); + } + + stream.destroy(); + return; + } + + if (!bytes) { + if (buff) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', buff); + } else { + iter(null, buff); + } + } + + row++; + buff = ''; + } + + return setTimeout(read, 1000); + } + + var data = decode.write(buffer.slice(0, bytes)); + + if (!iter) { + stream.emit('data', data); + } + + data = (buff + data).split(/\n+/); + var l = data.length - 1; + var i = 0; + + for (; i < l; i++) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', data[i]); + } else { + iter(null, data[i]); + } + } + + row++; + } + + buff = data[l]; + pos += bytes; + return read(); + }); + })(); + }); + + if (!iter) { + return stream; + } + + return stream.destroy; +}; \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/transports/console.js b/build/node_modules/winston/dist/winston/transports/console.js new file mode 100644 index 00000000..c58394a0 --- /dev/null +++ b/build/node_modules/winston/dist/winston/transports/console.js @@ -0,0 +1,166 @@ +/* eslint-disable no-console */ + +/* + * console.js: Transport for outputting to the console. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var os = require('os'); + +var _require = require('triple-beam'), + LEVEL = _require.LEVEL, + MESSAGE = _require.MESSAGE; + +var TransportStream = require('winston-transport'); +/** + * Transport for outputting to the console. + * @type {Console} + * @extends {TransportStream} + */ + + +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(Console, _TransportStream); + + var _super = _createSuper(Console); + + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + function Console() { + var _this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, Console); + + _this = _super.call(this, options); // Expose the name of this Transport on the prototype + + _this.name = options.name || 'console'; + _this.stderrLevels = _this._stringArrayToSet(options.stderrLevels); + _this.consoleWarnLevels = _this._stringArrayToSet(options.consoleWarnLevels); + _this.eol = options.eol || os.EOL; + + _this.setMaxListeners(30); + + return _this; + } + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + + + _createClass(Console, [{ + key: "log", + value: function log(info, callback) { + var _this2 = this; + + setImmediate(function () { + return _this2.emit('logged', info); + }); // Remark: what if there is no raw...? + + if (this.stderrLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + console._stderr.write("".concat(info[MESSAGE]).concat(this.eol)); + } else { + // console.error adds a newline + console.error(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + + return; + } else if (this.consoleWarnLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + // in Node.js console.warn is an alias for console.error + console._stderr.write("".concat(info[MESSAGE]).concat(this.eol)); + } else { + // console.warn adds a newline + console.warn(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + + return; + } + + if (console._stdout) { + // Node.js maps `process.stdout` to `console._stdout`. + console._stdout.write("".concat(info[MESSAGE]).concat(this.eol)); + } else { + // console.log adds a newline. + console.log(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + } + /** + * Returns a Set-like object with strArray's elements as keys (each with the + * value true). + * @param {Array} strArray - Array of Set-elements as strings. + * @param {?string} [errMsg] - Custom error message thrown on invalid input. + * @returns {Object} - TODO: add return description. + * @private + */ + + }, { + key: "_stringArrayToSet", + value: function _stringArrayToSet(strArray, errMsg) { + if (!strArray) return {}; + errMsg = errMsg || 'Cannot make set from type other than Array of string elements'; + + if (!Array.isArray(strArray)) { + throw new Error(errMsg); + } + + return strArray.reduce(function (set, el) { + if (typeof el !== 'string') { + throw new Error(errMsg); + } + + set[el] = true; + return set; + }, {}); + } + }]); + + return Console; +}(TransportStream); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/transports/file.js b/build/node_modules/winston/dist/winston/transports/file.js new file mode 100644 index 00000000..ddeacd08 --- /dev/null +++ b/build/node_modules/winston/dist/winston/transports/file.js @@ -0,0 +1,817 @@ +/* eslint-disable complexity,max-statements */ + +/** + * file.js: Transport for outputting to a local log file. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var fs = require('fs'); + +var path = require('path'); + +var asyncSeries = require('async/series'); + +var zlib = require('zlib'); + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +var _require2 = require('readable-stream'), + Stream = _require2.Stream, + PassThrough = _require2.PassThrough; + +var TransportStream = require('winston-transport'); + +var debug = require('@dabh/diagnostics')('winston:file'); + +var os = require('os'); + +var tailFile = require('../tail-file'); +/** + * Transport for outputting to a local log file. + * @type {File} + * @extends {TransportStream} + */ + + +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(File, _TransportStream); + + var _super = _createSuper(File); + + /** + * Constructor function for the File transport object responsible for + * persisting log messages and metadata to one or more files. + * @param {Object} options - Options for this instance. + */ + function File() { + var _this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, File); + + _this = _super.call(this, options); // Expose the name of this Transport on the prototype. + + _this.name = options.name || 'file'; // Helper function which throws an `Error` in the event that any of the + // rest of the arguments is present in `options`. + + function throwIf(target) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + args.slice(1).forEach(function (name) { + if (options[name]) { + throw new Error("Cannot set ".concat(name, " and ").concat(target, " together")); + } + }); + } // Setup the base stream that always gets piped to to handle buffering. + + + _this._stream = new PassThrough(); + + _this._stream.setMaxListeners(30); // Bind this context for listener methods. + + + _this._onError = _this._onError.bind(_assertThisInitialized(_this)); + + if (options.filename || options.dirname) { + throwIf('filename or dirname', 'stream'); + _this._basename = _this.filename = options.filename ? path.basename(options.filename) : 'winston.log'; + _this.dirname = options.dirname || path.dirname(options.filename); + _this.options = options.options || { + flags: 'a' + }; + } else if (options.stream) { + // eslint-disable-next-line no-console + console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream'); + throwIf('stream', 'filename', 'maxsize'); + _this._dest = _this._stream.pipe(_this._setupStream(options.stream)); + _this.dirname = path.dirname(_this._dest.path); // We need to listen for drain events when write() returns false. This + // can make node mad at times. + } else { + throw new Error('Cannot log to file without filename or stream.'); + } + + _this.maxsize = options.maxsize || null; + _this.rotationFormat = options.rotationFormat || false; + _this.zippedArchive = options.zippedArchive || false; + _this.maxFiles = options.maxFiles || null; + _this.eol = options.eol || os.EOL; + _this.tailable = options.tailable || false; // Internal state variables representing the number of files this instance + // has created and the current size (in bytes) of the current logfile. + + _this._size = 0; + _this._pendingSize = 0; + _this._created = 0; + _this._drain = false; + _this._opening = false; + _this._ending = false; + if (_this.dirname) _this._createLogDirIfNotExist(_this.dirname); + + _this.open(); + + return _this; + } + + _createClass(File, [{ + key: "finishIfEnding", + value: function finishIfEnding() { + var _this2 = this; + + if (this._ending) { + if (this._opening) { + this.once('open', function () { + _this2._stream.once('finish', function () { + return _this2.emit('finish'); + }); + + setImmediate(function () { + return _this2._stream.end(); + }); + }); + } else { + this._stream.once('finish', function () { + return _this2.emit('finish'); + }); + + setImmediate(function () { + return _this2._stream.end(); + }); + } + } + } + /** + * Core logging method exposed to Winston. Metadata is optional. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "log", + value: function log(info) { + var _this3 = this; + + var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; + + // Remark: (jcrugzz) What is necessary about this callback(null, true) now + // when thinking about 3.x? Should silent be handled in the base + // TransportStream _write method? + if (this.silent) { + callback(); + return true; + } // Output stream buffer is full and has asked us to wait for the drain event + + + if (this._drain) { + this._stream.once('drain', function () { + _this3._drain = false; + + _this3.log(info, callback); + }); + + return; + } + + if (this._rotate) { + this._stream.once('rotate', function () { + _this3._rotate = false; + + _this3.log(info, callback); + }); + + return; + } // Grab the raw string and append the expected EOL. + + + var output = "".concat(info[MESSAGE]).concat(this.eol); + var bytes = Buffer.byteLength(output); // After we have written to the PassThrough check to see if we need + // to rotate to the next file. + // + // Remark: This gets called too early and does not depict when data + // has been actually flushed to disk. + + function logged() { + var _this4 = this; + + this._size += bytes; + this._pendingSize -= bytes; + debug('logged %s %s', this._size, output); + this.emit('logged', info); // Do not attempt to rotate files while opening + + if (this._opening) { + return; + } // Check to see if we need to end the stream and create a new one. + + + if (!this._needsNewFile()) { + return; + } // End the current stream, ensure it flushes and create a new one. + // This could potentially be optimized to not run a stat call but its + // the safest way since we are supporting `maxFiles`. + + + this._rotate = true; + + this._endStream(function () { + return _this4._rotateFile(); + }); + } // Keep track of the pending bytes being written while files are opening + // in order to properly rotate the PassThrough this._stream when the file + // eventually does open. + + + this._pendingSize += bytes; + + if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) { + this.rotatedWhileOpening = true; + } + + var written = this._stream.write(output, logged.bind(this)); + + if (!written) { + this._drain = true; + + this._stream.once('drain', function () { + _this3._drain = false; + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + + debug('written', written, this._drain); + this.finishIfEnding(); + return written; + } + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * TODO: Refactor me. + */ + + }, { + key: "query", + value: function query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = normalizeQuery(options); + var file = path.join(this.dirname, this.filename); + var buff = ''; + var results = []; + var row = 0; + var stream = fs.createReadStream(file, { + encoding: 'utf8' + }); + stream.on('error', function (err) { + if (stream.readable) { + stream.destroy(); + } + + if (!callback) { + return; + } + + return err.code !== 'ENOENT' ? callback(err) : callback(null, results); + }); + stream.on('data', function (data) { + data = (buff + data).split(/\n+/); + var l = data.length - 1; + var i = 0; + + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + + row++; + } + + buff = data[l]; + }); + stream.on('close', function () { + if (buff) { + add(buff, true); + } + + if (options.order === 'desc') { + results = results.reverse(); + } // eslint-disable-next-line callback-return + + + if (callback) callback(null, results); + }); + + function add(buff, attempt) { + try { + var log = JSON.parse(buff); + + if (check(log)) { + push(log); + } + } catch (e) { + if (!attempt) { + stream.emit('error', e); + } + } + } + + function push(log) { + if (options.rows && results.length >= options.rows && options.order !== 'desc') { + if (stream.readable) { + stream.destroy(); + } + + return; + } + + if (options.fields) { + log = options.fields.reduce(function (obj, key) { + obj[key] = log[key]; + return obj; + }, {}); + } + + if (options.order === 'desc') { + if (results.length >= options.rows) { + results.shift(); + } + } + + results.push(log); + } + + function check(log) { + if (!log) { + return; + } + + if (_typeof(log) !== 'object') { + return; + } + + var time = new Date(log.timestamp); + + if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { + return; + } + + return true; + } + + function normalizeQuery(options) { + options = options || {}; // limit + + options.rows = options.rows || options.limit || 10; // starting row offset + + options.start = options.start || 0; // now + + options.until = options.until || new Date(); + + if (_typeof(options.until) !== 'object') { + options.until = new Date(options.until); + } // now - 24 + + + options.from = options.from || options.until - 24 * 60 * 60 * 1000; + + if (_typeof(options.from) !== 'object') { + options.from = new Date(options.from); + } // 'asc' or 'desc' + + + options.order = options.order || 'desc'; + return options; + } + } + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + * TODO: Refactor me. + */ + + }, { + key: "stream", + value: function stream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var file = path.join(this.dirname, this.filename); + var stream = new Stream(); + var tail = { + file: file, + start: options.start + }; + stream.destroy = tailFile(tail, function (err, line) { + if (err) { + return stream.emit('error', err); + } + + try { + stream.emit('data', line); + line = JSON.parse(line); + stream.emit('log', line); + } catch (e) { + stream.emit('error', e); + } + }); + return stream; + } + /** + * Checks to see the filesize of. + * @returns {undefined} + */ + + }, { + key: "open", + value: function open() { + var _this5 = this; + + // If we do not have a filename then we were passed a stream and + // don't need to keep track of size. + if (!this.filename) return; + if (this._opening) return; + this._opening = true; // Stat the target file to get the size and create the stream. + + this.stat(function (err, size) { + if (err) { + return _this5.emit('error', err); + } + + debug('stat done: %s { size: %s }', _this5.filename, size); + _this5._size = size; + _this5._dest = _this5._createStream(_this5._stream); + _this5._opening = false; + + _this5.once('open', function () { + if (_this5._stream.eventNames().includes('rotate')) { + _this5._stream.emit('rotate'); + } else { + _this5._rotate = false; + } + }); + }); + } + /** + * Stat the file and assess information in order to create the proper stream. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "stat", + value: function stat(callback) { + var _this6 = this; + + var target = this._getFile(); + + var fullpath = path.join(this.dirname, target); + fs.stat(fullpath, function (err, stat) { + if (err && err.code === 'ENOENT') { + debug('ENOENT ok', fullpath); // Update internally tracked filename with the new target name. + + _this6.filename = target; + return callback(null, 0); + } + + if (err) { + debug("err ".concat(err.code, " ").concat(fullpath)); + return callback(err); + } + + if (!stat || _this6._needsNewFile(stat.size)) { + // If `stats.size` is greater than the `maxsize` for this + // instance then try again. + return _this6._incFile(function () { + return _this6.stat(callback); + }); + } // Once we have figured out what the filename is, set it + // and return the size. + + + _this6.filename = target; + callback(null, stat.size); + }); + } + /** + * Closes the stream associated with this instance. + * @param {function} cb - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "close", + value: function close(cb) { + var _this7 = this; + + if (!this._stream) { + return; + } + + this._stream.end(function () { + if (cb) { + cb(); // eslint-disable-line callback-return + } + + _this7.emit('flush'); + + _this7.emit('closed'); + }); + } + /** + * TODO: add method description. + * @param {number} size - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "_needsNewFile", + value: function _needsNewFile(size) { + size = size || this._size; + return this.maxsize && size >= this.maxsize; + } + /** + * TODO: add method description. + * @param {Error} err - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "_onError", + value: function _onError(err) { + this.emit('error', err); + } + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "_setupStream", + value: function _setupStream(stream) { + stream.on('error', this._onError); + return stream; + } + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + + }, { + key: "_cleanupStream", + value: function _cleanupStream(stream) { + stream.removeListener('error', this._onError); + return stream; + } + /** + * TODO: add method description. + */ + + }, { + key: "_rotateFile", + value: function _rotateFile() { + var _this8 = this; + + this._incFile(function () { + return _this8.open(); + }); + } + /** + * Unpipe from the stream that has been marked as full and end it so it + * flushes to disk. + * + * @param {function} callback - Callback for when the current file has closed. + * @private + */ + + }, { + key: "_endStream", + value: function _endStream() { + var _this9 = this; + + var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {}; + + if (this._dest) { + this._stream.unpipe(this._dest); + + this._dest.end(function () { + _this9._cleanupStream(_this9._dest); + + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + } + /** + * Returns the WritableStream for the active file on this instance. If we + * should gzip the file then a zlib stream is returned. + * + * @param {ReadableStream} source – PassThrough to pipe to the file when open. + * @returns {WritableStream} Stream that writes to disk for the active file. + */ + + }, { + key: "_createStream", + value: function _createStream(source) { + var _this10 = this; + + var fullpath = path.join(this.dirname, this.filename); + debug('create stream start', fullpath, this.options); + var dest = fs.createWriteStream(fullpath, this.options) // TODO: What should we do with errors here? + .on('error', function (err) { + return debug(err); + }).on('close', function () { + return debug('close', dest.path, dest.bytesWritten); + }).on('open', function () { + debug('file open ok', fullpath); + + _this10.emit('open', fullpath); + + source.pipe(dest); // If rotation occured during the open operation then we immediately + // start writing to a new PassThrough, begin opening the next file + // and cleanup the previous source and dest once the source has drained. + + if (_this10.rotatedWhileOpening) { + _this10._stream = new PassThrough(); + + _this10._stream.setMaxListeners(30); + + _this10._rotateFile(); + + _this10.rotatedWhileOpening = false; + + _this10._cleanupStream(dest); + + source.end(); + } + }); + debug('create stream ok', fullpath); + + if (this.zippedArchive) { + var gzip = zlib.createGzip(); + gzip.pipe(dest); + return gzip; + } + + return dest; + } + /** + * TODO: add method description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + + }, { + key: "_incFile", + value: function _incFile(callback) { + debug('_incFile', this.filename); + var ext = path.extname(this._basename); + var basename = path.basename(this._basename, ext); + + if (!this.tailable) { + this._created += 1; + + this._checkMaxFilesIncrementing(ext, basename, callback); + } else { + this._checkMaxFilesTailable(ext, basename, callback); + } + } + /** + * Gets the next filename to use for this instance in the case that log + * filesizes are being capped. + * @returns {string} - TODO: add return description. + * @private + */ + + }, { + key: "_getFile", + value: function _getFile() { + var ext = path.extname(this._basename); + var basename = path.basename(this._basename, ext); + var isRotation = this.rotationFormat ? this.rotationFormat() : this._created; // Caveat emptor (indexzero): rotationFormat() was broken by design When + // combined with max files because the set of files to unlink is never + // stored. + + var target = !this.tailable && this._created ? "".concat(basename).concat(isRotation).concat(ext) : "".concat(basename).concat(ext); + return this.zippedArchive && !this.tailable ? "".concat(target, ".gz") : target; + } + /** + * Increment the number of files created or checked by this instance. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + + }, { + key: "_checkMaxFilesIncrementing", + value: function _checkMaxFilesIncrementing(ext, basename, callback) { + // Check for maxFiles option and delete file. + if (!this.maxFiles || this._created < this.maxFiles) { + return setImmediate(callback); + } + + var oldest = this._created - this.maxFiles; + var isOldest = oldest !== 0 ? oldest : ''; + var isZipped = this.zippedArchive ? '.gz' : ''; + var filePath = "".concat(basename).concat(isOldest).concat(ext).concat(isZipped); + var target = path.join(this.dirname, filePath); + fs.unlink(target, callback); + } + /** + * Roll files forward based on integer, up to maxFiles. e.g. if base if + * file.log and it becomes oversized, roll to file1.log, and allow file.log + * to be re-used. If file is oversized again, roll file1.log to file2.log, + * roll file.log to file1.log, and so on. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + + }, { + key: "_checkMaxFilesTailable", + value: function _checkMaxFilesTailable(ext, basename, callback) { + var _this12 = this; + + var tasks = []; + + if (!this.maxFiles) { + return; + } // const isZipped = this.zippedArchive ? '.gz' : ''; + + + var isZipped = this.zippedArchive ? '.gz' : ''; + + for (var x = this.maxFiles - 1; x > 1; x--) { + tasks.push(function (i, cb) { + var _this11 = this; + + var fileName = "".concat(basename).concat(i - 1).concat(ext).concat(isZipped); + var tmppath = path.join(this.dirname, fileName); + fs.exists(tmppath, function (exists) { + if (!exists) { + return cb(null); + } + + fileName = "".concat(basename).concat(i).concat(ext).concat(isZipped); + fs.rename(tmppath, path.join(_this11.dirname, fileName), cb); + }); + }.bind(this, x)); + } + + asyncSeries(tasks, function () { + fs.rename(path.join(_this12.dirname, "".concat(basename).concat(ext)), path.join(_this12.dirname, "".concat(basename, "1").concat(ext).concat(isZipped)), callback); + }); + } + }, { + key: "_createLogDirIfNotExist", + value: function _createLogDirIfNotExist(dirPath) { + /* eslint-disable no-sync */ + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { + recursive: true + }); + } + /* eslint-enable no-sync */ + + } + }]); + + return File; +}(TransportStream); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/transports/http.js b/build/node_modules/winston/dist/winston/transports/http.js new file mode 100644 index 00000000..b9a4135c --- /dev/null +++ b/build/node_modules/winston/dist/winston/transports/http.js @@ -0,0 +1,264 @@ +/** + * http.js: Transport for outputting to a json-rpcserver. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var http = require('http'); + +var https = require('https'); + +var _require = require('readable-stream'), + Stream = _require.Stream; + +var TransportStream = require('winston-transport'); +/** + * Transport for outputting to a json-rpc server. + * @type {Stream} + * @extends {TransportStream} + */ + + +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(Http, _TransportStream); + + var _super = _createSuper(Http); + + /** + * Constructor function for the Http transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + function Http() { + var _this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, Http); + + _this = _super.call(this, options); + _this.options = options; + _this.name = options.name || 'http'; + _this.ssl = !!options.ssl; + _this.host = options.host || 'localhost'; + _this.port = options.port; + _this.auth = options.auth; + _this.path = options.path || ''; + _this.agent = options.agent; + _this.headers = options.headers || {}; + _this.headers['content-type'] = 'application/json'; + + if (!_this.port) { + _this.port = _this.ssl ? 443 : 80; + } + + return _this; + } + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + + + _createClass(Http, [{ + key: "log", + value: function log(info, callback) { + var _this2 = this; + + this._request(info, function (err, res) { + if (res && res.statusCode !== 200) { + err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode)); + } + + if (err) { + _this2.emit('warn', err); + } else { + _this2.emit('logged', info); + } + }); // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering + // and block more requests from happening? + + + if (callback) { + setImmediate(callback); + } + } + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * @returns {undefined} + */ + + }, { + key: "query", + value: function query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = { + method: 'query', + params: this.normalizeQuery(options) + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + this._request(options, function (err, res, body) { + if (res && res.statusCode !== 200) { + err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode)); + } + + if (err) { + return callback(err); + } + + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + + callback(null, body); + }); + } + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description + */ + + }, { + key: "stream", + value: function stream() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var stream = new Stream(); + options = { + method: 'stream', + params: options + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + var buff = ''; + + var req = this._request(options); + + stream.destroy = function () { + return req.destroy(); + }; + + req.on('data', function (data) { + data = (buff + data).split(/\n+/); + var l = data.length - 1; + var i = 0; + + for (; i < l; i++) { + try { + stream.emit('log', JSON.parse(data[i])); + } catch (e) { + stream.emit('error', e); + } + } + + buff = data[l]; + }); + req.on('error', function (err) { + return stream.emit('error', err); + }); + return stream; + } + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + */ + + }, { + key: "_request", + value: function _request(options, callback) { + options = options || {}; + var auth = options.auth || this.auth; + var path = options.path || this.path || ''; + delete options.auth; + delete options.path; // Prepare options for outgoing HTTP request + + var headers = Object.assign({}, this.headers); + + if (auth && auth.bearer) { + headers.Authorization = "Bearer ".concat(auth.bearer); + } + + var req = (this.ssl ? https : http).request(_objectSpread(_objectSpread({}, this.options), {}, { + method: 'POST', + host: this.host, + port: this.port, + path: "/".concat(path.replace(/^\//, '')), + headers: headers, + auth: auth && auth.username && auth.password ? "".concat(auth.username, ":").concat(auth.password) : '', + agent: this.agent + })); + req.on('error', callback); + req.on('response', function (res) { + return res.on('end', function () { + return callback(null, res); + }).resume(); + }); + req.end(Buffer.from(JSON.stringify(options), 'utf8')); + } + }]); + + return Http; +}(TransportStream); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/transports/index.js b/build/node_modules/winston/dist/winston/transports/index.js new file mode 100644 index 00000000..d8b8aa74 --- /dev/null +++ b/build/node_modules/winston/dist/winston/transports/index.js @@ -0,0 +1,55 @@ +/** + * transports.js: Set of all transports Winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; +/** + * TODO: add property description. + * @type {Console} + */ + +Object.defineProperty(exports, 'Console', { + configurable: true, + enumerable: true, + get: function get() { + return require('./console'); + } +}); +/** + * TODO: add property description. + * @type {File} + */ + +Object.defineProperty(exports, 'File', { + configurable: true, + enumerable: true, + get: function get() { + return require('./file'); + } +}); +/** + * TODO: add property description. + * @type {Http} + */ + +Object.defineProperty(exports, 'Http', { + configurable: true, + enumerable: true, + get: function get() { + return require('./http'); + } +}); +/** + * TODO: add property description. + * @type {Stream} + */ + +Object.defineProperty(exports, 'Stream', { + configurable: true, + enumerable: true, + get: function get() { + return require('./stream'); + } +}); \ No newline at end of file diff --git a/build/node_modules/winston/dist/winston/transports/stream.js b/build/node_modules/winston/dist/winston/transports/stream.js new file mode 100644 index 00000000..57fc0194 --- /dev/null +++ b/build/node_modules/winston/dist/winston/transports/stream.js @@ -0,0 +1,117 @@ +/** + * stream.js: Transport for outputting to any arbitrary stream. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ +'use strict'; + +function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var isStream = require('is-stream'); + +var _require = require('triple-beam'), + MESSAGE = _require.MESSAGE; + +var os = require('os'); + +var TransportStream = require('winston-transport'); +/** + * Transport for outputting to any arbitrary stream. + * @type {Stream} + * @extends {TransportStream} + */ + + +module.exports = /*#__PURE__*/function (_TransportStream) { + _inherits(Stream, _TransportStream); + + var _super = _createSuper(Stream); + + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + function Stream() { + var _this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + _classCallCheck(this, Stream); + + _this = _super.call(this, options); + + if (!options.stream || !isStream(options.stream)) { + throw new Error('options.stream is required.'); + } // We need to listen for drain events when write() returns false. This can + // make node mad at times. + + + _this._stream = options.stream; + + _this._stream.setMaxListeners(Infinity); + + _this.isObjectMode = options.stream._writableState.objectMode; + _this.eol = options.eol || os.EOL; + return _this; + } + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + + + _createClass(Stream, [{ + key: "log", + value: function log(info, callback) { + var _this2 = this; + + setImmediate(function () { + return _this2.emit('logged', info); + }); + + if (this.isObjectMode) { + this._stream.write(info); + + if (callback) { + callback(); // eslint-disable-line callback-return + } + + return; + } + + this._stream.write("".concat(info[MESSAGE]).concat(this.eol)); + + if (callback) { + callback(); // eslint-disable-line callback-return + } + + return; + } + }]); + + return Stream; +}(TransportStream); \ No newline at end of file diff --git a/build/node_modules/winston/index.d.ts b/build/node_modules/winston/index.d.ts new file mode 100644 index 00000000..027379c3 --- /dev/null +++ b/build/node_modules/winston/index.d.ts @@ -0,0 +1,193 @@ +// Type definitions for winston 3.0 +// Project: https://github.com/winstonjs/winston + +/// + +import * as NodeJSStream from "stream"; + +import * as logform from 'logform'; +import * as Transport from 'winston-transport'; + +import * as Config from './lib/winston/config/index'; +import * as Transports from './lib/winston/transports/index'; + +declare namespace winston { + // Hoisted namespaces from other modules + export import format = logform.format; + export import Logform = logform; + export import config = Config; + export import transports = Transports; + export import transport = Transport; + + interface ExceptionHandler { + logger: Logger; + handlers: Map; + catcher: Function | boolean; + + handle(...transports: Transport[]): void; + unhandle(...transports: Transport[]): void; + getAllInfo(err: string | Error): object; + getProcessInfo(): object; + getOsInfo(): object; + getTrace(err: Error): object; + + new(logger: Logger): ExceptionHandler; + } + + interface QueryOptions { + rows?: number; + limit?: number; + start?: number; + from?: Date; + until?: Date; + order?: "asc" | "desc"; + fields: any; + } + + interface Profiler { + logger: Logger; + start: Number; + done(info?: any): boolean; + } + + type LogCallback = (error?: any, level?: string, message?: string, meta?: any) => void; + + interface LogEntry { + level: string; + message: string; + [optionName: string]: any; + } + + interface LogMethod { + (level: string, message: string, callback: LogCallback): Logger; + (level: string, message: string, meta: any, callback: LogCallback): Logger; + (level: string, message: string, ...meta: any[]): Logger; + (entry: LogEntry): Logger; + (level: string, message: any): Logger; + } + + interface LeveledLogMethod { + (message: string, callback: LogCallback): Logger; + (message: string, meta: any, callback: LogCallback): Logger; + (message: string, ...meta: any[]): Logger; + (message: any): Logger; + (infoObject: object): Logger; + } + + interface LoggerOptions { + levels?: Config.AbstractConfigSetLevels; + silent?: boolean; + format?: logform.Format; + level?: string; + exitOnError?: Function | boolean; + defaultMeta?: any; + transports?: Transport[] | Transport; + handleExceptions?: boolean; + exceptionHandlers?: any; + } + + interface Logger extends NodeJSStream.Transform { + silent: boolean; + format: logform.Format; + levels: Config.AbstractConfigSetLevels; + level: string; + transports: Transport[]; + exceptions: ExceptionHandler; + profilers: object; + exitOnError: Function | boolean; + defaultMeta?: any; + + log: LogMethod; + add(transport: Transport): Logger; + remove(transport: Transport): Logger; + clear(): Logger; + close(): Logger; + + // for cli and npm levels + error: LeveledLogMethod; + warn: LeveledLogMethod; + help: LeveledLogMethod; + data: LeveledLogMethod; + info: LeveledLogMethod; + debug: LeveledLogMethod; + prompt: LeveledLogMethod; + http: LeveledLogMethod; + verbose: LeveledLogMethod; + input: LeveledLogMethod; + silly: LeveledLogMethod; + + // for syslog levels only + emerg: LeveledLogMethod; + alert: LeveledLogMethod; + crit: LeveledLogMethod; + warning: LeveledLogMethod; + notice: LeveledLogMethod; + + query(options?: QueryOptions, callback?: (err: Error, results: any) => void): any; + stream(options?: any): NodeJS.ReadableStream; + + startTimer(): Profiler; + profile(id: string | number, meta?: LogEntry): Logger; + + configure(options: LoggerOptions): void; + + child(options: Object): Logger; + + isLevelEnabled(level: string): boolean; + isErrorEnabled(): boolean; + isWarnEnabled(): boolean; + isInfoEnabled(): boolean; + isVerboseEnabled(): boolean; + isDebugEnabled(): boolean; + isSillyEnabled(): boolean; + + new(options?: LoggerOptions): Logger; + } + + interface Container { + loggers: Map; + options: LoggerOptions; + + add(id: string, options?: LoggerOptions): Logger; + get(id: string, options?: LoggerOptions): Logger; + has(id: string): boolean; + close(id?: string): void; + + new(options?: LoggerOptions): Container; + } + + let version: string; + let ExceptionHandler: ExceptionHandler; + let Container: Container; + let loggers: Container; + + let addColors: (target: Config.AbstractConfigSetColors) => any; + let createLogger: (options?: LoggerOptions) => Logger; + + // Pass-through npm level methods routed to the default logger. + let error: LeveledLogMethod; + let warn: LeveledLogMethod; + let info: LeveledLogMethod; + let http: LeveledLogMethod; + let verbose: LeveledLogMethod; + let debug: LeveledLogMethod; + let silly: LeveledLogMethod; + + // Other pass-through methods routed to the default logger. + let log: LogMethod; + let query: (options?: QueryOptions, callback?: (err: Error, results: any) => void) => any; + let stream: (options?: any) => NodeJS.ReadableStream; + let add: (transport: Transport) => Logger; + let remove: (transport: Transport) => Logger; + let clear: () => Logger; + let startTimer: () => Profiler; + let profile: (id: string | number) => Logger; + let configure: (options: LoggerOptions) => void; + let child: (options: Object) => Logger; + let level: string; + let exceptions: ExceptionHandler; + let exitOnError: Function | boolean; + // let default: object; +} + +export = winston; diff --git a/build/node_modules/winston/lib/winston.js b/build/node_modules/winston/lib/winston.js new file mode 100644 index 00000000..e0c4e3ca --- /dev/null +++ b/build/node_modules/winston/lib/winston.js @@ -0,0 +1,182 @@ +/** + * winston.js: Top-level include defining Winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const logform = require('logform'); +const { warn } = require('./winston/common'); + +/** + * Setup to expose. + * @type {Object} + */ +const winston = exports; + +/** + * Expose version. Use `require` method for `webpack` support. + * @type {string} + */ +winston.version = require('../package.json').version; +/** + * Include transports defined by default by winston + * @type {Array} + */ +winston.transports = require('./winston/transports'); +/** + * Expose utility methods + * @type {Object} + */ +winston.config = require('./winston/config'); +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ +winston.addColors = logform.levels; +/** + * Hoist format-related functionality from logform. + * @type {Object} + */ +winston.format = logform.format; +/** + * Expose core Logging-related prototypes. + * @type {function} + */ +winston.createLogger = require('./winston/create-logger'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +winston.ExceptionHandler = require('./winston/exception-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +winston.RejectionHandler = require('./winston/rejection-handler'); +/** + * Expose core Logging-related prototypes. + * @type {Container} + */ +winston.Container = require('./winston/container'); +/** + * Expose core Logging-related prototypes. + * @type {Object} + */ +winston.Transport = require('winston-transport'); +/** + * We create and expose a default `Container` to `winston.loggers` so that the + * programmer may manage multiple `winston.Logger` instances without any + * additional overhead. + * @example + * // some-file1.js + * const logger = require('winston').loggers.get('something'); + * + * // some-file2.js + * const logger = require('winston').loggers.get('something'); + */ +winston.loggers = new winston.Container(); + +/** + * We create and expose a 'defaultLogger' so that the programmer may do the + * following without the need to create an instance of winston.Logger directly: + * @example + * const winston = require('winston'); + * winston.log('info', 'some message'); + * winston.error('some error'); + */ +const defaultLogger = winston.createLogger(); + +// Pass through the target methods onto `winston. +Object.keys(winston.config.npm.levels) + .concat([ + 'log', + 'query', + 'stream', + 'add', + 'remove', + 'clear', + 'profile', + 'startTimer', + 'handleExceptions', + 'unhandleExceptions', + 'handleRejections', + 'unhandleRejections', + 'configure', + 'child' + ]) + .forEach( + method => (winston[method] = (...args) => defaultLogger[method](...args)) + ); + +/** + * Define getter / setter for the default logger level which need to be exposed + * by winston. + * @type {string} + */ +Object.defineProperty(winston, 'level', { + get() { + return defaultLogger.level; + }, + set(val) { + defaultLogger.level = val; + } +}); + +/** + * Define getter for `exceptions` which replaces `handleExceptions` and + * `unhandleExceptions`. + * @type {Object} + */ +Object.defineProperty(winston, 'exceptions', { + get() { + return defaultLogger.exceptions; + } +}); + +/** + * Define getters / setters for appropriate properties of the default logger + * which need to be exposed by winston. + * @type {Logger} + */ +['exitOnError'].forEach(prop => { + Object.defineProperty(winston, prop, { + get() { + return defaultLogger[prop]; + }, + set(val) { + defaultLogger[prop] = val; + } + }); +}); + +/** + * The default transports and exceptionHandlers for the default winston logger. + * @type {Object} + */ +Object.defineProperty(winston, 'default', { + get() { + return { + exceptionHandlers: defaultLogger.exceptionHandlers, + rejectionHandlers: defaultLogger.rejectionHandlers, + transports: defaultLogger.transports + }; + } +}); + +// Have friendlier breakage notices for properties that were exposed by default +// on winston < 3.0. +warn.deprecated(winston, 'setLevels'); +warn.forFunctions(winston, 'useFormat', ['cli']); +warn.forProperties(winston, 'useFormat', ['padLevels', 'stripColors']); +warn.forFunctions(winston, 'deprecated', [ + 'addRewriter', + 'addFilter', + 'clone', + 'extend' +]); +warn.forProperties(winston, 'deprecated', ['emitErrs', 'levelLength']); +// Throw a useful error when users attempt to run `new winston.Logger`. +warn.moved(winston, 'createLogger', 'Logger'); diff --git a/build/node_modules/winston/lib/winston/common.js b/build/node_modules/winston/lib/winston/common.js new file mode 100644 index 00000000..1516510c --- /dev/null +++ b/build/node_modules/winston/lib/winston/common.js @@ -0,0 +1,61 @@ +/** + * common.js: Internal helper and utility functions for winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { format } = require('util'); + +/** + * Set of simple deprecation notices and a way to expose them for a set of + * properties. + * @type {Object} + * @private + */ +exports.warn = { + deprecated(prop) { + return () => { + throw new Error(format('{ %s } was removed in winston@3.0.0.', prop)); + }; + }, + useFormat(prop) { + return () => { + throw new Error([ + format('{ %s } was removed in winston@3.0.0.', prop), + 'Use a custom winston.format = winston.format(function) instead.' + ].join('\n')); + }; + }, + forFunctions(obj, type, props) { + props.forEach(prop => { + obj[prop] = exports.warn[type](prop); + }); + }, + moved(obj, movedTo, prop) { + function movedNotice() { + return () => { + throw new Error([ + format('winston.%s was moved in winston@3.0.0.', prop), + format('Use a winston.%s instead.', movedTo) + ].join('\n')); + }; + } + + Object.defineProperty(obj, prop, { + get: movedNotice, + set: movedNotice + }); + }, + forProperties(obj, type, props) { + props.forEach(prop => { + const notice = exports.warn[type](prop); + Object.defineProperty(obj, prop, { + get: notice, + set: notice + }); + }); + } +}; diff --git a/build/node_modules/winston/lib/winston/config/index.d.ts b/build/node_modules/winston/lib/winston/config/index.d.ts new file mode 100644 index 00000000..053129d0 --- /dev/null +++ b/build/node_modules/winston/lib/winston/config/index.d.ts @@ -0,0 +1,98 @@ +// Type definitions for winston 3.0 +// Project: https://github.com/winstonjs/winston + +/// + +declare namespace winston { + interface AbstractConfigSetLevels { + [key: string]: number; + } + + interface AbstractConfigSetColors { + [key: string]: string | string[]; + } + + interface AbstractConfigSet { + levels: AbstractConfigSetLevels; + colors: AbstractConfigSetColors; + } + + interface CliConfigSetLevels extends AbstractConfigSetLevels { + error: number; + warn: number; + help: number; + data: number; + info: number; + debug: number; + prompt: number; + verbose: number; + input: number; + silly: number; + } + + interface CliConfigSetColors extends AbstractConfigSetColors { + error: string | string[]; + warn: string | string[]; + help: string | string[]; + data: string | string[]; + info: string | string[]; + debug: string | string[]; + prompt: string | string[]; + verbose: string | string[]; + input: string | string[]; + silly: string | string[]; + } + + interface NpmConfigSetLevels extends AbstractConfigSetLevels { + error: number; + warn: number; + info: number; + http: number; + verbose: number; + debug: number; + silly: number; + } + + interface NpmConfigSetColors extends AbstractConfigSetColors { + error: string | string[]; + warn: string | string[]; + info: string | string[]; + verbose: string | string[]; + debug: string | string[]; + silly: string | string[]; + } + + interface SyslogConfigSetLevels extends AbstractConfigSetLevels { + emerg: number; + alert: number; + crit: number; + error: number; + warning: number; + notice: number; + info: number; + debug: number; + } + + interface SyslogConfigSetColors extends AbstractConfigSetColors { + emerg: string | string[]; + alert: string | string[]; + crit: string | string[]; + error: string | string[]; + warning: string | string[]; + notice: string | string[]; + info: string | string[]; + debug: string | string[]; + } + + interface Config { + allColors: AbstractConfigSetColors; + cli: { levels: CliConfigSetLevels, colors: CliConfigSetColors }; + npm: { levels: NpmConfigSetLevels, colors: NpmConfigSetColors }; + syslog: { levels: SyslogConfigSetLevels, colors: SyslogConfigSetColors }; + + addColors(colors: AbstractConfigSetColors): void; + } +} + +declare const winston: winston.Config; +export = winston; diff --git a/build/node_modules/winston/lib/winston/config/index.js b/build/node_modules/winston/lib/winston/config/index.js new file mode 100644 index 00000000..6eb79de1 --- /dev/null +++ b/build/node_modules/winston/lib/winston/config/index.js @@ -0,0 +1,35 @@ +/** + * index.js: Default settings for all levels that winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const logform = require('logform'); +const { configs } = require('triple-beam'); + +/** + * Export config set for the CLI. + * @type {Object} + */ +exports.cli = logform.levels(configs.cli); + +/** + * Export config set for npm. + * @type {Object} + */ +exports.npm = logform.levels(configs.npm); + +/** + * Export config set for the syslog. + * @type {Object} + */ +exports.syslog = logform.levels(configs.syslog); + +/** + * Hoist addColors from logform where it was refactored into in winston@3. + * @type {Object} + */ +exports.addColors = logform.levels; diff --git a/build/node_modules/winston/lib/winston/container.js b/build/node_modules/winston/lib/winston/container.js new file mode 100644 index 00000000..d1fa6810 --- /dev/null +++ b/build/node_modules/winston/lib/winston/container.js @@ -0,0 +1,114 @@ +/** + * container.js: Inversion of control container for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const createLogger = require('./create-logger'); + +/** + * Inversion of control container for winston logger instances. + * @type {Container} + */ +module.exports = class Container { + /** + * Constructor function for the Container object responsible for managing a + * set of `winston.Logger` instances based on string ids. + * @param {!Object} [options={}] - Default pass-thru options for Loggers. + */ + constructor(options = {}) { + this.loggers = new Map(); + this.options = options; + } + + /** + * Retreives a `winston.Logger` instance for the specified `id`. If an + * instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + add(id, options) { + if (!this.loggers.has(id)) { + // Remark: Simple shallow clone for configuration options in case we pass + // in instantiated protoypal objects + options = Object.assign({}, options || this.options); + const existing = options.transports || this.options.transports; + + // Remark: Make sure if we have an array of transports we slice it to + // make copies of those references. + options.transports = existing ? existing.slice() : []; + + const logger = createLogger(options); + logger.on('close', () => this._delete(id)); + this.loggers.set(id, logger); + } + + return this.loggers.get(id); + } + + /** + * Retreives a `winston.Logger` instance for the specified `id`. If + * an instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + get(id, options) { + return this.add(id, options); + } + + /** + * Check if the container has a logger with the id. + * @param {?string} id - The id of the Logger instance to find. + * @returns {boolean} - Boolean value indicating if this instance has a + * logger with the specified `id`. + */ + has(id) { + return !!this.loggers.has(id); + } + + /** + * Closes a `Logger` instance with the specified `id` if it exists. + * If no `id` is supplied then all Loggers are closed. + * @param {?string} id - The id of the Logger instance to close. + * @returns {undefined} + */ + close(id) { + if (id) { + return this._removeLogger(id); + } + + this.loggers.forEach((val, key) => this._removeLogger(key)); + } + + /** + * Remove a logger based on the id. + * @param {!string} id - The id of the logger to remove. + * @returns {undefined} + * @private + */ + _removeLogger(id) { + if (!this.loggers.has(id)) { + return; + } + + const logger = this.loggers.get(id); + logger.close(); + this._delete(id); + } + + /** + * Deletes a `Logger` instance with the specified `id`. + * @param {!string} id - The id of the Logger instance to delete from + * container. + * @returns {undefined} + * @private + */ + _delete(id) { + this.loggers.delete(id); + } +}; diff --git a/build/node_modules/winston/lib/winston/create-logger.js b/build/node_modules/winston/lib/winston/create-logger.js new file mode 100644 index 00000000..e868aeaa --- /dev/null +++ b/build/node_modules/winston/lib/winston/create-logger.js @@ -0,0 +1,104 @@ +/** + * create-logger.js: Logger factory for winston logger instances. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { LEVEL } = require('triple-beam'); +const config = require('./config'); +const Logger = require('./logger'); +const debug = require('@dabh/diagnostics')('winston:create-logger'); + +function isLevelEnabledFunctionName(level) { + return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled'; +} + +/** + * Create a new instance of a winston Logger. Creates a new + * prototype for each instance. + * @param {!Object} opts - Options for the created logger. + * @returns {Logger} - A newly created logger instance. + */ +module.exports = function (opts = {}) { + // + // Default levels: npm + // + opts.levels = opts.levels || config.npm.levels; + + /** + * DerivedLogger to attach the logs level methods. + * @type {DerivedLogger} + * @extends {Logger} + */ + class DerivedLogger extends Logger { + /** + * Create a new class derived logger for which the levels can be attached to + * the prototype of. This is a V8 optimization that is well know to increase + * performance of prototype functions. + * @param {!Object} options - Options for the created logger. + */ + constructor(options) { + super(options); + } + } + + const logger = new DerivedLogger(opts); + + // + // Create the log level methods for the derived logger. + // + Object.keys(opts.levels).forEach(function (level) { + debug('Define prototype method for "%s"', level); + if (level === 'log') { + // eslint-disable-next-line no-console + console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + return; + } + + // + // Define prototype methods for each log level e.g.: + // logger.log('info', msg) implies these methods are defined: + // - logger.info(msg) + // - logger.isInfoEnabled() + // + // Remark: to support logger.child this **MUST** be a function + // so it'll always be called on the instance instead of a fixed + // place in the prototype chain. + // + DerivedLogger.prototype[level] = function (...args) { + // Prefer any instance scope, but default to "root" logger + const self = this || logger; + + // Optimize the hot-path which is the single object. + if (args.length === 1) { + const [msg] = args; + const info = msg && msg.message && msg || { message: msg }; + info.level = info[LEVEL] = level; + self._addDefaultMeta(info); + self.write(info); + return (this || logger); + } + + // When provided nothing assume the empty string + if (args.length === 0) { + self.log(level, ''); + return self; + } + + // Otherwise build argument list which could potentially conform to + // either: + // . v3 API: log(obj) + // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback]) + return self.log(level, ...args); + }; + + DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () { + return (this || logger).isLevelEnabled(level); + }; + }); + + return logger; +}; diff --git a/build/node_modules/winston/lib/winston/exception-handler.js b/build/node_modules/winston/lib/winston/exception-handler.js new file mode 100644 index 00000000..682c530e --- /dev/null +++ b/build/node_modules/winston/lib/winston/exception-handler.js @@ -0,0 +1,245 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const os = require('os'); +const asyncForEach = require('async/forEach'); +const debug = require('@dabh/diagnostics')('winston:exception'); +const once = require('one-time'); +const stackTrace = require('stack-trace'); +const ExceptionStream = require('./exception-stream'); + +/** + * Object for handling uncaughtException events. + * @type {ExceptionHandler} + */ +module.exports = class ExceptionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error('Logger is required to handle exceptions'); + } + + this.logger = logger; + this.handlers = new Map(); + } + + /** + * Handles `uncaughtException` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach(arg => { + if (Array.isArray(arg)) { + return arg.forEach(handler => this._addHandler(handler)); + } + + this._addHandler(arg); + }); + + if (!this.catcher) { + this.catcher = this._uncaughtException.bind(this); + process.on('uncaughtException', this.catcher); + } + } + + /** + * Removes any handlers to `uncaughtException` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener('uncaughtException', this.catcher); + this.catcher = false; + + Array.from(this.handlers.values()) + .forEach(wrapper => this.logger.unpipe(wrapper)); + } + } + + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let { message } = err; + if (!message && typeof err === 'string') { + message = err; + } + + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: [ + `uncaughtException: ${(message || '(no error message)')}`, + err.stack || ' No stack trace' + ].join('\n'), + stack: err.stack, + exception: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(site => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleExceptions = true; + const wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _uncaughtException(err) { + const info = this.getAllInfo(err); + const handlers = this._getExceptionHandlers(); + // Calculate if we should exit on this error + let doExit = typeof this.logger.exitOnError === 'function' + ? this.logger.exitOnError(err) + : this.logger.exitOnError; + let timeout; + + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no exception handlers.'); + // eslint-disable-next-line no-console + console.warn('winston: not exiting process.'); + doExit = false; + } + + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + + if (doExit && !process._exiting) { + // Remark: Currently ignoring any exceptions from transports when + // catching uncaught exceptions. + if (timeout) { + clearTimeout(timeout); + } + // eslint-disable-next-line no-process-exit + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + + // Log to all transports attempting to listen for when they are completed. + asyncForEach(handlers, (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + + // Debug wrapping so that we can inspect what's going on under the covers. + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, () => doExit && gracefulExit()); + + this.logger.log(info); + + // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getExceptionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleExceptions: true` + return this.logger.transports.filter(wrap => { + const transport = wrap.transport || wrap; + return transport.handleExceptions; + }); + } +}; diff --git a/build/node_modules/winston/lib/winston/exception-stream.js b/build/node_modules/winston/lib/winston/exception-stream.js new file mode 100644 index 00000000..477eba0a --- /dev/null +++ b/build/node_modules/winston/lib/winston/exception-stream.js @@ -0,0 +1,54 @@ +/** + * exception-stream.js: TODO: add file header handler. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { Writable } = require('readable-stream'); + +/** + * TODO: add class description. + * @type {ExceptionStream} + * @extends {Writable} + */ +module.exports = class ExceptionStream extends Writable { + /** + * Constructor function for the ExceptionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.exception` set to true. + * @param {!TransportStream} transport - Stream to filter to exceptions + */ + constructor(transport) { + super({ objectMode: true }); + + if (!transport) { + throw new Error('ExceptionStream requires a TransportStream instance.'); + } + + // Remark (indexzero): we set `handleExceptions` here because it's the + // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers + this.handleExceptions = true; + this.transport = transport; + } + + /** + * Writes the info object to our transport instance if (and only if) the + * `exception` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.exception) { + return this.transport.log(info, callback); + } + + callback(); + return true; + } +}; diff --git a/build/node_modules/winston/lib/winston/logger.js b/build/node_modules/winston/lib/winston/logger.js new file mode 100644 index 00000000..89dd4aca --- /dev/null +++ b/build/node_modules/winston/lib/winston/logger.js @@ -0,0 +1,667 @@ +/** + * logger.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const { Stream, Transform } = require('readable-stream'); +const asyncForEach = require('async/forEach'); +const { LEVEL, SPLAT } = require('triple-beam'); +const isStream = require('is-stream'); +const ExceptionHandler = require('./exception-handler'); +const RejectionHandler = require('./rejection-handler'); +const LegacyTransportStream = require('winston-transport/legacy'); +const Profiler = require('./profiler'); +const { warn } = require('./common'); +const config = require('./config'); + +/** + * Captures the number of format (i.e. %s strings) in a given string. + * Based on `util.format`, see Node.js source: + * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230 + * @type {RegExp} + */ +const formatRegExp = /%[scdjifoO%]/g; + +/** + * TODO: add class description. + * @type {Logger} + * @extends {Transform} + */ +class Logger extends Transform { + /** + * Constructor function for the Logger object responsible for persisting log + * messages and metadata to one or more transports. + * @param {!Object} options - foo + */ + constructor(options) { + super({ objectMode: true }); + this.configure(options); + } + + child(defaultRequestMetadata) { + const logger = this; + return Object.create(logger, { + write: { + value: function (info) { + const infoClone = Object.assign( + {}, + defaultRequestMetadata, + info + ); + + // Object.assign doesn't copy inherited Error + // properties so we have to do that explicitly + // + // Remark (indexzero): we should remove this + // since the errors format will handle this case. + // + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + } + + logger.write(infoClone); + } + } + }); + } + + /** + * This will wholesale reconfigure this instance by: + * 1. Resetting all transports. Older transports will be removed implicitly. + * 2. Set all other options including levels, colors, rewriters, filters, + * exceptionHandlers, etc. + * @param {!Object} options - TODO: add param description. + * @returns {undefined} + */ + configure({ + silent, + format, + defaultMeta, + levels, + level = 'info', + exitOnError = true, + transports, + colors, + emitErrs, + formatters, + padLevels, + rewriters, + stripColors, + exceptionHandlers, + rejectionHandlers + } = {}) { + // Reset transports if we already have them + if (this.transports.length) { + this.clear(); + } + + this.silent = silent; + this.format = format || this.format || require('logform/json')(); + + this.defaultMeta = defaultMeta || null; + // Hoist other options onto this instance. + this.levels = levels || this.levels || config.npm.levels; + this.level = level; + this.exceptions = new ExceptionHandler(this); + this.rejections = new RejectionHandler(this); + this.profilers = {}; + this.exitOnError = exitOnError; + + // Add all transports we have been provided. + if (transports) { + transports = Array.isArray(transports) ? transports : [transports]; + transports.forEach(transport => this.add(transport)); + } + + if ( + colors || + emitErrs || + formatters || + padLevels || + rewriters || + stripColors + ) { + throw new Error( + [ + '{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', + 'Use a custom winston.format(function) instead.', + 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md' + ].join('\n') + ); + } + + if (exceptionHandlers) { + this.exceptions.handle(exceptionHandlers); + } + if (rejectionHandlers) { + this.rejections.handle(rejectionHandlers); + } + } + + isLevelEnabled(level) { + const givenLevelValue = getLevelValue(this.levels, level); + if (givenLevelValue === null) { + return false; + } + + const configuredLevelValue = getLevelValue(this.levels, this.level); + if (configuredLevelValue === null) { + return false; + } + + if (!this.transports || this.transports.length === 0) { + return configuredLevelValue >= givenLevelValue; + } + + const index = this.transports.findIndex(transport => { + let transportLevelValue = getLevelValue(this.levels, transport.level); + if (transportLevelValue === null) { + transportLevelValue = configuredLevelValue; + } + return transportLevelValue >= givenLevelValue; + }); + return index !== -1; + } + + /* eslint-disable valid-jsdoc */ + /** + * Ensure backwards compatibility with a `log` method + * @param {mixed} level - Level the log message is written at. + * @param {mixed} msg - TODO: add param description. + * @param {mixed} meta - TODO: add param description. + * @returns {Logger} - TODO: add return description. + * + * @example + * // Supports the existing API: + * logger.log('info', 'Hello world', { custom: true }); + * logger.log('info', new Error('Yo, it\'s on fire')); + * + * // Requires winston.format.splat() + * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); + * + * // And the new API with a single JSON literal: + * logger.log({ level: 'info', message: 'Hello world', custom: true }); + * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); + * + * // Also requires winston.format.splat() + * logger.log({ + * level: 'info', + * message: '%s %d%%', + * [SPLAT]: ['A string', 50], + * meta: { thisIsMeta: true } + * }); + * + */ + /* eslint-enable valid-jsdoc */ + log(level, msg, ...splat) { + // eslint-disable-line max-params + // Optimize for the hotpath of logging JSON literals + if (arguments.length === 1) { + // Yo dawg, I heard you like levels ... seriously ... + // In this context the LHS `level` here is actually the `info` so read + // this as: info[LEVEL] = info.level; + level[LEVEL] = level.level; + this._addDefaultMeta(level); + this.write(level); + return this; + } + + // Slightly less hotpath, but worth optimizing for. + if (arguments.length === 2) { + if (msg && typeof msg === 'object') { + msg[LEVEL] = msg.level = level; + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + + this.write({ [LEVEL]: level, level, message: msg }); + return this; + } + + const [meta] = splat; + if (typeof meta === 'object' && meta !== null) { + // Extract tokens, if none available default to empty array to + // ensure consistancy in expected results + const tokens = msg && msg.match && msg.match(formatRegExp); + + if (!tokens) { + const info = Object.assign({}, this.defaultMeta, meta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + }); + + if (meta.message) info.message = `${info.message} ${meta.message}`; + if (meta.stack) info.stack = meta.stack; + + this.write(info); + return this; + } + } + + this.write(Object.assign({}, this.defaultMeta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + })); + + return this; + } + + /** + * Pushes data so that it can be picked up by all of our pipe targets. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - Continues stream processing. + * @returns {undefined} + * @private + */ + _transform(info, enc, callback) { + if (this.silent) { + return callback(); + } + + // [LEVEL] is only soft guaranteed to be set here since we are a proper + // stream. It is likely that `info` came in through `.log(info)` or + // `.info(info)`. If it is not defined, however, define it. + // This LEVEL symbol is provided by `triple-beam` and also used in: + // - logform + // - winston-transport + // - abstract-winston-transport + if (!info[LEVEL]) { + info[LEVEL] = info.level; + } + + // Remark: really not sure what to do here, but this has been reported as + // very confusing by pre winston@2.0.0 users as quite confusing when using + // custom levels. + if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { + // eslint-disable-next-line no-console + console.error('[winston] Unknown logger level: %s', info[LEVEL]); + } + + // Remark: not sure if we should simply error here. + if (!this._readableState.pipes) { + // eslint-disable-next-line no-console + console.error( + '[winston] Attempt to write logs with no transports %j', + info + ); + } + + // Here we write to the `format` pipe-chain, which on `readable` above will + // push the formatted `info` Object onto the buffer for this instance. We trap + // (and re-throw) any errors generated by the user-provided format, but also + // guarantee that the streams callback is invoked so that we can continue flowing. + try { + this.push(this.format.transform(info, this.format.options)); + } catch (ex) { + throw ex; + } finally { + // eslint-disable-next-line callback-return + callback(); + } + } + + /** + * Delays the 'finish' event until all transport pipe targets have + * also emitted 'finish' or are already finished. + * @param {mixed} callback - Continues stream processing. + */ + _final(callback) { + const transports = this.transports.slice(); + asyncForEach( + transports, + (transport, next) => { + if (!transport || transport.finished) return setImmediate(next); + transport.once('finish', next); + transport.end(); + }, + callback + ); + } + + /** + * Adds the transport to this logger instance by piping to it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + add(transport) { + // Support backwards compatibility with all existing `winston < 3.x.x` + // transports which meet one of two criteria: + // 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream. + // 2. They expose a log method which has a length greater than 2 (i.e. more then + // just `log(info, callback)`. + const target = + !isStream(transport) || transport.log.length > 2 + ? new LegacyTransportStream({ transport }) + : transport; + + if (!target._writableState || !target._writableState.objectMode) { + throw new Error( + 'Transports must WritableStreams in objectMode. Set { objectMode: true }.' + ); + } + + // Listen for the `error` event and the `warn` event on the new Transport. + this._onEvent('error', target); + this._onEvent('warn', target); + this.pipe(target); + + if (transport.handleExceptions) { + this.exceptions.handle(); + } + + if (transport.handleRejections) { + this.rejections.handle(); + } + + return this; + } + + /** + * Removes the transport from this logger instance by unpiping from it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + remove(transport) { + if (!transport) return this; + let target = transport; + if (!isStream(transport) || transport.log.length > 2) { + target = this.transports.filter( + match => match.transport === transport + )[0]; + } + + if (target) { + this.unpipe(target); + } + return this; + } + + /** + * Removes all transports from this logger instance. + * @returns {Logger} - TODO: add return description. + */ + clear() { + this.unpipe(); + return this; + } + + /** + * Cleans up resources (streams, event listeners) for all transports + * associated with this instance (if necessary). + * @returns {Logger} - TODO: add return description. + */ + close() { + this.clear(); + this.emit('close'); + return this; + } + + /** + * Sets the `target` levels specified on this instance. + * @param {Object} Target levels to use on this instance. + */ + setLevels() { + warn.deprecated('setLevels'); + } + + /** + * Queries the all transports for this instance with the specified `options`. + * This will aggregate each transport's results into one object containing + * a property per transport. + * @param {Object} options - Query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + */ + query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + const results = {}; + const queryObject = Object.assign({}, options.query || {}); + + // Helper function to query a single transport + function queryTransport(transport, next) { + if (options.query && typeof transport.formatQuery === 'function') { + options.query = transport.formatQuery(queryObject); + } + + transport.query(options, (err, res) => { + if (err) { + return next(err); + } + + if (typeof transport.formatResults === 'function') { + res = transport.formatResults(res, options.format); + } + + next(null, res); + }); + } + + // Helper function to accumulate the results from `queryTransport` into + // the `results`. + function addResults(transport, next) { + queryTransport(transport, (err, result) => { + // queryTransport could potentially invoke the callback multiple times + // since Transport code can be unpredictable. + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + + // eslint-disable-next-line callback-return + next(); + } + + next = null; + }); + } + + // Iterate over the transports in parallel setting the appropriate key in + // the `results`. + asyncForEach( + this.transports.filter(transport => !!transport.query), + addResults, + () => callback(null, results) + ); + } + + /** + * Returns a log stream for all transports. Options object is optional. + * @param{Object} options={} - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + */ + stream(options = {}) { + const out = new Stream(); + const streams = []; + + out._streams = streams; + out.destroy = () => { + let i = streams.length; + while (i--) { + streams[i].destroy(); + } + }; + + // Create a list of all transports for this instance. + this.transports + .filter(transport => !!transport.stream) + .forEach(transport => { + const str = transport.stream(options); + if (!str) { + return; + } + + streams.push(str); + + str.on('log', log => { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit('log', log); + }); + + str.on('error', err => { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit('error', err); + }); + }); + + return out; + } + + /** + * Returns an object corresponding to a specific timing. When done is called + * the timer will finish and log the duration. e.g.: + * @returns {Profile} - TODO: add return description. + * @example + * const timer = winston.startTimer() + * setTimeout(() => { + * timer.done({ + * message: 'Logging message' + * }); + * }, 1000); + */ + startTimer() { + return new Profiler(this); + } + + /** + * Tracks the time inbetween subsequent calls to this method with the same + * `id` parameter. The second call to this method will log the difference in + * milliseconds along with the message. + * @param {string} id Unique id of the profiler + * @returns {Logger} - TODO: add return description. + */ + profile(id, ...args) { + const time = Date.now(); + if (this.profilers[id]) { + const timeEnd = this.profilers[id]; + delete this.profilers[id]; + + // Attempt to be kind to users if they are still using older APIs. + if (typeof args[args.length - 2] === 'function') { + // eslint-disable-next-line no-console + console.warn( + 'Callback function no longer supported as of winston@3.0.0' + ); + args.pop(); + } + + // Set the duration property of the metadata + const info = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = time - timeEnd; + info.message = info.message || id; + return this.write(info); + } + + this.profilers[id] = time; + return this; + } + + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + handleExceptions(...args) { + // eslint-disable-next-line no-console + console.warn( + 'Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()' + ); + this.exceptions.handle(...args); + } + + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + unhandleExceptions(...args) { + // eslint-disable-next-line no-console + console.warn( + 'Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()' + ); + this.exceptions.unhandle(...args); + } + + /** + * Throw a more meaningful deprecation notice + * @throws {Error} - TODO: add throws description. + */ + cli() { + throw new Error( + [ + 'Logger.cli() was removed in winston@3.0.0', + 'Use a custom winston.formats.cli() instead.', + 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md' + ].join('\n') + ); + } + + /** + * Bubbles the `event` that occured on the specified `transport` up + * from this instance. + * @param {string} event - The event that occured + * @param {Object} transport - Transport on which the event occured + * @private + */ + _onEvent(event, transport) { + function transportEvent(err) { + // https://github.com/winstonjs/winston/issues/1364 + if (event === 'error' && !this.transports.includes(transport)) { + this.add(transport); + } + this.emit(event, err, transport); + } + + if (!transport['__winston' + event]) { + transport['__winston' + event] = transportEvent.bind(this); + transport.on(event, transport['__winston' + event]); + } + } + + _addDefaultMeta(msg) { + if (this.defaultMeta) { + Object.assign(msg, this.defaultMeta); + } + } +} + +function getLevelValue(levels, level) { + const value = levels[level]; + if (!value && value !== 0) { + return null; + } + return value; +} + +/** + * Represents the current readableState pipe targets for this Logger instance. + * @type {Array|Object} + */ +Object.defineProperty(Logger.prototype, 'transports', { + configurable: false, + enumerable: true, + get() { + const { pipes } = this._readableState; + return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + } +}); + +module.exports = Logger; diff --git a/build/node_modules/winston/lib/winston/profiler.js b/build/node_modules/winston/lib/winston/profiler.js new file mode 100644 index 00000000..edcc5a65 --- /dev/null +++ b/build/node_modules/winston/lib/winston/profiler.js @@ -0,0 +1,51 @@ +/** + * profiler.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * TODO: add class description. + * @type {Profiler} + * @private + */ +module.exports = class Profiler { + /** + * Constructor function for the Profiler instance used by + * `Logger.prototype.startTimer`. When done is called the timer will finish + * and log the duration. + * @param {!Logger} logger - TODO: add param description. + * @private + */ + constructor(logger) { + if (!logger) { + throw new Error('Logger is required for profiling.'); + } + + this.logger = logger; + this.start = Date.now(); + } + + /** + * Ends the current timer (i.e. Profiler) instance and logs the `msg` along + * with the duration since creation. + * @returns {mixed} - TODO: add return description. + * @private + */ + done(...args) { + if (typeof args[args.length - 1] === 'function') { + // eslint-disable-next-line no-console + console.warn('Callback function no longer supported as of winston@3.0.0'); + args.pop(); + } + + const info = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + info.level = info.level || 'info'; + info.durationMs = (Date.now()) - this.start; + + return this.logger.write(info); + } +}; diff --git a/build/node_modules/winston/lib/winston/rejection-handler.js b/build/node_modules/winston/lib/winston/rejection-handler.js new file mode 100644 index 00000000..7d8f65e5 --- /dev/null +++ b/build/node_modules/winston/lib/winston/rejection-handler.js @@ -0,0 +1,251 @@ +/** + * exception-handler.js: Object for handling uncaughtException events. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const os = require('os'); +const asyncForEach = require('async/forEach'); +const debug = require('@dabh/diagnostics')('winston:rejection'); +const once = require('one-time'); +const stackTrace = require('stack-trace'); +const ExceptionStream = require('./exception-stream'); + +/** + * Object for handling unhandledRejection events. + * @type {RejectionHandler} + */ +module.exports = class RejectionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error('Logger is required to handle rejections'); + } + + this.logger = logger; + this.handlers = new Map(); + } + + /** + * Handles `unhandledRejection` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach(arg => { + if (Array.isArray(arg)) { + return arg.forEach(handler => this._addHandler(handler)); + } + + this._addHandler(arg); + }); + + if (!this.catcher) { + this.catcher = this._unhandledRejection.bind(this); + process.on('unhandledRejection', this.catcher); + } + } + + /** + * Removes any handlers to `unhandledRejection` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener('unhandledRejection', this.catcher); + this.catcher = false; + + Array.from(this.handlers.values()).forEach(wrapper => + this.logger.unpipe(wrapper) + ); + } + } + + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let { message } = err; + if (!message && typeof err === 'string') { + message = err; + } + + return { + error: err, + // TODO (indexzero): how do we configure this? + level: 'error', + message: [ + `unhandledRejection: ${message || '(no error message)'}`, + err.stack || ' No stack trace' + ].join('\n'), + stack: err.stack, + exception: true, + date: new Date().toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; + } + + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(site => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleRejections = true; + const wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _unhandledRejection(err) { + const info = this.getAllInfo(err); + const handlers = this._getRejectionHandlers(); + // Calculate if we should exit on this error + let doExit = + typeof this.logger.exitOnError === 'function' + ? this.logger.exitOnError(err) + : this.logger.exitOnError; + let timeout; + + if (!handlers.length && doExit) { + // eslint-disable-next-line no-console + console.warn('winston: exitOnError cannot be true with no rejection handlers.'); + // eslint-disable-next-line no-console + console.warn('winston: not exiting process.'); + doExit = false; + } + + function gracefulExit() { + debug('doExit', doExit); + debug('process._exiting', process._exiting); + + if (doExit && !process._exiting) { + // Remark: Currently ignoring any rejections from transports when + // catching unhandled rejections. + if (timeout) { + clearTimeout(timeout); + } + // eslint-disable-next-line no-process-exit + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + + // Log to all transports attempting to listen for when they are completed. + asyncForEach( + handlers, + (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + + // Debug wrapping so that we can inspect what's going on under the covers. + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + + transport._ending = true; + transport.once('finish', onDone('finished')); + transport.once('error', onDone('error')); + }, + () => doExit && gracefulExit() + ); + + this.logger.log(info); + + // If exitOnError is true, then only allow the logging of exceptions to + // take up to `3000ms`. + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } + } + + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getRejectionHandlers() { + // Remark (indexzero): since `logger.transports` returns all of the pipes + // from the _readableState of the stream we actually get the join of the + // explicit handlers and the implicit transports with + // `handleRejections: true` + return this.logger.transports.filter(wrap => { + const transport = wrap.transport || wrap; + return transport.handleRejections; + }); + } +}; diff --git a/build/node_modules/winston/lib/winston/tail-file.js b/build/node_modules/winston/lib/winston/tail-file.js new file mode 100644 index 00000000..86ea904c --- /dev/null +++ b/build/node_modules/winston/lib/winston/tail-file.js @@ -0,0 +1,124 @@ +/** + * tail-file.js: TODO: add file header description. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const fs = require('fs'); +const { StringDecoder } = require('string_decoder'); +const { Stream } = require('readable-stream'); + +/** + * Simple no-op function. + * @returns {undefined} + */ +function noop() {} + +/** + * TODO: add function description. + * @param {Object} options - Options for tail. + * @param {function} iter - Iterator function to execute on every line. +* `tail -f` a file. Options must include file. + * @returns {mixed} - TODO: add return description. + */ +module.exports = (options, iter) => { + const buffer = Buffer.alloc(64 * 1024); + const decode = new StringDecoder('utf8'); + const stream = new Stream(); + let buff = ''; + let pos = 0; + let row = 0; + + if (options.start === -1) { + delete options.start; + } + + stream.readable = true; + stream.destroy = () => { + stream.destroyed = true; + stream.emit('end'); + stream.emit('close'); + }; + + fs.open(options.file, 'a+', '0644', (err, fd) => { + if (err) { + if (!iter) { + stream.emit('error', err); + } else { + iter(err); + } + stream.destroy(); + return; + } + + (function read() { + if (stream.destroyed) { + fs.close(fd, noop); + return; + } + + return fs.read(fd, buffer, 0, buffer.length, pos, (error, bytes) => { + if (error) { + if (!iter) { + stream.emit('error', error); + } else { + iter(error); + } + stream.destroy(); + return; + } + + if (!bytes) { + if (buff) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', buff); + } else { + iter(null, buff); + } + } + row++; + buff = ''; + } + return setTimeout(read, 1000); + } + + let data = decode.write(buffer.slice(0, bytes)); + if (!iter) { + stream.emit('data', data); + } + + data = (buff + data).split(/\n+/); + + const l = data.length - 1; + let i = 0; + + for (; i < l; i++) { + // eslint-disable-next-line eqeqeq + if (options.start == null || row > options.start) { + if (!iter) { + stream.emit('line', data[i]); + } else { + iter(null, data[i]); + } + } + row++; + } + + buff = data[l]; + pos += bytes; + return read(); + }); + }()); + }); + + if (!iter) { + return stream; + } + + return stream.destroy; +}; diff --git a/build/node_modules/winston/lib/winston/transports/console.js b/build/node_modules/winston/lib/winston/transports/console.js new file mode 100644 index 00000000..1bb08978 --- /dev/null +++ b/build/node_modules/winston/lib/winston/transports/console.js @@ -0,0 +1,117 @@ +/* eslint-disable no-console */ +/* + * console.js: Transport for outputting to the console. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const os = require('os'); +const { LEVEL, MESSAGE } = require('triple-beam'); +const TransportStream = require('winston-transport'); + +/** + * Transport for outputting to the console. + * @type {Console} + * @extends {TransportStream} + */ +module.exports = class Console extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + + // Expose the name of this Transport on the prototype + this.name = options.name || 'console'; + this.stderrLevels = this._stringArrayToSet(options.stderrLevels); + this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels); + this.eol = options.eol || os.EOL; + + this.setMaxListeners(30); + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit('logged', info)); + + // Remark: what if there is no raw...? + if (this.stderrLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + // console.error adds a newline + console.error(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } else if (this.consoleWarnLevels[info[LEVEL]]) { + if (console._stderr) { + // Node.js maps `process.stderr` to `console._stderr`. + // in Node.js console.warn is an alias for console.error + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + // console.warn adds a newline + console.warn(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + + if (console._stdout) { + // Node.js maps `process.stdout` to `console._stdout`. + console._stdout.write(`${info[MESSAGE]}${this.eol}`); + } else { + // console.log adds a newline. + console.log(info[MESSAGE]); + } + + if (callback) { + callback(); // eslint-disable-line callback-return + } + } + + /** + * Returns a Set-like object with strArray's elements as keys (each with the + * value true). + * @param {Array} strArray - Array of Set-elements as strings. + * @param {?string} [errMsg] - Custom error message thrown on invalid input. + * @returns {Object} - TODO: add return description. + * @private + */ + _stringArrayToSet(strArray, errMsg) { + if (!strArray) + return {}; + + errMsg = errMsg || 'Cannot make set from type other than Array of string elements'; + + if (!Array.isArray(strArray)) { + throw new Error(errMsg); + } + + return strArray.reduce((set, el) => { + if (typeof el !== 'string') { + throw new Error(errMsg); + } + set[el] = true; + + return set; + }, {}); + } +}; diff --git a/build/node_modules/winston/lib/winston/transports/file.js b/build/node_modules/winston/lib/winston/transports/file.js new file mode 100644 index 00000000..d0314be9 --- /dev/null +++ b/build/node_modules/winston/lib/winston/transports/file.js @@ -0,0 +1,695 @@ +/* eslint-disable complexity,max-statements */ +/** + * file.js: Transport for outputting to a local log file. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const asyncSeries = require('async/series'); +const zlib = require('zlib'); +const { MESSAGE } = require('triple-beam'); +const { Stream, PassThrough } = require('readable-stream'); +const TransportStream = require('winston-transport'); +const debug = require('@dabh/diagnostics')('winston:file'); +const os = require('os'); +const tailFile = require('../tail-file'); + +/** + * Transport for outputting to a local log file. + * @type {File} + * @extends {TransportStream} + */ +module.exports = class File extends TransportStream { + /** + * Constructor function for the File transport object responsible for + * persisting log messages and metadata to one or more files. + * @param {Object} options - Options for this instance. + */ + constructor(options = {}) { + super(options); + + // Expose the name of this Transport on the prototype. + this.name = options.name || 'file'; + + // Helper function which throws an `Error` in the event that any of the + // rest of the arguments is present in `options`. + function throwIf(target, ...args) { + args.slice(1).forEach(name => { + if (options[name]) { + throw new Error(`Cannot set ${name} and ${target} together`); + } + }); + } + + // Setup the base stream that always gets piped to to handle buffering. + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + + // Bind this context for listener methods. + this._onError = this._onError.bind(this); + + if (options.filename || options.dirname) { + throwIf('filename or dirname', 'stream'); + this._basename = this.filename = options.filename + ? path.basename(options.filename) + : 'winston.log'; + + this.dirname = options.dirname || path.dirname(options.filename); + this.options = options.options || { flags: 'a' }; + } else if (options.stream) { + // eslint-disable-next-line no-console + console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream'); + throwIf('stream', 'filename', 'maxsize'); + this._dest = this._stream.pipe(this._setupStream(options.stream)); + this.dirname = path.dirname(this._dest.path); + // We need to listen for drain events when write() returns false. This + // can make node mad at times. + } else { + throw new Error('Cannot log to file without filename or stream.'); + } + + this.maxsize = options.maxsize || null; + this.rotationFormat = options.rotationFormat || false; + this.zippedArchive = options.zippedArchive || false; + this.maxFiles = options.maxFiles || null; + this.eol = options.eol || os.EOL; + this.tailable = options.tailable || false; + + // Internal state variables representing the number of files this instance + // has created and the current size (in bytes) of the current logfile. + this._size = 0; + this._pendingSize = 0; + this._created = 0; + this._drain = false; + this._opening = false; + this._ending = false; + + if (this.dirname) this._createLogDirIfNotExist(this.dirname); + this.open(); + } + + finishIfEnding() { + if (this._ending) { + if (this._opening) { + this.once('open', () => { + this._stream.once('finish', () => this.emit('finish')); + setImmediate(() => this._stream.end()); + }); + } else { + this._stream.once('finish', () => this.emit('finish')); + setImmediate(() => this._stream.end()); + } + } + } + + + /** + * Core logging method exposed to Winston. Metadata is optional. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback = () => {}) { + // Remark: (jcrugzz) What is necessary about this callback(null, true) now + // when thinking about 3.x? Should silent be handled in the base + // TransportStream _write method? + if (this.silent) { + callback(); + return true; + } + + // Output stream buffer is full and has asked us to wait for the drain event + if (this._drain) { + this._stream.once('drain', () => { + this._drain = false; + this.log(info, callback); + }); + return; + } + if (this._rotate) { + this._stream.once('rotate', () => { + this._rotate = false; + this.log(info, callback); + }); + return; + } + + // Grab the raw string and append the expected EOL. + const output = `${info[MESSAGE]}${this.eol}`; + const bytes = Buffer.byteLength(output); + + // After we have written to the PassThrough check to see if we need + // to rotate to the next file. + // + // Remark: This gets called too early and does not depict when data + // has been actually flushed to disk. + function logged() { + this._size += bytes; + this._pendingSize -= bytes; + + debug('logged %s %s', this._size, output); + this.emit('logged', info); + + // Do not attempt to rotate files while opening + if (this._opening) { + return; + } + + // Check to see if we need to end the stream and create a new one. + if (!this._needsNewFile()) { + return; + } + + // End the current stream, ensure it flushes and create a new one. + // This could potentially be optimized to not run a stat call but its + // the safest way since we are supporting `maxFiles`. + this._rotate = true; + this._endStream(() => this._rotateFile()); + } + + // Keep track of the pending bytes being written while files are opening + // in order to properly rotate the PassThrough this._stream when the file + // eventually does open. + this._pendingSize += bytes; + if (this._opening + && !this.rotatedWhileOpening + && this._needsNewFile(this._size + this._pendingSize)) { + this.rotatedWhileOpening = true; + } + + const written = this._stream.write(output, logged.bind(this)); + if (!written) { + this._drain = true; + this._stream.once('drain', () => { + this._drain = false; + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + + debug('written', written, this._drain); + + this.finishIfEnding(); + + return written; + } + + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * TODO: Refactor me. + */ + query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = normalizeQuery(options); + const file = path.join(this.dirname, this.filename); + let buff = ''; + let results = []; + let row = 0; + + const stream = fs.createReadStream(file, { + encoding: 'utf8' + }); + + stream.on('error', err => { + if (stream.readable) { + stream.destroy(); + } + if (!callback) { + return; + } + + return err.code !== 'ENOENT' ? callback(err) : callback(null, results); + }); + + stream.on('data', data => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; + } + + buff = data[l]; + }); + + stream.on('close', () => { + if (buff) { + add(buff, true); + } + if (options.order === 'desc') { + results = results.reverse(); + } + + // eslint-disable-next-line callback-return + if (callback) callback(null, results); + }); + + function add(buff, attempt) { + try { + const log = JSON.parse(buff); + if (check(log)) { + push(log); + } + } catch (e) { + if (!attempt) { + stream.emit('error', e); + } + } + } + + function push(log) { + if ( + options.rows && + results.length >= options.rows && + options.order !== 'desc' + ) { + if (stream.readable) { + stream.destroy(); + } + return; + } + + if (options.fields) { + log = options.fields.reduce((obj, key) => { + obj[key] = log[key]; + return obj; + }, {}); + } + + if (options.order === 'desc') { + if (results.length >= options.rows) { + results.shift(); + } + } + results.push(log); + } + + function check(log) { + if (!log) { + return; + } + + if (typeof log !== 'object') { + return; + } + + const time = new Date(log.timestamp); + if ( + (options.from && time < options.from) || + (options.until && time > options.until) || + (options.level && options.level !== log.level) + ) { + return; + } + + return true; + } + + function normalizeQuery(options) { + options = options || {}; + + // limit + options.rows = options.rows || options.limit || 10; + + // starting row offset + options.start = options.start || 0; + + // now + options.until = options.until || new Date(); + if (typeof options.until !== 'object') { + options.until = new Date(options.until); + } + + // now - 24 + options.from = options.from || (options.until - (24 * 60 * 60 * 1000)); + if (typeof options.from !== 'object') { + options.from = new Date(options.from); + } + + // 'asc' or 'desc' + options.order = options.order || 'desc'; + + return options; + } + } + + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + * TODO: Refactor me. + */ + stream(options = {}) { + const file = path.join(this.dirname, this.filename); + const stream = new Stream(); + const tail = { + file, + start: options.start + }; + + stream.destroy = tailFile(tail, (err, line) => { + if (err) { + return stream.emit('error', err); + } + + try { + stream.emit('data', line); + line = JSON.parse(line); + stream.emit('log', line); + } catch (e) { + stream.emit('error', e); + } + }); + + return stream; + } + + /** + * Checks to see the filesize of. + * @returns {undefined} + */ + open() { + // If we do not have a filename then we were passed a stream and + // don't need to keep track of size. + if (!this.filename) return; + if (this._opening) return; + + this._opening = true; + + // Stat the target file to get the size and create the stream. + this.stat((err, size) => { + if (err) { + return this.emit('error', err); + } + debug('stat done: %s { size: %s }', this.filename, size); + this._size = size; + this._dest = this._createStream(this._stream); + this._opening = false; + this.once('open', () => { + if (this._stream.eventNames().includes('rotate')) { + this._stream.emit('rotate'); + } else { + this._rotate = false; + } + }); + }); + } + + /** + * Stat the file and assess information in order to create the proper stream. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + stat(callback) { + const target = this._getFile(); + const fullpath = path.join(this.dirname, target); + + fs.stat(fullpath, (err, stat) => { + if (err && err.code === 'ENOENT') { + debug('ENOENT ok', fullpath); + // Update internally tracked filename with the new target name. + this.filename = target; + return callback(null, 0); + } + + if (err) { + debug(`err ${err.code} ${fullpath}`); + return callback(err); + } + + if (!stat || this._needsNewFile(stat.size)) { + // If `stats.size` is greater than the `maxsize` for this + // instance then try again. + return this._incFile(() => this.stat(callback)); + } + + // Once we have figured out what the filename is, set it + // and return the size. + this.filename = target; + callback(null, stat.size); + }); + } + + /** + * Closes the stream associated with this instance. + * @param {function} cb - TODO: add param description. + * @returns {undefined} + */ + close(cb) { + if (!this._stream) { + return; + } + + this._stream.end(() => { + if (cb) { + cb(); // eslint-disable-line callback-return + } + this.emit('flush'); + this.emit('closed'); + }); + } + + /** + * TODO: add method description. + * @param {number} size - TODO: add param description. + * @returns {undefined} + */ + _needsNewFile(size) { + size = size || this._size; + return this.maxsize && size >= this.maxsize; + } + + /** + * TODO: add method description. + * @param {Error} err - TODO: add param description. + * @returns {undefined} + */ + _onError(err) { + this.emit('error', err); + } + + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _setupStream(stream) { + stream.on('error', this._onError); + + return stream; + } + + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _cleanupStream(stream) { + stream.removeListener('error', this._onError); + + return stream; + } + + /** + * TODO: add method description. + */ + _rotateFile() { + this._incFile(() => this.open()); + } + + /** + * Unpipe from the stream that has been marked as full and end it so it + * flushes to disk. + * + * @param {function} callback - Callback for when the current file has closed. + * @private + */ + _endStream(callback = () => {}) { + if (this._dest) { + this._stream.unpipe(this._dest); + this._dest.end(() => { + this._cleanupStream(this._dest); + callback(); + }); + } else { + callback(); // eslint-disable-line callback-return + } + } + + /** + * Returns the WritableStream for the active file on this instance. If we + * should gzip the file then a zlib stream is returned. + * + * @param {ReadableStream} source – PassThrough to pipe to the file when open. + * @returns {WritableStream} Stream that writes to disk for the active file. + */ + _createStream(source) { + const fullpath = path.join(this.dirname, this.filename); + + debug('create stream start', fullpath, this.options); + const dest = fs.createWriteStream(fullpath, this.options) + // TODO: What should we do with errors here? + .on('error', err => debug(err)) + .on('close', () => debug('close', dest.path, dest.bytesWritten)) + .on('open', () => { + debug('file open ok', fullpath); + this.emit('open', fullpath); + source.pipe(dest); + + // If rotation occured during the open operation then we immediately + // start writing to a new PassThrough, begin opening the next file + // and cleanup the previous source and dest once the source has drained. + if (this.rotatedWhileOpening) { + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + this._rotateFile(); + this.rotatedWhileOpening = false; + this._cleanupStream(dest); + source.end(); + } + }); + + debug('create stream ok', fullpath); + if (this.zippedArchive) { + const gzip = zlib.createGzip(); + gzip.pipe(dest); + return gzip; + } + + return dest; + } + + /** + * TODO: add method description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + _incFile(callback) { + debug('_incFile', this.filename); + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, callback); + } else { + this._checkMaxFilesTailable(ext, basename, callback); + } + } + + /** + * Gets the next filename to use for this instance in the case that log + * filesizes are being capped. + * @returns {string} - TODO: add return description. + * @private + */ + _getFile() { + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const isRotation = this.rotationFormat + ? this.rotationFormat() + : this._created; + + // Caveat emptor (indexzero): rotationFormat() was broken by design When + // combined with max files because the set of files to unlink is never + // stored. + const target = !this.tailable && this._created + ? `${basename}${isRotation}${ext}` + : `${basename}${ext}`; + + return this.zippedArchive && !this.tailable + ? `${target}.gz` + : target; + } + + /** + * Increment the number of files created or checked by this instance. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesIncrementing(ext, basename, callback) { + // Check for maxFiles option and delete file. + if (!this.maxFiles || this._created < this.maxFiles) { + return setImmediate(callback); + } + + const oldest = this._created - this.maxFiles; + const isOldest = oldest !== 0 ? oldest : ''; + const isZipped = this.zippedArchive ? '.gz' : ''; + const filePath = `${basename}${isOldest}${ext}${isZipped}`; + const target = path.join(this.dirname, filePath); + + fs.unlink(target, callback); + } + + /** + * Roll files forward based on integer, up to maxFiles. e.g. if base if + * file.log and it becomes oversized, roll to file1.log, and allow file.log + * to be re-used. If file is oversized again, roll file1.log to file2.log, + * roll file.log to file1.log, and so on. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesTailable(ext, basename, callback) { + const tasks = []; + if (!this.maxFiles) { + return; + } + + // const isZipped = this.zippedArchive ? '.gz' : ''; + const isZipped = this.zippedArchive ? '.gz' : ''; + for (let x = this.maxFiles - 1; x > 1; x--) { + tasks.push(function (i, cb) { + let fileName = `${basename}${(i - 1)}${ext}${isZipped}`; + const tmppath = path.join(this.dirname, fileName); + + fs.exists(tmppath, exists => { + if (!exists) { + return cb(null); + } + + fileName = `${basename}${i}${ext}${isZipped}`; + fs.rename(tmppath, path.join(this.dirname, fileName), cb); + }); + }.bind(this, x)); + } + + asyncSeries(tasks, () => { + fs.rename( + path.join(this.dirname, `${basename}${ext}`), + path.join(this.dirname, `${basename}1${ext}${isZipped}`), + callback + ); + }); + } + + _createLogDirIfNotExist(dirPath) { + /* eslint-disable no-sync */ + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + } + /* eslint-enable no-sync */ + } +}; diff --git a/build/node_modules/winston/lib/winston/transports/http.js b/build/node_modules/winston/lib/winston/transports/http.js new file mode 100644 index 00000000..ad29ef6e --- /dev/null +++ b/build/node_modules/winston/lib/winston/transports/http.js @@ -0,0 +1,202 @@ +/** + * http.js: Transport for outputting to a json-rpcserver. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const http = require('http'); +const https = require('https'); +const { Stream } = require('readable-stream'); +const TransportStream = require('winston-transport'); + +/** + * Transport for outputting to a json-rpc server. + * @type {Stream} + * @extends {TransportStream} + */ +module.exports = class Http extends TransportStream { + /** + * Constructor function for the Http transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + + this.options = options; + this.name = options.name || 'http'; + this.ssl = !!options.ssl; + this.host = options.host || 'localhost'; + this.port = options.port; + this.auth = options.auth; + this.path = options.path || ''; + this.agent = options.agent; + this.headers = options.headers || {}; + this.headers['content-type'] = 'application/json'; + + if (!this.port) { + this.port = this.ssl ? 443 : 80; + } + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + this._request(info, (err, res) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + + if (err) { + this.emit('warn', err); + } else { + this.emit('logged', info); + } + }); + + // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering + // and block more requests from happening? + if (callback) { + setImmediate(callback); + } + } + + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * @returns {undefined} + */ + query(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = { + method: 'query', + params: this.normalizeQuery(options) + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + this._request(options, (err, res, body) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + + if (err) { + return callback(err); + } + + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + + callback(null, body); + }); + } + + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description + */ + stream(options = {}) { + const stream = new Stream(); + options = { + method: 'stream', + params: options + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + let buff = ''; + const req = this._request(options); + + stream.destroy = () => req.destroy(); + req.on('data', data => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + + let i = 0; + for (; i < l; i++) { + try { + stream.emit('log', JSON.parse(data[i])); + } catch (e) { + stream.emit('error', e); + } + } + + buff = data[l]; + }); + req.on('error', err => stream.emit('error', err)); + + return stream; + } + + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + */ + _request(options, callback) { + options = options || {}; + + const auth = options.auth || this.auth; + const path = options.path || this.path || ''; + + delete options.auth; + delete options.path; + + // Prepare options for outgoing HTTP request + const headers = Object.assign({}, this.headers); + if (auth && auth.bearer) { + headers.Authorization = `Bearer ${auth.bearer}`; + } + const req = (this.ssl ? https : http).request({ + ...this.options, + method: 'POST', + host: this.host, + port: this.port, + path: `/${path.replace(/^\//, '')}`, + headers: headers, + auth: (auth && auth.username && auth.password) ? (`${auth.username}:${auth.password}`) : '', + agent: this.agent + }); + + req.on('error', callback); + req.on('response', res => ( + res.on('end', () => callback(null, res)).resume() + )); + req.end(Buffer.from(JSON.stringify(options), 'utf8')); + } +}; diff --git a/build/node_modules/winston/lib/winston/transports/index.d.ts b/build/node_modules/winston/lib/winston/transports/index.d.ts new file mode 100644 index 00000000..ae0633c0 --- /dev/null +++ b/build/node_modules/winston/lib/winston/transports/index.d.ts @@ -0,0 +1,100 @@ +// Type definitions for winston 3.0 +// Project: https://github.com/winstonjs/winston + +/// + +import {Agent} from "http"; + +import * as Transport from 'winston-transport'; + +declare namespace winston { + interface ConsoleTransportOptions extends Transport.TransportStreamOptions { + consoleWarnLevels?: string[], + stderrLevels?: string[]; + debugStdout?: boolean; + eol?: string; + } + + interface ConsoleTransportInstance extends Transport { + name: string; + stderrLevels: string[]; + eol: string; + + new(options?: ConsoleTransportOptions): ConsoleTransportInstance; + } + + interface FileTransportOptions extends Transport.TransportStreamOptions { + filename?: string; + dirname?: string; + options?: object; + maxsize?: number; + stream?: NodeJS.WritableStream; + rotationFormat?: Function; + zippedArchive?: boolean; + maxFiles?: number; + eol?: string; + tailable?: boolean; + } + + interface FileTransportInstance extends Transport { + name: string; + filename: string; + dirname: string; + options: object; + maxsize: number | null; + rotationFormat: Function | boolean; + zippedArchive: boolean; + maxFiles: number | null; + eol: string; + tailable: boolean; + + new(options?: FileTransportOptions): FileTransportInstance; + } + + interface HttpTransportOptions extends Transport.TransportStreamOptions { + ssl?: any; + host?: string; + port?: number; + auth?: { username?: string | undefined, password?: string | undefined, bearer?: string | undefined }; + path?: string; + agent?: Agent; + headers?: object; + } + + interface HttpTransportInstance extends Transport { + name: string; + ssl: boolean; + host: string; + port: number; + auth?: { username?: string | undefined, password?: string | undefined, bearer?: string | undefined }; + path: string; + agent?: Agent | null; + + new(options?: HttpTransportOptions): HttpTransportInstance; + } + + interface StreamTransportOptions extends Transport.TransportStreamOptions { + stream: NodeJS.WritableStream; + eol?: string; + } + + interface StreamTransportInstance extends Transport { + eol: string; + + new(options?: StreamTransportOptions): StreamTransportInstance; + } + + interface Transports { + FileTransportOptions: FileTransportOptions; + File: FileTransportInstance; + ConsoleTransportOptions: ConsoleTransportOptions; + Console: ConsoleTransportInstance; + HttpTransportOptions: HttpTransportOptions; + Http: HttpTransportInstance; + StreamTransportOptions: StreamTransportOptions; + Stream: StreamTransportInstance; + } +} + +declare const winston: winston.Transports; +export = winston; diff --git a/build/node_modules/winston/lib/winston/transports/index.js b/build/node_modules/winston/lib/winston/transports/index.js new file mode 100644 index 00000000..f2f7cc35 --- /dev/null +++ b/build/node_modules/winston/lib/winston/transports/index.js @@ -0,0 +1,56 @@ +/** + * transports.js: Set of all transports Winston knows about. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +/** + * TODO: add property description. + * @type {Console} + */ +Object.defineProperty(exports, 'Console', { + configurable: true, + enumerable: true, + get() { + return require('./console'); + } +}); + +/** + * TODO: add property description. + * @type {File} + */ +Object.defineProperty(exports, 'File', { + configurable: true, + enumerable: true, + get() { + return require('./file'); + } +}); + +/** + * TODO: add property description. + * @type {Http} + */ +Object.defineProperty(exports, 'Http', { + configurable: true, + enumerable: true, + get() { + return require('./http'); + } +}); + +/** + * TODO: add property description. + * @type {Stream} + */ +Object.defineProperty(exports, 'Stream', { + configurable: true, + enumerable: true, + get() { + return require('./stream'); + } +}); diff --git a/build/node_modules/winston/lib/winston/transports/stream.js b/build/node_modules/winston/lib/winston/transports/stream.js new file mode 100644 index 00000000..378520a3 --- /dev/null +++ b/build/node_modules/winston/lib/winston/transports/stream.js @@ -0,0 +1,63 @@ +/** + * stream.js: Transport for outputting to any arbitrary stream. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + */ + +'use strict'; + +const isStream = require('is-stream'); +const { MESSAGE } = require('triple-beam'); +const os = require('os'); +const TransportStream = require('winston-transport'); + +/** + * Transport for outputting to any arbitrary stream. + * @type {Stream} + * @extends {TransportStream} + */ +module.exports = class Stream extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + + if (!options.stream || !isStream(options.stream)) { + throw new Error('options.stream is required.'); + } + + // We need to listen for drain events when write() returns false. This can + // make node mad at times. + this._stream = options.stream; + this._stream.setMaxListeners(Infinity); + this.isObjectMode = options.stream._writableState.objectMode; + this.eol = options.eol || os.EOL; + } + + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit('logged', info)); + if (this.isObjectMode) { + this._stream.write(info); + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } + + this._stream.write(`${info[MESSAGE]}${this.eol}`); + if (callback) { + callback(); // eslint-disable-line callback-return + } + return; + } +}; diff --git a/build/node_modules/winston/node_modules/readable-stream/CONTRIBUTING.md b/build/node_modules/winston/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 00000000..f478d58d --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/build/node_modules/winston/node_modules/readable-stream/GOVERNANCE.md b/build/node_modules/winston/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 00000000..16ffb93f --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/build/node_modules/winston/node_modules/readable-stream/LICENSE b/build/node_modules/winston/node_modules/readable-stream/LICENSE new file mode 100644 index 00000000..2873b3b2 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" diff --git a/build/node_modules/winston/node_modules/readable-stream/README.md b/build/node_modules/winston/node_modules/readable-stream/README.md new file mode 100644 index 00000000..6f035ab1 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/build/node_modules/winston/node_modules/readable-stream/errors-browser.js b/build/node_modules/winston/node_modules/readable-stream/errors-browser.js new file mode 100644 index 00000000..fb8e73e1 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/build/node_modules/winston/node_modules/readable-stream/errors.js b/build/node_modules/winston/node_modules/readable-stream/errors.js new file mode 100644 index 00000000..8471526d --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/build/node_modules/winston/node_modules/readable-stream/experimentalWarning.js b/build/node_modules/winston/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 00000000..78e84149 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/_stream_duplex.js b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 00000000..67525192 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,139 @@ +// 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. +'use strict'; +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = require('./_stream_readable'); + +var Writable = require('./_stream_writable'); + +require('inherits')(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + 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); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer + +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(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; + } +}); \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/_stream_passthrough.js b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 00000000..32e7414c --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,39 @@ +// 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 passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +require('inherits')(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/_stream_readable.js b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 00000000..192d4514 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1124 @@ +// 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. +'use strict'; + +module.exports = Readable; +/**/ + +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; +/**/ + +var EE = require('events').EventEmitter; + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = require('util'); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +var BufferList = require('./internal/streams/buffer_list'); + +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; + +require('inherits')(Readable, Stream); + +var errorOrDestroy = destroyImpl.errorOrDestroy; +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); // 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 (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // 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 (isDuplex) 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" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // 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; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // 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 = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); // 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', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(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) { + 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) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, 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) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } 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; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // 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. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } 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 ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. + + +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB + + +var MAX_HWM = 0x40000000; + +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + 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.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || 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 = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + 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) { + debug('onEofChunk'); + 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; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + 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; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + 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; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + 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) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; + +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) process.nextTick(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(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // 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', state.awaitDrain); + state.awaitDrain++; + } + + 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) errorOrDestroy(dest, 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 pipeOnDrainFunctionResult() { + 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, { + hasUnpiped: false + }); + } + + 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); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; + +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +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'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + 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 (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + 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 _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.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 = _this.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 methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + + return createReadableStreamAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); // exposed for testing purposes only. + +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); // 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.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} + +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + + return from(Readable, iterable, opts); + }; +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; +} \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/_stream_transform.js b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 00000000..41a738c4 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,201 @@ +// 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. +'use strict'; + +module.exports = Transform; + +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + +var Duplex = require('./_stream_duplex'); + +require('inherits')(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // 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.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +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) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +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.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) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 00000000..a2634d7c --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,697 @@ +// 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. +'use strict'; + +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 Duplex; +/**/ + +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').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 = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +var errorOrDestroy = destroyImpl.errorOrDestroy; + +require('inherits')(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) 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() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // 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; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // 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 writableStateBufferGetter() { + 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 value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); // 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. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // 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 () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy(stream, er); + process.nextTick(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 er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + 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.ending) 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 () { + this._writableState.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !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 ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // 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 (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else 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 + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, 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; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + 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) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(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); + } + + state.bufferedRequestCount = 0; + } 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; + state.bufferedRequestCount--; // 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.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +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) endWritable(this, state, cb); + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +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) { + errorOrDestroy(stream, 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.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(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'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(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; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(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) { + cb(err); +}; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 00000000..9fb615a2 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,207 @@ +'use strict'; + +var _Object$setPrototypeO; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var finished = require('./end-of-stream'); + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); + +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; + +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 00000000..cdea425f --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,210 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('buffer'), + Buffer = _require.Buffer; + +var _require2 = require('util'), + inspect = _require2.inspect; + +var custom = inspect && inspect.custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: 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; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: 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; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: 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; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + 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; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.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) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.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) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; +}(); \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/destroy.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 00000000..3268a16f --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,105 @@ +'use strict'; // 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) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // 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) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; +} + +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} + +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} + +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.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 00000000..831f286d --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,104 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; +} + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from-browser.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 00000000..a4ce56f3 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 00000000..6c412844 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,64 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; + +function from(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; +} + +module.exports = from; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/pipeline.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 00000000..65899098 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,97 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/state.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 00000000..19887eb8 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,27 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 00000000..9332a3fd --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream.js b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 00000000..ce2ad5b6 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/build/node_modules/winston/node_modules/readable-stream/package.json b/build/node_modules/winston/node_modules/readable-stream/package.json new file mode 100644 index 00000000..0f15d305 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/package.json @@ -0,0 +1,97 @@ +{ + "_from": "readable-stream@^3.4.0", + "_id": "readable-stream@3.6.0", + "_inBundle": false, + "_integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "_location": "/winston/readable-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "readable-stream@^3.4.0", + "name": "readable-stream", + "escapedName": "readable-stream", + "rawSpec": "^3.4.0", + "saveSpec": null, + "fetchSpec": "^3.4.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "_shasum": "337bbda3adc0706bd3e024426a286d4b4b2c9198", + "_spec": "readable-stream@^3.4.0", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build/node_modules/winston", + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "bugs": { + "url": "https://github.com/nodejs/readable-stream/issues" + }, + "bundleDependencies": false, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "deprecated": false, + "description": "Streams3, a user-land copy of the stream library from Node.js", + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "engines": { + "node": ">= 6" + }, + "homepage": "https://github.com/nodejs/readable-stream#readme", + "keywords": [ + "readable", + "stream", + "pipe" + ], + "license": "MIT", + "main": "readable.js", + "name": "readable-stream", + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream.git" + }, + "scripts": { + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "version": "3.6.0" +} diff --git a/build/node_modules/winston/node_modules/readable-stream/readable-browser.js b/build/node_modules/winston/node_modules/readable-stream/readable-browser.js new file mode 100644 index 00000000..adbf60de --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/build/node_modules/winston/node_modules/readable-stream/readable.js b/build/node_modules/winston/node_modules/readable-stream/readable.js new file mode 100644 index 00000000..9e0ca120 --- /dev/null +++ b/build/node_modules/winston/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/build/node_modules/winston/package.json b/build/node_modules/winston/package.json new file mode 100644 index 00000000..be9a660a --- /dev/null +++ b/build/node_modules/winston/package.json @@ -0,0 +1,118 @@ +{ + "_from": "winston@^3.3.3", + "_id": "winston@3.3.3", + "_inBundle": false, + "_integrity": "sha512-oEXTISQnC8VlSAKf1KYSSd7J6IWuRPQqDdo8eoRNaYKLvwSb5+79Z3Yi1lrl6KDpU6/VWaxpakDAtb1oQ4n9aw==", + "_location": "/winston", + "_phantomChildren": { + "inherits": "2.0.4", + "string_decoder": "1.1.1", + "util-deprecate": "1.0.2" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "winston@^3.3.3", + "name": "winston", + "escapedName": "winston", + "rawSpec": "^3.3.3", + "saveSpec": null, + "fetchSpec": "^3.3.3" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/winston/-/winston-3.3.3.tgz", + "_shasum": "ae6172042cafb29786afa3d09c8ff833ab7c9170", + "_spec": "winston@^3.3.3", + "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "browser": "./dist/winston", + "bugs": { + "url": "https://github.com/winstonjs/winston/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@dabh/diagnostics": "^2.0.2", + "async": "^3.1.0", + "is-stream": "^2.0.0", + "logform": "^2.2.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.4.0" + }, + "deprecated": false, + "description": "A logger for just about everything.", + "devDependencies": { + "@babel/cli": "^7.10.3", + "@babel/core": "^7.10.3", + "@babel/preset-env": "^7.10.3", + "@types/node": "^14.0.13", + "abstract-winston-transport": "^0.5.1", + "assume": "^2.2.0", + "colors": "^1.4.0", + "cross-spawn-async": "^2.2.5", + "eslint-config-populist": "^4.2.0", + "hock": "^1.4.1", + "mocha": "^8.0.1", + "nyc": "^15.1.0", + "rimraf": "^3.0.2", + "split2": "^3.1.1", + "std-mocks": "^1.0.1", + "through2": "^3.0.1", + "winston-compat": "^0.1.5" + }, + "engines": { + "node": ">= 6.4.0" + }, + "homepage": "https://github.com/winstonjs/winston#readme", + "keywords": [ + "winston", + "logger", + "logging", + "logs", + "sysadmin", + "bunyan", + "pino", + "loglevel", + "tools", + "json", + "stream" + ], + "license": "MIT", + "main": "./lib/winston", + "maintainers": [ + { + "name": "Jarrett Cruger", + "email": "jcrugzz@gmail.com" + }, + { + "name": "Chris Alderson", + "email": "chrisalderson@protonmail.com" + }, + { + "name": "David Hyde", + "email": "dabh@stanford.edu" + } + ], + "name": "winston", + "repository": { + "type": "git", + "url": "git+https://github.com/winstonjs/winston.git" + }, + "scripts": { + "build": "rimraf dist && babel lib -d dist", + "lint": "populist lib/*.js lib/winston/*.js lib/winston/**/*.js", + "prepublishOnly": "npm run build", + "pretest": "npm run lint", + "test": "nyc --reporter=text --reporter lcov npm run test:mocha", + "test:mocha": "mocha test/*.test.js test/**/*.test.js --exit" + }, + "types": "./index.d.ts", + "version": "3.3.3" +} diff --git a/build/package-lock.json b/build/package-lock.json index f9316135..0fba82a2 100644 --- a/build/package-lock.json +++ b/build/package-lock.json @@ -1,9 +1,19 @@ { "name": "purecloud-guest-chat-client", - "version": "7.1.0", + "version": "7.2.0", "lockfileVersion": 1, "requires": true, "dependencies": { + "@dabh/diagnostics": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.2.tgz", + "integrity": "sha512-+A1YivoVDNNVCdfozHSR8v/jyuuLTMXwjWuxPFlFlUapXoGc+Gj9mDlTDDfrwl7rXCl2tNZ0kE8sIBO6YOn96Q==", + "requires": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + } + }, "abstract-leveldown": { "version": "0.12.4", "resolved": "https://registry.npmjs.org/abstract-leveldown/-/abstract-leveldown-0.12.4.tgz", @@ -53,6 +63,11 @@ } } }, + "async": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.0.tgz", + "integrity": "sha512-TR2mEZFVOj2pLStYxLht7TyfuRzaydfpxr3k9RpHIzMgw7A64dzsdqCxH1WJyQdoe8T10nDXd9wnEigmiuHIZw==" + }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -257,6 +272,51 @@ "integrity": "sha1-YT+2hjmyaklKxTJT4Vsaa9iK2oU=", "dev": true }, + "color": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/color/-/color-3.0.0.tgz", + "integrity": "sha512-jCpd5+s0s0t7p3pHQKpnJ0TpQKKdleP71LWcA0aqiljpiuAkOSUFN/dyH8ZwF0hRmFlrIuRhufds1QyEP9EB+w==", + "requires": { + "color-convert": "^1.9.1", + "color-string": "^1.5.2" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "color-string": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.5.5.tgz", + "integrity": "sha512-jgIoum0OfQfq9Whcfc2z/VhCNcmQjWbey6qBX0vqt7YICflUmBCh9E9CiQD5GSJ+Uehixm3NUwHVhqUAWRivZg==", + "requires": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==" + }, + "colorspace": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.2.tgz", + "integrity": "sha512-vt+OoIP2d76xLhjwbBaucYlNSpPsrJWPlBTtwCpQKIu6/CSMutyzX93O/Do0qzpH3YoHEes8YEFXyZ797rEhzQ==", + "requires": { + "color": "3.0.x", + "text-hex": "1.0.x" + } + }, "combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -288,6 +348,14 @@ "typedarray": "^0.0.6" } }, + "configparser": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/configparser/-/configparser-0.3.9.tgz", + "integrity": "sha512-ZlHt4SyiCfcQmFkt+2OfUQG6PC4GLyXthfBHvCH9I4ZtDxqMaAkfeEP+bkgePWgO3869+dRMVIcjklwfZmPDjg==", + "requires": { + "mkdirp": "^0.5.1" + } + }, "cookiejar": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.2.tgz", @@ -459,6 +527,11 @@ } } }, + "enabled": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" + }, "errno": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", @@ -544,6 +617,21 @@ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, + "fast-safe-stringify": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz", + "integrity": "sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA==" + }, + "fecha": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.1.tgz", + "integrity": "sha512-MMMQ0ludy/nBs1/o0zVOiKTpG7qMbonKUzjJgQFEuvq6INZ1OraKPRAWkBq5vlKLOUMpmNYG1JoN3oDPUQ9m3Q==" + }, + "fn.name": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==" + }, "foreach": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", @@ -749,6 +837,11 @@ "call-bind": "^1.0.0" } }, + "is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" + }, "is-bigint": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.2.tgz", @@ -825,6 +918,11 @@ "has-symbols": "^1.0.2" } }, + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==" + }, "is-string": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.6.tgz", @@ -888,6 +986,11 @@ } } }, + "kuler": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==" + }, "level-blobs": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/level-blobs/-/level-blobs-0.1.7.tgz", @@ -1083,6 +1186,18 @@ } } }, + "logform": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/logform/-/logform-2.2.0.tgz", + "integrity": "sha512-N0qPlqfypFx7UHNn4B3lzS/b0uLqt2hmuoa+PpuXNYgozdJYAyauF5Ky0BWVjrxDlMWiT3qN4zPq3vVAfZy7Yg==", + "requires": { + "colors": "^1.2.1", + "fast-safe-stringify": "^2.0.4", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "triple-beam": "^1.3.0" + } + }, "lolex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/lolex/-/lolex-1.3.2.tgz", @@ -1185,18 +1300,16 @@ } }, "minimist": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" }, "mkdirp": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", - "integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", - "dev": true, + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", "requires": { - "minimist": "0.0.8" + "minimist": "^1.2.5" } }, "mocha": { @@ -1225,6 +1338,21 @@ "ms": "0.7.1" } }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", + "integrity": "sha1-HXMHam35hs2TROFecfzAWkyavxI=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, "ms": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", @@ -1289,6 +1417,14 @@ "wrappy": "1" } }, + "one-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "requires": { + "fn.name": "1.x.x" + } + }, "parse-asn1": { "version": "5.1.6", "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", @@ -1575,6 +1711,14 @@ "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", "dev": true }, + "simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=", + "requires": { + "is-arrayish": "^0.3.1" + } + }, "sinon": { "version": "1.17.3", "resolved": "https://registry.npmjs.org/sinon/-/sinon-1.17.3.tgz", @@ -1593,6 +1737,11 @@ "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", "dev": true }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=" + }, "string-range": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/string-range/-/string-range-1.2.2.tgz", @@ -1650,6 +1799,16 @@ "integrity": "sha1-/x7R5hFp0Gs88tWI4YixjYhH4X4=", "dev": true }, + "text-hex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==" + }, + "triple-beam": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.3.0.tgz", + "integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==" + }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", @@ -1727,6 +1886,43 @@ "is-typed-array": "^1.1.3" } }, + "winston": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.3.3.tgz", + "integrity": "sha512-oEXTISQnC8VlSAKf1KYSSd7J6IWuRPQqDdo8eoRNaYKLvwSb5+79Z3Yi1lrl6KDpU6/VWaxpakDAtb1oQ4n9aw==", + "requires": { + "@dabh/diagnostics": "^2.0.2", + "async": "^3.1.0", + "is-stream": "^2.0.0", + "logform": "^2.2.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.4.0" + }, + "dependencies": { + "readable-stream": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + } + } + }, + "winston-transport": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.4.0.tgz", + "integrity": "sha512-Lc7/p3GtqtqPBYYtS6KCN3c77/2QCev51DvcJKbkFPQNoj1sinkGwLGFDxkXY9J6p9+EPnYs+D90uwbnaiURTw==", + "requires": { + "readable-stream": "^2.3.7", + "triple-beam": "^1.2.0" + } + }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/build/package.json b/build/package.json index ce077bc0..fac801ef 100644 --- a/build/package.json +++ b/build/package.json @@ -1,6 +1,6 @@ { "name": "purecloud-guest-chat-client", - "version": "7.1.0", + "version": "7.2.0", "description": "A JavaScript library to interface with the PureCloud Platform API", "license": "MIT", "main": "dist/node/purecloud-guest-chat-client.js", @@ -30,7 +30,9 @@ "url": "https://developer.mypurecloud.com" }, "dependencies": { - "superagent": "^3.8.3" + "configparser": "^0.3.9", + "superagent": "^3.8.3", + "winston": "^3.3.3" }, "devDependencies": { "mocha": "~2.3.4", diff --git a/build/src/purecloud-guest-chat-client/ApiClient.js b/build/src/purecloud-guest-chat-client/ApiClient.js index 5308508b..167a6f2a 100644 --- a/build/src/purecloud-guest-chat-client/ApiClient.js +++ b/build/src/purecloud-guest-chat-client/ApiClient.js @@ -1,8 +1,9 @@ import superagent from 'superagent'; +import Configuration from './configuration.js'; /** * @module purecloud-guest-chat-client/ApiClient - * @version 7.1.0 + * @version 7.2.0 */ class ApiClient { /** @@ -79,6 +80,11 @@ class ApiClient { this.hasLocalStorage = false; } + /** + * Create configuration instance for ApiClient and prepare logger. + */ + this.config = new Configuration(); + /** * The base URL against which to resolve every API call's (relative) path. * @type {String} @@ -118,16 +124,6 @@ class ApiClient { if (typeof(window) !== 'undefined') window.ApiClient = this; } - /** - * @description Sets the debug log to enable debug logging - * @param {log} debugLog - In most cases use `console.log` - * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0. - */ - setDebugLog(debugLog, maxLines) { - this.debugLog = debugLog; - this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined; - } - /** * @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned. * @param {boolean} returnExtended - `true` to return extended responses @@ -144,7 +140,6 @@ class ApiClient { setPersistSettings(doPersist, prefix) { this.persistSettings = doPersist; this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud'; - this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`); } /** @@ -169,7 +164,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.'); return; } @@ -179,7 +173,6 @@ class ApiClient { // Save updated auth data localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData)); - this._debugTrace('Auth data saved to local storage'); } catch (e) { console.error(e); } @@ -194,7 +187,6 @@ class ApiClient { // Ensure we can access local storage if (!this.hasLocalStorage) { - this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.'); return; } @@ -214,24 +206,7 @@ class ApiClient { * @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc. */ setEnvironment(environment) { - if (!environment) - environment = 'mypurecloud.com'; - - // Strip trailing slash - environment = environment.replace(/\/+$/, ''); - - // Strip protocol and subdomain - if (environment.startsWith('https://')) - environment = environment.substring(8); - if (environment.startsWith('http://')) - environment = environment.substring(7); - if (environment.startsWith('api.')) - environment = environment.substring(4); - - // Set vars - this.environment = environment; - this.basePath = `https://api.${environment}`; - this.authUrl = `https://login.${environment}`; + this.config.setEnvironment(environment); } /** @@ -288,7 +263,7 @@ class ApiClient { */ _buildAuthUrl(path, query) { if (!query) query = {}; - return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`); + return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`); } /** @@ -317,7 +292,7 @@ class ApiClient { if (!path.match(/^\//)) { path = `/${path}`; } - var url = this.basePath + path; + var url = this.config.basePath + path; url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => { var value; if (pathParams.hasOwnProperty(key)) { @@ -502,23 +477,6 @@ class ApiClient { request.proxy(this.proxy); } - if(this.debugLog){ - var trace = `[REQUEST] ${httpMethod} ${url}`; - if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){ - trace += `\nPath Params: ${JSON.stringify(pathParams)}`; - } - - if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){ - trace += `\nQuery Params: ${JSON.stringify(queryParams)}`; - } - - if(bodyParam){ - trace += `\nnBody: ${JSON.stringify(bodyParam)}`; - } - - this._debugTrace(trace); - } - // apply authentications this.applyAuthToRequest(request, authNames); @@ -527,7 +485,7 @@ class ApiClient { // set header parameters request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); - //request.set({ 'purecloud-sdk': '7.1.0' }); + //request.set({ 'purecloud-sdk': '7.2.0' }); // set request timeout request.timeout(this.timeout); @@ -589,23 +547,22 @@ class ApiClient { } : response.body ? response.body : response.text; // Debug logging - if (this.debugLog) { - var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`; - if (response.headers) - trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`; - if (response.body) - trace += `\nBody: ${JSON.stringify(response.body,null,2)}`; - - // Log trace message - this._debugTrace(trace); - - // Log stack trace - if (error) - this._debugTrace(error); - } + this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined); + this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined); // Resolve promise if (error) { + // Log error + this.config.logger.log( + 'error', + response.statusCode, + httpMethod, + url, + request.header, + response.headers, + bodyParam, + response.body + ); reject(data); } else { resolve(data); @@ -613,39 +570,6 @@ class ApiClient { }); }); } - - /** - * @description Parses an ISO-8601 string representation of a date value. - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - parseDate(str) { - return new Date(str.replace(/T/i, ' ')); - } - - /** - * @description Logs to the debug log - * @param {String} str The date value as a string. - * @returns {Date} The parsed date object. - */ - _debugTrace(trace) { - if (!this.debugLog) return; - - if (typeof(trace) === 'string') { - // Truncate - var truncTrace = ''; - var lines = trace.split('\n'); - if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) { - for (var i = 0; i < this.debugLogMaxLines; i++) { - truncTrace += `${lines[i]}\n`; - } - truncTrace += '...response truncated...'; - trace = truncTrace; - } - } - - this.debugLog(trace); - } } export default ApiClient; diff --git a/build/src/purecloud-guest-chat-client/api/WebChatApi.js b/build/src/purecloud-guest-chat-client/api/WebChatApi.js index ecf71939..94d8c720 100644 --- a/build/src/purecloud-guest-chat-client/api/WebChatApi.js +++ b/build/src/purecloud-guest-chat-client/api/WebChatApi.js @@ -5,7 +5,7 @@ class WebChatApi { /** * WebChat service. * @module purecloud-guest-chat-client/api/WebChatApi - * @version 7.1.0 + * @version 7.2.0 */ /** diff --git a/build/src/purecloud-guest-chat-client/configuration.js b/build/src/purecloud-guest-chat-client/configuration.js new file mode 100644 index 00000000..312a3152 --- /dev/null +++ b/build/src/purecloud-guest-chat-client/configuration.js @@ -0,0 +1,155 @@ +import Logger from './logger.js'; + +class Configuration { + /** + * Singleton getter + */ + get instance() { + return Configuration.instance; + } + + /** + * Singleton setter + */ + set instance(value) { + Configuration.instance = value; + } + + constructor() { + if (!Configuration.instance) { + Configuration.instance = this; + } + + if (typeof window !== 'undefined') { + this.configPath = ''; + } else { + const os = require('os'); + const path = require('path'); + this.configPath = path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config'); + } + + this.live_reload_config = true; + this.host; + this.environment; + this.basePath; + this.authUrl; + this.config; + this.logger = new Logger(); + this.setEnvironment(); + this.liveLoadConfig(); + } + + liveLoadConfig() { + // If in browser, don't read config file, use default values + if (typeof window !== 'undefined') { + this.configPath = ''; + return; + } + + this.updateConfigFromFile(); + + if (this.live_reload_config && this.live_reload_config === true) { + try { + const fs = require('fs'); + fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => { + this.updateConfigFromFile(); + if (!this.live_reload_config) { + fs.unwatchFile(this.configPath); + } + }); + } catch (err) { + // do nothing + } + } + } + + setConfigPath(path) { + if (path && path !== this.configPath) { + this.configPath = path; + this.liveLoadConfig(); + } + } + + updateConfigFromFile() { + const ConfigParser = require('configparser'); + var configparser = new ConfigParser(); + + try { + configparser.read(this.configPath); // If no error catched, indicates it's INI format + this.config = configparser; + } catch (error) { + if (error.name && error.name === 'MissingSectionHeaderError') { + // Not INI format, see if it's JSON format + const fs = require('fs'); + var configData = fs.readFileSync(this.configPath, 'utf8'); + this.config = { + _sections: JSON.parse(configData), // To match INI data format + }; + } + } + + if (this.config) this.updateConfigValues(); + } + + updateConfigValues() { + this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level')); + this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format')); + this.logger.log_to_console = + this.getConfigBoolean('logging', 'log_to_console') !== undefined + ? this.getConfigBoolean('logging', 'log_to_console') + : this.logger.log_to_console; + this.logger.log_file_path = + this.getConfigString('logging', 'log_file_path') !== undefined + ? this.getConfigString('logging', 'log_file_path') + : this.logger.log_file_path; + this.logger.log_response_body = + this.getConfigBoolean('logging', 'log_response_body') !== undefined + ? this.getConfigBoolean('logging', 'log_response_body') + : this.logger.log_response_body; + this.logger.log_request_body = + this.getConfigBoolean('logging', 'log_request_body') !== undefined + ? this.getConfigBoolean('logging', 'log_request_body') + : this.logger.log_request_body; + this.live_reload_config = + this.getConfigBoolean('general', 'live_reload_config') !== undefined + ? this.getConfigBoolean('general', 'live_reload_config') + : this.live_reload_config; + this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host; + + this.setEnvironment(); + + // Update logging configs + this.logger.setLogger(); + } + + setEnvironment(env) { + // Default value + if (env) this.environment = env; + else this.environment = this.host ? this.host : 'mypurecloud.com'; + + // Strip trailing slash + this.environment = this.environment.replace(/\/+$/, ''); + + // Strip protocol and subdomain + if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8); + if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7); + if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4); + + this.basePath = `https://api.${this.environment}`; + this.authUrl = `https://login.${this.environment}`; + } + + getConfigString(section, key) { + if (this.config._sections[section]) return this.config._sections[section][key]; + } + + getConfigBoolean(section, key) { + if (this.config._sections[section] && this.config._sections[section][key] !== undefined) { + if (typeof this.config._sections[section][key] === 'string') { + return this.config._sections[section][key] === 'true'; + } else return this.config._sections[section][key]; + } + } +} + +export default Configuration; diff --git a/build/src/purecloud-guest-chat-client/index.js b/build/src/purecloud-guest-chat-client/index.js index 1970a4bb..7feb1abf 100644 --- a/build/src/purecloud-guest-chat-client/index.js +++ b/build/src/purecloud-guest-chat-client/index.js @@ -32,7 +32,7 @@ import WebChatApi from './api/WebChatApi.js'; * *

* @module purecloud-guest-chat-client/index - * @version 7.1.0 + * @version 7.2.0 */ class platformClient { constructor() { diff --git a/build/src/purecloud-guest-chat-client/logger.js b/build/src/purecloud-guest-chat-client/logger.js new file mode 100644 index 00000000..91d6a83a --- /dev/null +++ b/build/src/purecloud-guest-chat-client/logger.js @@ -0,0 +1,198 @@ +const logLevels = { + levels: { + none: 0, + error: 1, + debug: 2, + trace: 3, + }, +}; + +const logLevelEnum = { + level: { + LNone: 'none', + LError: 'error', + LDebug: 'debug', + LTrace: 'trace', + }, +}; + +const logFormatEnum = { + formats: { + JSON: 'json', + TEXT: 'text', + }, +}; + +class Logger { + get logLevelEnum() { + return logLevelEnum; + } + + get logFormatEnum() { + return logFormatEnum; + } + + constructor() { + this.log_level = logLevelEnum.level.LNone; + this.log_format = logFormatEnum.formats.TEXT; + this.log_to_console = true; + this.log_file_path; + this.log_response_body = false; + this.log_request_body = false; + + this.setLogger(); + } + + setLogger() { + if(typeof window === 'undefined') { + const winston = require('winston'); + this.logger = winston.createLogger({ + levels: logLevels.levels, + level: this.log_level, + }); + if (this.log_file_path && this.log_file_path !== '') { + if (this.log_format === logFormatEnum.formats.JSON) { + this.logger.add(new winston.transports.File({ format: winston.format.json(), filename: this.log_file_path })); + } else { + this.logger.add( + new winston.transports.File({ + format: winston.format.combine( + winston.format((info) => { + info.level = info.level.toUpperCase(); + return info; + })(), + winston.format.simple() + ), + filename: this.log_file_path, + }) + ); + } + } + if (this.log_to_console) { + if (this.log_format === logFormatEnum.formats.JSON) { + this.logger.add(new winston.transports.Console({ format: winston.format.json() })); + } else { + this.logger.add( + new winston.transports.Console({ + format: winston.format.combine( + winston.format((info) => { + info.level = info.level.toUpperCase(); + return info; + })(), + winston.format.simple() + ), + }) + ); + } + } + } + } + + log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody); + if (typeof window !== 'undefined') { + var shouldLog = this.calculateLogLevel(level); + if (shouldLog > 0 && this.log_to_console === true) { + if(this.log_format === this.logFormatEnum.formats.JSON) { + console.log(content); + } else { + console.log(`${level.toUpperCase()}: ${content}`); + } + } + } else { + if (this.logger.transports.length > 0) this.logger.log(level, content); + } + } + + calculateLogLevel(level) { + switch (this.log_level) { + case this.logLevelEnum.level.LError: + if (level !== this.logLevelEnum.level.LError) { + return -1; + } + return 1; + case this.logLevelEnum.level.LDebug: + if (level === this.logLevelEnum.level.LTrace) { + return -1; + } + return 1; + case this.logLevelEnum.level.LTrace: + return 1; + default: + return -1; + } + } + + formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) { + var result; + if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]'; + if (!this.log_request_body) requestBody = undefined; + if (!this.log_response_body) responseBody = undefined; + if (this.log_format && this.log_format === logFormatEnum.formats.JSON) { + result = { + level: level, + date: new Date().toISOString(), + method: method, + url: decodeURIComponent(url), + correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '', + statusCode: statusCode, + }; + if (requestHeaders) result.requestHeaders = requestHeaders; + if (responseHeaders) result.responseHeaders = responseHeaders; + if (requestBody) result.requestBody = requestBody; + if (responseBody) result.responseBody = responseBody; + } else { + result = `${new Date().toISOString()} +=== REQUEST === +${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue( + 'Headers', + this.formatHeaderString(requestHeaders) + )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')} +=== RESPONSE === +${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue( + 'CorrelationId', + responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '' + )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`; + } + + return result; + } + + formatHeaderString(headers) { + var headerString = ''; + if (!headers) return headerString; + for (const [key, value] of Object.entries(headers)) { + headerString += `\n\t${key}: ${value}`; + } + return headerString; + } + + formatValue(key, value) { + if (!value || value === '' || value === '{}') return ''; + return `${key}: ${value}\n`; + } + + getLogLevel(level) { + switch (level) { + case 'error': + return logLevelEnum.level.LError; + case 'debug': + return logLevelEnum.level.LDebug; + case 'trace': + return logLevelEnum.level.LTrace; + default: + return logLevelEnum.level.LNone; + } + } + + getLogFormat(format) { + switch (format) { + case 'json': + return logFormatEnum.formats.JSON; + default: + return logFormatEnum.formats.TEXT; + } + } +} + +export default Logger; diff --git a/releaseNotes.md b/releaseNotes.md index 3e76be49..c6c099b1 100644 --- a/releaseNotes.md +++ b/releaseNotes.md @@ -1,7 +1,7 @@ Platform API version: 4658 -Reverting logging and configuration changes because of regression introduced. +Adding the configuration and logging changes back because the browser issues have been resolved. See https://developer.genesys.cloud/api/rest/client-libraries/ for more information # Major Changes (0 changes) diff --git a/version.json b/version.json index 904004a7..165eedad 100644 --- a/version.json +++ b/version.json @@ -1,9 +1,9 @@ { "major": 7, - "minor": 1, + "minor": 2, "point": 0, "prerelease": "", "apiVersion": 0, - "display": "7.1.0", - "displayFull": "7.1.0" + "display": "7.2.0", + "displayFull": "7.2.0" } \ No newline at end of file