+ * @private
+ */
+
+var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/; // eslint-disable-line no-control-regex
+
+/**
+ * Create an attachment Content-Disposition header.
+ *
+ * @param {string} [filename]
+ * @param {object} [options]
+ * @param {string} [options.type=attachment]
+ * @param {string|boolean} [options.fallback=true]
+ * @return {string}
+ * @public
+ */
+
+function contentDisposition$1 (filename, options) {
+ var opts = options || {};
+
+ // get type
+ var type = opts.type || 'attachment';
+
+ // get parameters
+ var params = createparams(filename, opts.fallback);
+
+ // format into string
+ return format$2(new ContentDisposition(type, params))
+}
+
+/**
+ * Create parameters object from filename and fallback.
+ *
+ * @param {string} [filename]
+ * @param {string|boolean} [fallback=true]
+ * @return {object}
+ * @private
+ */
+
+function createparams (filename, fallback) {
+ if (filename === undefined) {
+ return
+ }
+
+ var params = {};
+
+ if (typeof filename !== 'string') {
+ throw new TypeError('filename must be a string')
+ }
+
+ // fallback defaults to true
+ if (fallback === undefined) {
+ fallback = true;
+ }
+
+ if (typeof fallback !== 'string' && typeof fallback !== 'boolean') {
+ throw new TypeError('fallback must be a string or boolean')
+ }
+
+ if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) {
+ throw new TypeError('fallback must be ISO-8859-1 string')
+ }
+
+ // restrict to file base name
+ var name = basename(filename);
+
+ // determine if name is suitable for quoted string
+ var isQuotedString = TEXT_REGEXP.test(name);
+
+ // generate fallback name
+ var fallbackName = typeof fallback !== 'string'
+ ? fallback && getlatin1(name)
+ : basename(fallback);
+ var hasFallback = typeof fallbackName === 'string' && fallbackName !== name;
+
+ // set extended filename parameter
+ if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
+ params['filename*'] = name;
+ }
+
+ // set filename parameter
+ if (isQuotedString || hasFallback) {
+ params.filename = hasFallback
+ ? fallbackName
+ : name;
+ }
+
+ return params
+}
+
+/**
+ * Format object to Content-Disposition header.
+ *
+ * @param {object} obj
+ * @param {string} obj.type
+ * @param {object} [obj.parameters]
+ * @return {string}
+ * @private
+ */
+
+function format$2 (obj) {
+ var parameters = obj.parameters;
+ var type = obj.type;
+
+ if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) {
+ throw new TypeError('invalid type')
+ }
+
+ // start with normalized type
+ var string = String(type).toLowerCase();
+
+ // append parameters
+ if (parameters && typeof parameters === 'object') {
+ var param;
+ var params = Object.keys(parameters).sort();
+
+ for (var i = 0; i < params.length; i++) {
+ param = params[i];
+
+ var val = param.substr(-1) === '*'
+ ? ustring(parameters[param])
+ : qstring(parameters[param]);
+
+ string += '; ' + param + '=' + val;
+ }
+ }
+
+ return string
+}
+
+/**
+ * Decode a RFC 5987 field value (gracefully).
+ *
+ * @param {string} str
+ * @return {string}
+ * @private
+ */
+
+function decodefield (str) {
+ var match = EXT_VALUE_REGEXP.exec(str);
+
+ if (!match) {
+ throw new TypeError('invalid extended field value')
+ }
+
+ var charset = match[1].toLowerCase();
+ var encoded = match[2];
+ var value;
+
+ // to binary string
+ var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode);
+
+ switch (charset) {
+ case 'iso-8859-1':
+ value = getlatin1(binary);
+ break
+ case 'utf-8':
+ value = Buffer$2.from(binary, 'binary').toString('utf8');
+ break
+ default:
+ throw new TypeError('unsupported charset in extended field')
+ }
+
+ return value
+}
+
+/**
+ * Get ISO-8859-1 version of string.
+ *
+ * @param {string} val
+ * @return {string}
+ * @private
+ */
+
+function getlatin1 (val) {
+ // simple Unicode -> ISO-8859-1 transformation
+ return String(val).replace(NON_LATIN1_REGEXP, '?')
+}
+
+/**
+ * Parse Content-Disposition header string.
+ *
+ * @param {string} string
+ * @return {object}
+ * @public
+ */
+
+function parse$b (string) {
+ if (!string || typeof string !== 'string') {
+ throw new TypeError('argument string is required')
+ }
+
+ var match = DISPOSITION_TYPE_REGEXP.exec(string);
+
+ if (!match) {
+ throw new TypeError('invalid type format')
+ }
+
+ // normalize type
+ var index = match[0].length;
+ var type = match[1].toLowerCase();
+
+ var key;
+ var names = [];
+ var params = {};
+ var value;
+
+ // calculate index to start at
+ index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';'
+ ? index - 1
+ : index;
+
+ // match parameters
+ while ((match = PARAM_REGEXP.exec(string))) {
+ if (match.index !== index) {
+ throw new TypeError('invalid parameter format')
+ }
+
+ index += match[0].length;
+ key = match[1].toLowerCase();
+ value = match[2];
+
+ if (names.indexOf(key) !== -1) {
+ throw new TypeError('invalid duplicate parameter')
+ }
+
+ names.push(key);
+
+ if (key.indexOf('*') + 1 === key.length) {
+ // decode extended value
+ key = key.slice(0, -1);
+ value = decodefield(value);
+
+ // overwrite existing value
+ params[key] = value;
+ continue
+ }
+
+ if (typeof params[key] === 'string') {
+ continue
+ }
+
+ if (value[0] === '"') {
+ // remove quotes and escapes
+ value = value
+ .substr(1, value.length - 2)
+ .replace(QESC_REGEXP, '$1');
+ }
+
+ params[key] = value;
+ }
+
+ if (index !== -1 && index !== string.length) {
+ throw new TypeError('invalid parameter format')
+ }
+
+ return new ContentDisposition(type, params)
+}
+
+/**
+ * Percent decode a single character.
+ *
+ * @param {string} str
+ * @param {string} hex
+ * @return {string}
+ * @private
+ */
+
+function pdecode (str, hex) {
+ return String.fromCharCode(parseInt(hex, 16))
+}
+
+/**
+ * Percent encode a single character.
+ *
+ * @param {string} char
+ * @return {string}
+ * @private
+ */
+
+function pencode (char) {
+ return '%' + String(char)
+ .charCodeAt(0)
+ .toString(16)
+ .toUpperCase()
+}
+
+/**
+ * Quote a string for HTTP.
+ *
+ * @param {string} val
+ * @return {string}
+ * @private
+ */
+
+function qstring (val) {
+ var str = String(val);
+
+ return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
+}
+
+/**
+ * Encode a Unicode string for HTTP (RFC 5987).
+ *
+ * @param {string} val
+ * @return {string}
+ * @private
+ */
+
+function ustring (val) {
+ var str = String(val);
+
+ // percent encode as UTF-8
+ var encoded = encodeURIComponent(str)
+ .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode);
+
+ return 'UTF-8\'\'' + encoded
+}
+
+/**
+ * Class for parsed Content-Disposition header for v8 optimization
+ *
+ * @public
+ * @param {string} type
+ * @param {object} parameters
+ * @constructor
+ */
+
+function ContentDisposition (type, parameters) {
+ this.type = type;
+ this.parameters = parameters;
+}
+
+var sendExports = {};
+var send$2 = {
+ get exports(){ return sendExports; },
+ set exports(v){ sendExports = v; },
+};
+
+var srcExports = {};
+var src$2 = {
+ get exports(){ return srcExports; },
+ set exports(v){ srcExports = v; },
+};
+
+var browserExports = {};
+var browser = {
+ get exports(){ return browserExports; },
+ set exports(v){ browserExports = v; },
+};
+
+var debugExports = {};
+var debug$3 = {
+ get exports(){ return debugExports; },
+ set exports(v){ debugExports = v; },
+};
+
+/**
+ * Helpers.
+ */
+
+var ms$2;
+var hasRequiredMs;
+
+function requireMs () {
+ if (hasRequiredMs) return ms$2;
+ hasRequiredMs = 1;
+ var s = 1000;
+ var m = s * 60;
+ var h = m * 60;
+ var d = h * 24;
+ var y = d * 365.25;
+
+ /**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+ ms$2 = function(val, options) {
+ options = options || {};
+ var type = typeof val;
+ if (type === 'string' && val.length > 0) {
+ return parse(val);
+ } else if (type === 'number' && isNaN(val) === false) {
+ return options.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ 'val is not a non-empty string or a valid number. val=' +
+ JSON.stringify(val)
+ );
+ };
+
+ /**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+ function parse(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+ default:
+ return undefined;
+ }
+ }
+
+ /**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+ function fmtShort(ms) {
+ if (ms >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+ if (ms >= h) {
+ return Math.round(ms / h) + 'h';
+ }
+ if (ms >= m) {
+ return Math.round(ms / m) + 'm';
+ }
+ if (ms >= s) {
+ return Math.round(ms / s) + 's';
+ }
+ return ms + 'ms';
+ }
+
+ /**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+ function fmtLong(ms) {
+ return plural(ms, d, 'day') ||
+ plural(ms, h, 'hour') ||
+ plural(ms, m, 'minute') ||
+ plural(ms, s, 'second') ||
+ ms + ' ms';
+ }
+
+ /**
+ * Pluralization helper.
+ */
+
+ function plural(ms, n, name) {
+ if (ms < n) {
+ return;
+ }
+ if (ms < n * 1.5) {
+ return Math.floor(ms / n) + ' ' + name;
+ }
+ return Math.ceil(ms / n) + ' ' + name + 's';
+ }
+ return ms$2;
+}
+
+var hasRequiredDebug$1;
+
+function requireDebug$1 () {
+ if (hasRequiredDebug$1) return debugExports;
+ hasRequiredDebug$1 = 1;
+ (function (module, exports) {
+ /**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
+ exports.coerce = coerce;
+ exports.disable = disable;
+ exports.enable = enable;
+ exports.enabled = enabled;
+ exports.humanize = requireMs();
+
+ /**
+ * The currently active debug mode names, and names to skip.
+ */
+
+ exports.names = [];
+ exports.skips = [];
+
+ /**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
+
+ exports.formatters = {};
+
+ /**
+ * Previous log timestamp.
+ */
+
+ var prevTime;
+
+ /**
+ * Select a color.
+ * @param {String} namespace
+ * @return {Number}
+ * @api private
+ */
+
+ function selectColor(namespace) {
+ var hash = 0, i;
+
+ for (i in namespace) {
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
+
+ return exports.colors[Math.abs(hash) % exports.colors.length];
+ }
+
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+
+ function createDebug(namespace) {
+
+ function debug() {
+ // disabled?
+ if (!debug.enabled) return;
+
+ var self = debug;
+
+ // set `diff` timestamp
+ var curr = +new Date();
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+
+ // turn the `arguments` into a proper Array
+ var args = new Array(arguments.length);
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i];
+ }
+
+ args[0] = exports.coerce(args[0]);
+
+ if ('string' !== typeof args[0]) {
+ // anything else let's inspect with %O
+ args.unshift('%O');
+ }
+
+ // apply any `formatters` transformations
+ var index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
+ // if we encounter an escaped % then don't increase the array index
+ if (match === '%%') return match;
+ index++;
+ var formatter = exports.formatters[format];
+ if ('function' === typeof formatter) {
+ var val = args[index];
+ match = formatter.call(self, val);
+
+ // now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
+
+ // apply env-specific formatting (colors, etc.)
+ exports.formatArgs.call(self, args);
+
+ var logFn = debug.log || exports.log || console.log.bind(console);
+ logFn.apply(self, args);
+ }
+
+ debug.namespace = namespace;
+ debug.enabled = exports.enabled(namespace);
+ debug.useColors = exports.useColors();
+ debug.color = selectColor(namespace);
+
+ // env-specific initialization logic for debug instances
+ if ('function' === typeof exports.init) {
+ exports.init(debug);
+ }
+
+ return debug;
+ }
+
+ /**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+
+ function enable(namespaces) {
+ exports.save(namespaces);
+
+ exports.names = [];
+ exports.skips = [];
+
+ var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+ var len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ if (!split[i]) continue; // ignore empty strings
+ namespaces = split[i].replace(/\*/g, '.*?');
+ if (namespaces[0] === '-') {
+ exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
+ } else {
+ exports.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+ }
+
+ /**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+ function disable() {
+ exports.enable('');
+ }
+
+ /**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+ function enabled(name) {
+ var i, len;
+ for (i = 0, len = exports.skips.length; i < len; i++) {
+ if (exports.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (i = 0, len = exports.names.length; i < len; i++) {
+ if (exports.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+
+ function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+ }
+} (debug$3, debugExports));
+ return debugExports;
+}
+
+/**
+ * This is the web browser implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+var hasRequiredBrowser;
+
+function requireBrowser () {
+ if (hasRequiredBrowser) return browserExports;
+ hasRequiredBrowser = 1;
+ (function (module, exports) {
+ exports = module.exports = requireDebug$1();
+ exports.log = log;
+ exports.formatArgs = formatArgs;
+ exports.save = save;
+ exports.load = load;
+ exports.useColors = useColors;
+ exports.storage = 'undefined' != typeof chrome
+ && 'undefined' != typeof chrome.storage
+ ? chrome.storage.local
+ : localstorage();
+
+ /**
+ * Colors.
+ */
+
+ exports.colors = [
+ 'lightseagreen',
+ 'forestgreen',
+ 'goldenrod',
+ 'dodgerblue',
+ 'darkorchid',
+ 'crimson'
+ ];
+
+ /**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+
+ function useColors() {
+ // NB: In an Electron preload script, document will be defined but not fully
+ // initialized. Since we know we're in Chrome, we'll just detect this case
+ // explicitly
+ if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
+ return true;
+ }
+
+ // is webkit? http://stackoverflow.com/a/16459606/376773
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
+ // is firebug? http://stackoverflow.com/a/398120/376773
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
+ // is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
+ // double check webkit in userAgent just in case we are in a worker
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+ }
+
+ /**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+ exports.formatters.j = function(v) {
+ try {
+ return JSON.stringify(v);
+ } catch (err) {
+ return '[UnexpectedJSONParseError]: ' + err.message;
+ }
+ };
+
+
+ /**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
+
+ function formatArgs(args) {
+ var useColors = this.useColors;
+
+ args[0] = (useColors ? '%c' : '')
+ + this.namespace
+ + (useColors ? ' %c' : ' ')
+ + args[0]
+ + (useColors ? '%c ' : ' ')
+ + '+' + exports.humanize(this.diff);
+
+ if (!useColors) return;
+
+ var c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit');
+
+ // the final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ var index = 0;
+ var lastC = 0;
+ args[0].replace(/%[a-zA-Z%]/g, function(match) {
+ if ('%%' === match) return;
+ index++;
+ if ('%c' === match) {
+ // we only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
+
+ args.splice(lastC, 0, c);
+ }
+
+ /**
+ * Invokes `console.log()` when available.
+ * No-op when `console.log` is not a "function".
+ *
+ * @api public
+ */
+
+ function log() {
+ // this hackery is required for IE8/9, where
+ // the `console.log` function doesn't have 'apply'
+ return 'object' === typeof console
+ && console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
+ }
+
+ /**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+ function save(namespaces) {
+ try {
+ if (null == namespaces) {
+ exports.storage.removeItem('debug');
+ } else {
+ exports.storage.debug = namespaces;
+ }
+ } catch(e) {}
+ }
+
+ /**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+ function load() {
+ var r;
+ try {
+ r = exports.storage.debug;
+ } catch(e) {}
+
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
+ r = process.env.DEBUG;
+ }
+
+ return r;
+ }
+
+ /**
+ * Enable namespaces listed in `localStorage.debug` initially.
+ */
+
+ exports.enable(load());
+
+ /**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
+
+ function localstorage() {
+ try {
+ return window.localStorage;
+ } catch (e) {}
+ }
+} (browser, browserExports));
+ return browserExports;
+}
+
+var nodeExports$1 = {};
+var node$1 = {
+ get exports(){ return nodeExports$1; },
+ set exports(v){ nodeExports$1 = v; },
+};
+
+/**
+ * Module dependencies.
+ */
+
+var hasRequiredNode$1;
+
+function requireNode$1 () {
+ if (hasRequiredNode$1) return nodeExports$1;
+ hasRequiredNode$1 = 1;
+ (function (module, exports) {
+ var tty = require$$0$g;
+ var util = require$$1$7;
+
+ /**
+ * This is the Node.js implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+ exports = module.exports = requireDebug$1();
+ exports.init = init;
+ exports.log = log;
+ exports.formatArgs = formatArgs;
+ exports.save = save;
+ exports.load = load;
+ exports.useColors = useColors;
+
+ /**
+ * Colors.
+ */
+
+ exports.colors = [6, 2, 3, 4, 5, 1];
+
+ /**
+ * Build up the default `inspectOpts` object from the environment variables.
+ *
+ * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
+ */
+
+ exports.inspectOpts = Object.keys(process.env).filter(function (key) {
+ return /^debug_/i.test(key);
+ }).reduce(function (obj, key) {
+ // camel-case
+ var prop = key
+ .substring(6)
+ .toLowerCase()
+ .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
+
+ // coerce string value into JS value
+ var val = process.env[key];
+ if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
+ else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
+ else if (val === 'null') val = null;
+ else val = Number(val);
+
+ obj[prop] = val;
+ return obj;
+ }, {});
+
+ /**
+ * The file descriptor to write the `debug()` calls to.
+ * Set the `DEBUG_FD` env variable to override with another value. i.e.:
+ *
+ * $ DEBUG_FD=3 node script.js 3>debug.log
+ */
+
+ var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
+
+ if (1 !== fd && 2 !== fd) {
+ util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
+ }
+
+ var stream = 1 === fd ? process.stdout :
+ 2 === fd ? process.stderr :
+ createWritableStdioStream(fd);
+
+ /**
+ * Is stdout a TTY? Colored output is enabled when `true`.
+ */
+
+ function useColors() {
+ return 'colors' in exports.inspectOpts
+ ? Boolean(exports.inspectOpts.colors)
+ : tty.isatty(fd);
+ }
+
+ /**
+ * Map %o to `util.inspect()`, all on a single line.
+ */
+
+ exports.formatters.o = function(v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts)
+ .split('\n').map(function(str) {
+ return str.trim()
+ }).join(' ');
+ };
+
+ /**
+ * Map %o to `util.inspect()`, allowing multiple lines if needed.
+ */
+
+ exports.formatters.O = function(v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts);
+ };
+
+ /**
+ * Adds ANSI color escape codes if enabled.
+ *
+ * @api public
+ */
+
+ function formatArgs(args) {
+ var name = this.namespace;
+ var useColors = this.useColors;
+
+ if (useColors) {
+ var c = this.color;
+ var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
+
+ args[0] = prefix + args[0].split('\n').join('\n' + prefix);
+ args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
+ } else {
+ args[0] = new Date().toUTCString()
+ + ' ' + name + ' ' + args[0];
+ }
+ }
+
+ /**
+ * Invokes `util.format()` with the specified arguments and writes to `stream`.
+ */
+
+ function log() {
+ return stream.write(util.format.apply(util, arguments) + '\n');
+ }
+
+ /**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+ function save(namespaces) {
+ if (null == namespaces) {
+ // If you set a process.env field to null or undefined, it gets cast to the
+ // string 'null' or 'undefined'. Just delete instead.
+ delete process.env.DEBUG;
+ } else {
+ process.env.DEBUG = namespaces;
+ }
+ }
+
+ /**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+ function load() {
+ return process.env.DEBUG;
+ }
+
+ /**
+ * Copied from `node/src/node.js`.
+ *
+ * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
+ * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
+ */
+
+ function createWritableStdioStream (fd) {
+ var stream;
+ var tty_wrap = process.binding('tty_wrap');
+
+ // Note stream._type is used for test-module-load-list.js
+
+ switch (tty_wrap.guessHandleType(fd)) {
+ case 'TTY':
+ stream = new tty.WriteStream(fd);
+ stream._type = 'tty';
+
+ // Hack to have stream not keep the event loop alive.
+ // See https://github.com/joyent/node/issues/1726
+ if (stream._handle && stream._handle.unref) {
+ stream._handle.unref();
+ }
+ break;
+
+ case 'FILE':
+ var fs = require$$0$e;
+ stream = new fs.SyncWriteStream(fd, { autoClose: false });
+ stream._type = 'fs';
+ break;
+
+ case 'PIPE':
+ case 'TCP':
+ var net = require$$4$2;
+ stream = new net.Socket({
+ fd: fd,
+ readable: false,
+ writable: true
+ });
+
+ // FIXME Should probably have an option in net.Socket to create a
+ // stream from an existing fd which is writable only. But for now
+ // we'll just add this hack and set the `readable` member to false.
+ // Test: ./node test/fixtures/echo.js < /etc/passwd
+ stream.readable = false;
+ stream.read = null;
+ stream._type = 'pipe';
+
+ // FIXME Hack to have stream not keep the event loop alive.
+ // See https://github.com/joyent/node/issues/1726
+ if (stream._handle && stream._handle.unref) {
+ stream._handle.unref();
+ }
+ break;
+
+ default:
+ // Probably an error on in uv_guess_handle()
+ throw new Error('Implement me. Unknown stream file type!');
+ }
+
+ // For supporting legacy API we put the FD here.
+ stream.fd = fd;
+
+ stream._isStdio = true;
+
+ return stream;
+ }
+
+ /**
+ * Init logic for `debug` instances.
+ *
+ * Create a new `inspectOpts` object in case `useColors` is set
+ * differently for a particular `debug` instance.
+ */
+
+ function init (debug) {
+ debug.inspectOpts = {};
+
+ var keys = Object.keys(exports.inspectOpts);
+ for (var i = 0; i < keys.length; i++) {
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
+ }
+ }
+
+ /**
+ * Enable namespaces listed in `process.env.DEBUG` initially.
+ */
+
+ exports.enable(load());
+} (node$1, nodeExports$1));
+ return nodeExports$1;
+}
+
+/**
+ * Detect Electron renderer process, which is node, but we should
+ * treat as a browser.
+ */
+
+(function (module) {
+ if (typeof process !== 'undefined' && process.type === 'renderer') {
+ module.exports = requireBrowser();
+ } else {
+ module.exports = requireNode$1();
+ }
+} (src$2));
+
+/*!
+ * etag
+ * Copyright(c) 2014-2016 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var etag_1 = etag$1;
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var crypto$3 = require$$0$j;
+var Stats = require$$0$e.Stats;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var toString$5 = Object.prototype.toString;
+
+/**
+ * Generate an entity tag.
+ *
+ * @param {Buffer|string} entity
+ * @return {string}
+ * @private
+ */
+
+function entitytag (entity) {
+ if (entity.length === 0) {
+ // fast-path empty
+ return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
+ }
+
+ // compute hash of entity
+ var hash = crypto$3
+ .createHash('sha1')
+ .update(entity, 'utf8')
+ .digest('base64')
+ .substring(0, 27);
+
+ // compute length of entity
+ var len = typeof entity === 'string'
+ ? Buffer.byteLength(entity, 'utf8')
+ : entity.length;
+
+ return '"' + len.toString(16) + '-' + hash + '"'
+}
+
+/**
+ * Create a simple ETag.
+ *
+ * @param {string|Buffer|Stats} entity
+ * @param {object} [options]
+ * @param {boolean} [options.weak]
+ * @return {String}
+ * @public
+ */
+
+function etag$1 (entity, options) {
+ if (entity == null) {
+ throw new TypeError('argument entity is required')
+ }
+
+ // support fs.Stats object
+ var isStats = isstats(entity);
+ var weak = options && typeof options.weak === 'boolean'
+ ? options.weak
+ : isStats;
+
+ // validate argument
+ if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
+ throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
+ }
+
+ // generate entity tag
+ var tag = isStats
+ ? stattag(entity)
+ : entitytag(entity);
+
+ return weak
+ ? 'W/' + tag
+ : tag
+}
+
+/**
+ * Determine if object is a Stats object.
+ *
+ * @param {object} obj
+ * @return {boolean}
+ * @api private
+ */
+
+function isstats (obj) {
+ // genuine fs.Stats
+ if (typeof Stats === 'function' && obj instanceof Stats) {
+ return true
+ }
+
+ // quack quack
+ return obj && typeof obj === 'object' &&
+ 'ctime' in obj && toString$5.call(obj.ctime) === '[object Date]' &&
+ 'mtime' in obj && toString$5.call(obj.mtime) === '[object Date]' &&
+ 'ino' in obj && typeof obj.ino === 'number' &&
+ 'size' in obj && typeof obj.size === 'number'
+}
+
+/**
+ * Generate a tag for a stat.
+ *
+ * @param {object} stat
+ * @return {string}
+ * @private
+ */
+
+function stattag (stat) {
+ var mtime = stat.mtime.getTime().toString(16);
+ var size = stat.size.toString(16);
+
+ return '"' + size + '-' + mtime + '"'
+}
+
+/*!
+ * fresh
+ * Copyright(c) 2012 TJ Holowaychuk
+ * Copyright(c) 2016-2017 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * RegExp to check for no-cache token in Cache-Control.
+ * @private
+ */
+
+var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/;
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var fresh_1 = fresh$2;
+
+/**
+ * Check freshness of the response using request and response headers.
+ *
+ * @param {Object} reqHeaders
+ * @param {Object} resHeaders
+ * @return {Boolean}
+ * @public
+ */
+
+function fresh$2 (reqHeaders, resHeaders) {
+ // fields
+ var modifiedSince = reqHeaders['if-modified-since'];
+ var noneMatch = reqHeaders['if-none-match'];
+
+ // unconditional request
+ if (!modifiedSince && !noneMatch) {
+ return false
+ }
+
+ // Always return stale when Cache-Control: no-cache
+ // to support end-to-end reload requests
+ // https://tools.ietf.org/html/rfc2616#section-14.9.4
+ var cacheControl = reqHeaders['cache-control'];
+ if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
+ return false
+ }
+
+ // if-none-match
+ if (noneMatch && noneMatch !== '*') {
+ var etag = resHeaders['etag'];
+
+ if (!etag) {
+ return false
+ }
+
+ var etagStale = true;
+ var matches = parseTokenList$1(noneMatch);
+ for (var i = 0; i < matches.length; i++) {
+ var match = matches[i];
+ if (match === etag || match === 'W/' + etag || 'W/' + match === etag) {
+ etagStale = false;
+ break
+ }
+ }
+
+ if (etagStale) {
+ return false
+ }
+ }
+
+ // if-modified-since
+ if (modifiedSince) {
+ var lastModified = resHeaders['last-modified'];
+ var modifiedStale = !lastModified || !(parseHttpDate$1(lastModified) <= parseHttpDate$1(modifiedSince));
+
+ if (modifiedStale) {
+ return false
+ }
+ }
+
+ return true
+}
+
+/**
+ * Parse an HTTP Date into a number.
+ *
+ * @param {string} date
+ * @private
+ */
+
+function parseHttpDate$1 (date) {
+ var timestamp = date && Date.parse(date);
+
+ // istanbul ignore next: guard against date.js Date.parse patching
+ return typeof timestamp === 'number'
+ ? timestamp
+ : NaN
+}
+
+/**
+ * Parse a HTTP token list.
+ *
+ * @param {string} str
+ * @private
+ */
+
+function parseTokenList$1 (str) {
+ var end = 0;
+ var list = [];
+ var start = 0;
+
+ // gather tokens
+ for (var i = 0, len = str.length; i < len; i++) {
+ switch (str.charCodeAt(i)) {
+ case 0x20: /* */
+ if (start === end) {
+ start = end = i + 1;
+ }
+ break
+ case 0x2c: /* , */
+ list.push(str.substring(start, end));
+ start = end = i + 1;
+ break
+ default:
+ end = i + 1;
+ break
+ }
+ }
+
+ // final token
+ list.push(str.substring(start, end));
+
+ return list
+}
+
+var require$$2$2 = {
+ "application/andrew-inset": [
+ "ez"
+],
+ "application/applixware": [
+ "aw"
+],
+ "application/atom+xml": [
+ "atom"
+],
+ "application/atomcat+xml": [
+ "atomcat"
+],
+ "application/atomsvc+xml": [
+ "atomsvc"
+],
+ "application/bdoc": [
+ "bdoc"
+],
+ "application/ccxml+xml": [
+ "ccxml"
+],
+ "application/cdmi-capability": [
+ "cdmia"
+],
+ "application/cdmi-container": [
+ "cdmic"
+],
+ "application/cdmi-domain": [
+ "cdmid"
+],
+ "application/cdmi-object": [
+ "cdmio"
+],
+ "application/cdmi-queue": [
+ "cdmiq"
+],
+ "application/cu-seeme": [
+ "cu"
+],
+ "application/dash+xml": [
+ "mpd"
+],
+ "application/davmount+xml": [
+ "davmount"
+],
+ "application/docbook+xml": [
+ "dbk"
+],
+ "application/dssc+der": [
+ "dssc"
+],
+ "application/dssc+xml": [
+ "xdssc"
+],
+ "application/ecmascript": [
+ "ecma"
+],
+ "application/emma+xml": [
+ "emma"
+],
+ "application/epub+zip": [
+ "epub"
+],
+ "application/exi": [
+ "exi"
+],
+ "application/font-tdpfr": [
+ "pfr"
+],
+ "application/font-woff": [
+],
+ "application/font-woff2": [
+],
+ "application/geo+json": [
+ "geojson"
+],
+ "application/gml+xml": [
+ "gml"
+],
+ "application/gpx+xml": [
+ "gpx"
+],
+ "application/gxf": [
+ "gxf"
+],
+ "application/gzip": [
+ "gz"
+],
+ "application/hyperstudio": [
+ "stk"
+],
+ "application/inkml+xml": [
+ "ink",
+ "inkml"
+],
+ "application/ipfix": [
+ "ipfix"
+],
+ "application/java-archive": [
+ "jar",
+ "war",
+ "ear"
+],
+ "application/java-serialized-object": [
+ "ser"
+],
+ "application/java-vm": [
+ "class"
+],
+ "application/javascript": [
+ "js",
+ "mjs"
+],
+ "application/json": [
+ "json",
+ "map"
+],
+ "application/json5": [
+ "json5"
+],
+ "application/jsonml+json": [
+ "jsonml"
+],
+ "application/ld+json": [
+ "jsonld"
+],
+ "application/lost+xml": [
+ "lostxml"
+],
+ "application/mac-binhex40": [
+ "hqx"
+],
+ "application/mac-compactpro": [
+ "cpt"
+],
+ "application/mads+xml": [
+ "mads"
+],
+ "application/manifest+json": [
+ "webmanifest"
+],
+ "application/marc": [
+ "mrc"
+],
+ "application/marcxml+xml": [
+ "mrcx"
+],
+ "application/mathematica": [
+ "ma",
+ "nb",
+ "mb"
+],
+ "application/mathml+xml": [
+ "mathml"
+],
+ "application/mbox": [
+ "mbox"
+],
+ "application/mediaservercontrol+xml": [
+ "mscml"
+],
+ "application/metalink+xml": [
+ "metalink"
+],
+ "application/metalink4+xml": [
+ "meta4"
+],
+ "application/mets+xml": [
+ "mets"
+],
+ "application/mods+xml": [
+ "mods"
+],
+ "application/mp21": [
+ "m21",
+ "mp21"
+],
+ "application/mp4": [
+ "mp4s",
+ "m4p"
+],
+ "application/msword": [
+ "doc",
+ "dot"
+],
+ "application/mxf": [
+ "mxf"
+],
+ "application/octet-stream": [
+ "bin",
+ "dms",
+ "lrf",
+ "mar",
+ "so",
+ "dist",
+ "distz",
+ "pkg",
+ "bpk",
+ "dump",
+ "elc",
+ "deploy",
+ "exe",
+ "dll",
+ "deb",
+ "dmg",
+ "iso",
+ "img",
+ "msi",
+ "msp",
+ "msm",
+ "buffer"
+],
+ "application/oda": [
+ "oda"
+],
+ "application/oebps-package+xml": [
+ "opf"
+],
+ "application/ogg": [
+ "ogx"
+],
+ "application/omdoc+xml": [
+ "omdoc"
+],
+ "application/onenote": [
+ "onetoc",
+ "onetoc2",
+ "onetmp",
+ "onepkg"
+],
+ "application/oxps": [
+ "oxps"
+],
+ "application/patch-ops-error+xml": [
+ "xer"
+],
+ "application/pdf": [
+ "pdf"
+],
+ "application/pgp-encrypted": [
+ "pgp"
+],
+ "application/pgp-signature": [
+ "asc",
+ "sig"
+],
+ "application/pics-rules": [
+ "prf"
+],
+ "application/pkcs10": [
+ "p10"
+],
+ "application/pkcs7-mime": [
+ "p7m",
+ "p7c"
+],
+ "application/pkcs7-signature": [
+ "p7s"
+],
+ "application/pkcs8": [
+ "p8"
+],
+ "application/pkix-attr-cert": [
+ "ac"
+],
+ "application/pkix-cert": [
+ "cer"
+],
+ "application/pkix-crl": [
+ "crl"
+],
+ "application/pkix-pkipath": [
+ "pkipath"
+],
+ "application/pkixcmp": [
+ "pki"
+],
+ "application/pls+xml": [
+ "pls"
+],
+ "application/postscript": [
+ "ai",
+ "eps",
+ "ps"
+],
+ "application/prs.cww": [
+ "cww"
+],
+ "application/pskc+xml": [
+ "pskcxml"
+],
+ "application/raml+yaml": [
+ "raml"
+],
+ "application/rdf+xml": [
+ "rdf"
+],
+ "application/reginfo+xml": [
+ "rif"
+],
+ "application/relax-ng-compact-syntax": [
+ "rnc"
+],
+ "application/resource-lists+xml": [
+ "rl"
+],
+ "application/resource-lists-diff+xml": [
+ "rld"
+],
+ "application/rls-services+xml": [
+ "rs"
+],
+ "application/rpki-ghostbusters": [
+ "gbr"
+],
+ "application/rpki-manifest": [
+ "mft"
+],
+ "application/rpki-roa": [
+ "roa"
+],
+ "application/rsd+xml": [
+ "rsd"
+],
+ "application/rss+xml": [
+ "rss"
+],
+ "application/rtf": [
+ "rtf"
+],
+ "application/sbml+xml": [
+ "sbml"
+],
+ "application/scvp-cv-request": [
+ "scq"
+],
+ "application/scvp-cv-response": [
+ "scs"
+],
+ "application/scvp-vp-request": [
+ "spq"
+],
+ "application/scvp-vp-response": [
+ "spp"
+],
+ "application/sdp": [
+ "sdp"
+],
+ "application/set-payment-initiation": [
+ "setpay"
+],
+ "application/set-registration-initiation": [
+ "setreg"
+],
+ "application/shf+xml": [
+ "shf"
+],
+ "application/smil+xml": [
+ "smi",
+ "smil"
+],
+ "application/sparql-query": [
+ "rq"
+],
+ "application/sparql-results+xml": [
+ "srx"
+],
+ "application/srgs": [
+ "gram"
+],
+ "application/srgs+xml": [
+ "grxml"
+],
+ "application/sru+xml": [
+ "sru"
+],
+ "application/ssdl+xml": [
+ "ssdl"
+],
+ "application/ssml+xml": [
+ "ssml"
+],
+ "application/tei+xml": [
+ "tei",
+ "teicorpus"
+],
+ "application/thraud+xml": [
+ "tfi"
+],
+ "application/timestamped-data": [
+ "tsd"
+],
+ "application/vnd.3gpp.pic-bw-large": [
+ "plb"
+],
+ "application/vnd.3gpp.pic-bw-small": [
+ "psb"
+],
+ "application/vnd.3gpp.pic-bw-var": [
+ "pvb"
+],
+ "application/vnd.3gpp2.tcap": [
+ "tcap"
+],
+ "application/vnd.3m.post-it-notes": [
+ "pwn"
+],
+ "application/vnd.accpac.simply.aso": [
+ "aso"
+],
+ "application/vnd.accpac.simply.imp": [
+ "imp"
+],
+ "application/vnd.acucobol": [
+ "acu"
+],
+ "application/vnd.acucorp": [
+ "atc",
+ "acutc"
+],
+ "application/vnd.adobe.air-application-installer-package+zip": [
+ "air"
+],
+ "application/vnd.adobe.formscentral.fcdt": [
+ "fcdt"
+],
+ "application/vnd.adobe.fxp": [
+ "fxp",
+ "fxpl"
+],
+ "application/vnd.adobe.xdp+xml": [
+ "xdp"
+],
+ "application/vnd.adobe.xfdf": [
+ "xfdf"
+],
+ "application/vnd.ahead.space": [
+ "ahead"
+],
+ "application/vnd.airzip.filesecure.azf": [
+ "azf"
+],
+ "application/vnd.airzip.filesecure.azs": [
+ "azs"
+],
+ "application/vnd.amazon.ebook": [
+ "azw"
+],
+ "application/vnd.americandynamics.acc": [
+ "acc"
+],
+ "application/vnd.amiga.ami": [
+ "ami"
+],
+ "application/vnd.android.package-archive": [
+ "apk"
+],
+ "application/vnd.anser-web-certificate-issue-initiation": [
+ "cii"
+],
+ "application/vnd.anser-web-funds-transfer-initiation": [
+ "fti"
+],
+ "application/vnd.antix.game-component": [
+ "atx"
+],
+ "application/vnd.apple.installer+xml": [
+ "mpkg"
+],
+ "application/vnd.apple.mpegurl": [
+ "m3u8"
+],
+ "application/vnd.apple.pkpass": [
+ "pkpass"
+],
+ "application/vnd.aristanetworks.swi": [
+ "swi"
+],
+ "application/vnd.astraea-software.iota": [
+ "iota"
+],
+ "application/vnd.audiograph": [
+ "aep"
+],
+ "application/vnd.blueice.multipass": [
+ "mpm"
+],
+ "application/vnd.bmi": [
+ "bmi"
+],
+ "application/vnd.businessobjects": [
+ "rep"
+],
+ "application/vnd.chemdraw+xml": [
+ "cdxml"
+],
+ "application/vnd.chipnuts.karaoke-mmd": [
+ "mmd"
+],
+ "application/vnd.cinderella": [
+ "cdy"
+],
+ "application/vnd.claymore": [
+ "cla"
+],
+ "application/vnd.cloanto.rp9": [
+ "rp9"
+],
+ "application/vnd.clonk.c4group": [
+ "c4g",
+ "c4d",
+ "c4f",
+ "c4p",
+ "c4u"
+],
+ "application/vnd.cluetrust.cartomobile-config": [
+ "c11amc"
+],
+ "application/vnd.cluetrust.cartomobile-config-pkg": [
+ "c11amz"
+],
+ "application/vnd.commonspace": [
+ "csp"
+],
+ "application/vnd.contact.cmsg": [
+ "cdbcmsg"
+],
+ "application/vnd.cosmocaller": [
+ "cmc"
+],
+ "application/vnd.crick.clicker": [
+ "clkx"
+],
+ "application/vnd.crick.clicker.keyboard": [
+ "clkk"
+],
+ "application/vnd.crick.clicker.palette": [
+ "clkp"
+],
+ "application/vnd.crick.clicker.template": [
+ "clkt"
+],
+ "application/vnd.crick.clicker.wordbank": [
+ "clkw"
+],
+ "application/vnd.criticaltools.wbs+xml": [
+ "wbs"
+],
+ "application/vnd.ctc-posml": [
+ "pml"
+],
+ "application/vnd.cups-ppd": [
+ "ppd"
+],
+ "application/vnd.curl.car": [
+ "car"
+],
+ "application/vnd.curl.pcurl": [
+ "pcurl"
+],
+ "application/vnd.dart": [
+ "dart"
+],
+ "application/vnd.data-vision.rdz": [
+ "rdz"
+],
+ "application/vnd.dece.data": [
+ "uvf",
+ "uvvf",
+ "uvd",
+ "uvvd"
+],
+ "application/vnd.dece.ttml+xml": [
+ "uvt",
+ "uvvt"
+],
+ "application/vnd.dece.unspecified": [
+ "uvx",
+ "uvvx"
+],
+ "application/vnd.dece.zip": [
+ "uvz",
+ "uvvz"
+],
+ "application/vnd.denovo.fcselayout-link": [
+ "fe_launch"
+],
+ "application/vnd.dna": [
+ "dna"
+],
+ "application/vnd.dolby.mlp": [
+ "mlp"
+],
+ "application/vnd.dpgraph": [
+ "dpg"
+],
+ "application/vnd.dreamfactory": [
+ "dfac"
+],
+ "application/vnd.ds-keypoint": [
+ "kpxx"
+],
+ "application/vnd.dvb.ait": [
+ "ait"
+],
+ "application/vnd.dvb.service": [
+ "svc"
+],
+ "application/vnd.dynageo": [
+ "geo"
+],
+ "application/vnd.ecowin.chart": [
+ "mag"
+],
+ "application/vnd.enliven": [
+ "nml"
+],
+ "application/vnd.epson.esf": [
+ "esf"
+],
+ "application/vnd.epson.msf": [
+ "msf"
+],
+ "application/vnd.epson.quickanime": [
+ "qam"
+],
+ "application/vnd.epson.salt": [
+ "slt"
+],
+ "application/vnd.epson.ssf": [
+ "ssf"
+],
+ "application/vnd.eszigno3+xml": [
+ "es3",
+ "et3"
+],
+ "application/vnd.ezpix-album": [
+ "ez2"
+],
+ "application/vnd.ezpix-package": [
+ "ez3"
+],
+ "application/vnd.fdf": [
+ "fdf"
+],
+ "application/vnd.fdsn.mseed": [
+ "mseed"
+],
+ "application/vnd.fdsn.seed": [
+ "seed",
+ "dataless"
+],
+ "application/vnd.flographit": [
+ "gph"
+],
+ "application/vnd.fluxtime.clip": [
+ "ftc"
+],
+ "application/vnd.framemaker": [
+ "fm",
+ "frame",
+ "maker",
+ "book"
+],
+ "application/vnd.frogans.fnc": [
+ "fnc"
+],
+ "application/vnd.frogans.ltf": [
+ "ltf"
+],
+ "application/vnd.fsc.weblaunch": [
+ "fsc"
+],
+ "application/vnd.fujitsu.oasys": [
+ "oas"
+],
+ "application/vnd.fujitsu.oasys2": [
+ "oa2"
+],
+ "application/vnd.fujitsu.oasys3": [
+ "oa3"
+],
+ "application/vnd.fujitsu.oasysgp": [
+ "fg5"
+],
+ "application/vnd.fujitsu.oasysprs": [
+ "bh2"
+],
+ "application/vnd.fujixerox.ddd": [
+ "ddd"
+],
+ "application/vnd.fujixerox.docuworks": [
+ "xdw"
+],
+ "application/vnd.fujixerox.docuworks.binder": [
+ "xbd"
+],
+ "application/vnd.fuzzysheet": [
+ "fzs"
+],
+ "application/vnd.genomatix.tuxedo": [
+ "txd"
+],
+ "application/vnd.geogebra.file": [
+ "ggb"
+],
+ "application/vnd.geogebra.tool": [
+ "ggt"
+],
+ "application/vnd.geometry-explorer": [
+ "gex",
+ "gre"
+],
+ "application/vnd.geonext": [
+ "gxt"
+],
+ "application/vnd.geoplan": [
+ "g2w"
+],
+ "application/vnd.geospace": [
+ "g3w"
+],
+ "application/vnd.gmx": [
+ "gmx"
+],
+ "application/vnd.google-apps.document": [
+ "gdoc"
+],
+ "application/vnd.google-apps.presentation": [
+ "gslides"
+],
+ "application/vnd.google-apps.spreadsheet": [
+ "gsheet"
+],
+ "application/vnd.google-earth.kml+xml": [
+ "kml"
+],
+ "application/vnd.google-earth.kmz": [
+ "kmz"
+],
+ "application/vnd.grafeq": [
+ "gqf",
+ "gqs"
+],
+ "application/vnd.groove-account": [
+ "gac"
+],
+ "application/vnd.groove-help": [
+ "ghf"
+],
+ "application/vnd.groove-identity-message": [
+ "gim"
+],
+ "application/vnd.groove-injector": [
+ "grv"
+],
+ "application/vnd.groove-tool-message": [
+ "gtm"
+],
+ "application/vnd.groove-tool-template": [
+ "tpl"
+],
+ "application/vnd.groove-vcard": [
+ "vcg"
+],
+ "application/vnd.hal+xml": [
+ "hal"
+],
+ "application/vnd.handheld-entertainment+xml": [
+ "zmm"
+],
+ "application/vnd.hbci": [
+ "hbci"
+],
+ "application/vnd.hhe.lesson-player": [
+ "les"
+],
+ "application/vnd.hp-hpgl": [
+ "hpgl"
+],
+ "application/vnd.hp-hpid": [
+ "hpid"
+],
+ "application/vnd.hp-hps": [
+ "hps"
+],
+ "application/vnd.hp-jlyt": [
+ "jlt"
+],
+ "application/vnd.hp-pcl": [
+ "pcl"
+],
+ "application/vnd.hp-pclxl": [
+ "pclxl"
+],
+ "application/vnd.hydrostatix.sof-data": [
+ "sfd-hdstx"
+],
+ "application/vnd.ibm.minipay": [
+ "mpy"
+],
+ "application/vnd.ibm.modcap": [
+ "afp",
+ "listafp",
+ "list3820"
+],
+ "application/vnd.ibm.rights-management": [
+ "irm"
+],
+ "application/vnd.ibm.secure-container": [
+ "sc"
+],
+ "application/vnd.iccprofile": [
+ "icc",
+ "icm"
+],
+ "application/vnd.igloader": [
+ "igl"
+],
+ "application/vnd.immervision-ivp": [
+ "ivp"
+],
+ "application/vnd.immervision-ivu": [
+ "ivu"
+],
+ "application/vnd.insors.igm": [
+ "igm"
+],
+ "application/vnd.intercon.formnet": [
+ "xpw",
+ "xpx"
+],
+ "application/vnd.intergeo": [
+ "i2g"
+],
+ "application/vnd.intu.qbo": [
+ "qbo"
+],
+ "application/vnd.intu.qfx": [
+ "qfx"
+],
+ "application/vnd.ipunplugged.rcprofile": [
+ "rcprofile"
+],
+ "application/vnd.irepository.package+xml": [
+ "irp"
+],
+ "application/vnd.is-xpr": [
+ "xpr"
+],
+ "application/vnd.isac.fcs": [
+ "fcs"
+],
+ "application/vnd.jam": [
+ "jam"
+],
+ "application/vnd.jcp.javame.midlet-rms": [
+ "rms"
+],
+ "application/vnd.jisp": [
+ "jisp"
+],
+ "application/vnd.joost.joda-archive": [
+ "joda"
+],
+ "application/vnd.kahootz": [
+ "ktz",
+ "ktr"
+],
+ "application/vnd.kde.karbon": [
+ "karbon"
+],
+ "application/vnd.kde.kchart": [
+ "chrt"
+],
+ "application/vnd.kde.kformula": [
+ "kfo"
+],
+ "application/vnd.kde.kivio": [
+ "flw"
+],
+ "application/vnd.kde.kontour": [
+ "kon"
+],
+ "application/vnd.kde.kpresenter": [
+ "kpr",
+ "kpt"
+],
+ "application/vnd.kde.kspread": [
+ "ksp"
+],
+ "application/vnd.kde.kword": [
+ "kwd",
+ "kwt"
+],
+ "application/vnd.kenameaapp": [
+ "htke"
+],
+ "application/vnd.kidspiration": [
+ "kia"
+],
+ "application/vnd.kinar": [
+ "kne",
+ "knp"
+],
+ "application/vnd.koan": [
+ "skp",
+ "skd",
+ "skt",
+ "skm"
+],
+ "application/vnd.kodak-descriptor": [
+ "sse"
+],
+ "application/vnd.las.las+xml": [
+ "lasxml"
+],
+ "application/vnd.llamagraphics.life-balance.desktop": [
+ "lbd"
+],
+ "application/vnd.llamagraphics.life-balance.exchange+xml": [
+ "lbe"
+],
+ "application/vnd.lotus-1-2-3": [
+ "123"
+],
+ "application/vnd.lotus-approach": [
+ "apr"
+],
+ "application/vnd.lotus-freelance": [
+ "pre"
+],
+ "application/vnd.lotus-notes": [
+ "nsf"
+],
+ "application/vnd.lotus-organizer": [
+ "org"
+],
+ "application/vnd.lotus-screencam": [
+ "scm"
+],
+ "application/vnd.lotus-wordpro": [
+ "lwp"
+],
+ "application/vnd.macports.portpkg": [
+ "portpkg"
+],
+ "application/vnd.mcd": [
+ "mcd"
+],
+ "application/vnd.medcalcdata": [
+ "mc1"
+],
+ "application/vnd.mediastation.cdkey": [
+ "cdkey"
+],
+ "application/vnd.mfer": [
+ "mwf"
+],
+ "application/vnd.mfmp": [
+ "mfm"
+],
+ "application/vnd.micrografx.flo": [
+ "flo"
+],
+ "application/vnd.micrografx.igx": [
+ "igx"
+],
+ "application/vnd.mif": [
+ "mif"
+],
+ "application/vnd.mobius.daf": [
+ "daf"
+],
+ "application/vnd.mobius.dis": [
+ "dis"
+],
+ "application/vnd.mobius.mbk": [
+ "mbk"
+],
+ "application/vnd.mobius.mqy": [
+ "mqy"
+],
+ "application/vnd.mobius.msl": [
+ "msl"
+],
+ "application/vnd.mobius.plc": [
+ "plc"
+],
+ "application/vnd.mobius.txf": [
+ "txf"
+],
+ "application/vnd.mophun.application": [
+ "mpn"
+],
+ "application/vnd.mophun.certificate": [
+ "mpc"
+],
+ "application/vnd.mozilla.xul+xml": [
+ "xul"
+],
+ "application/vnd.ms-artgalry": [
+ "cil"
+],
+ "application/vnd.ms-cab-compressed": [
+ "cab"
+],
+ "application/vnd.ms-excel": [
+ "xls",
+ "xlm",
+ "xla",
+ "xlc",
+ "xlt",
+ "xlw"
+],
+ "application/vnd.ms-excel.addin.macroenabled.12": [
+ "xlam"
+],
+ "application/vnd.ms-excel.sheet.binary.macroenabled.12": [
+ "xlsb"
+],
+ "application/vnd.ms-excel.sheet.macroenabled.12": [
+ "xlsm"
+],
+ "application/vnd.ms-excel.template.macroenabled.12": [
+ "xltm"
+],
+ "application/vnd.ms-fontobject": [
+ "eot"
+],
+ "application/vnd.ms-htmlhelp": [
+ "chm"
+],
+ "application/vnd.ms-ims": [
+ "ims"
+],
+ "application/vnd.ms-lrm": [
+ "lrm"
+],
+ "application/vnd.ms-officetheme": [
+ "thmx"
+],
+ "application/vnd.ms-outlook": [
+ "msg"
+],
+ "application/vnd.ms-pki.seccat": [
+ "cat"
+],
+ "application/vnd.ms-pki.stl": [
+ "stl"
+],
+ "application/vnd.ms-powerpoint": [
+ "ppt",
+ "pps",
+ "pot"
+],
+ "application/vnd.ms-powerpoint.addin.macroenabled.12": [
+ "ppam"
+],
+ "application/vnd.ms-powerpoint.presentation.macroenabled.12": [
+ "pptm"
+],
+ "application/vnd.ms-powerpoint.slide.macroenabled.12": [
+ "sldm"
+],
+ "application/vnd.ms-powerpoint.slideshow.macroenabled.12": [
+ "ppsm"
+],
+ "application/vnd.ms-powerpoint.template.macroenabled.12": [
+ "potm"
+],
+ "application/vnd.ms-project": [
+ "mpp",
+ "mpt"
+],
+ "application/vnd.ms-word.document.macroenabled.12": [
+ "docm"
+],
+ "application/vnd.ms-word.template.macroenabled.12": [
+ "dotm"
+],
+ "application/vnd.ms-works": [
+ "wps",
+ "wks",
+ "wcm",
+ "wdb"
+],
+ "application/vnd.ms-wpl": [
+ "wpl"
+],
+ "application/vnd.ms-xpsdocument": [
+ "xps"
+],
+ "application/vnd.mseq": [
+ "mseq"
+],
+ "application/vnd.musician": [
+ "mus"
+],
+ "application/vnd.muvee.style": [
+ "msty"
+],
+ "application/vnd.mynfc": [
+ "taglet"
+],
+ "application/vnd.neurolanguage.nlu": [
+ "nlu"
+],
+ "application/vnd.nitf": [
+ "ntf",
+ "nitf"
+],
+ "application/vnd.noblenet-directory": [
+ "nnd"
+],
+ "application/vnd.noblenet-sealer": [
+ "nns"
+],
+ "application/vnd.noblenet-web": [
+ "nnw"
+],
+ "application/vnd.nokia.n-gage.data": [
+ "ngdat"
+],
+ "application/vnd.nokia.n-gage.symbian.install": [
+ "n-gage"
+],
+ "application/vnd.nokia.radio-preset": [
+ "rpst"
+],
+ "application/vnd.nokia.radio-presets": [
+ "rpss"
+],
+ "application/vnd.novadigm.edm": [
+ "edm"
+],
+ "application/vnd.novadigm.edx": [
+ "edx"
+],
+ "application/vnd.novadigm.ext": [
+ "ext"
+],
+ "application/vnd.oasis.opendocument.chart": [
+ "odc"
+],
+ "application/vnd.oasis.opendocument.chart-template": [
+ "otc"
+],
+ "application/vnd.oasis.opendocument.database": [
+ "odb"
+],
+ "application/vnd.oasis.opendocument.formula": [
+ "odf"
+],
+ "application/vnd.oasis.opendocument.formula-template": [
+ "odft"
+],
+ "application/vnd.oasis.opendocument.graphics": [
+ "odg"
+],
+ "application/vnd.oasis.opendocument.graphics-template": [
+ "otg"
+],
+ "application/vnd.oasis.opendocument.image": [
+ "odi"
+],
+ "application/vnd.oasis.opendocument.image-template": [
+ "oti"
+],
+ "application/vnd.oasis.opendocument.presentation": [
+ "odp"
+],
+ "application/vnd.oasis.opendocument.presentation-template": [
+ "otp"
+],
+ "application/vnd.oasis.opendocument.spreadsheet": [
+ "ods"
+],
+ "application/vnd.oasis.opendocument.spreadsheet-template": [
+ "ots"
+],
+ "application/vnd.oasis.opendocument.text": [
+ "odt"
+],
+ "application/vnd.oasis.opendocument.text-master": [
+ "odm"
+],
+ "application/vnd.oasis.opendocument.text-template": [
+ "ott"
+],
+ "application/vnd.oasis.opendocument.text-web": [
+ "oth"
+],
+ "application/vnd.olpc-sugar": [
+ "xo"
+],
+ "application/vnd.oma.dd2+xml": [
+ "dd2"
+],
+ "application/vnd.openofficeorg.extension": [
+ "oxt"
+],
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
+ "pptx"
+],
+ "application/vnd.openxmlformats-officedocument.presentationml.slide": [
+ "sldx"
+],
+ "application/vnd.openxmlformats-officedocument.presentationml.slideshow": [
+ "ppsx"
+],
+ "application/vnd.openxmlformats-officedocument.presentationml.template": [
+ "potx"
+],
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [
+ "xlsx"
+],
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.template": [
+ "xltx"
+],
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
+ "docx"
+],
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.template": [
+ "dotx"
+],
+ "application/vnd.osgeo.mapguide.package": [
+ "mgp"
+],
+ "application/vnd.osgi.dp": [
+ "dp"
+],
+ "application/vnd.osgi.subsystem": [
+ "esa"
+],
+ "application/vnd.palm": [
+ "pdb",
+ "pqa",
+ "oprc"
+],
+ "application/vnd.pawaafile": [
+ "paw"
+],
+ "application/vnd.pg.format": [
+ "str"
+],
+ "application/vnd.pg.osasli": [
+ "ei6"
+],
+ "application/vnd.picsel": [
+ "efif"
+],
+ "application/vnd.pmi.widget": [
+ "wg"
+],
+ "application/vnd.pocketlearn": [
+ "plf"
+],
+ "application/vnd.powerbuilder6": [
+ "pbd"
+],
+ "application/vnd.previewsystems.box": [
+ "box"
+],
+ "application/vnd.proteus.magazine": [
+ "mgz"
+],
+ "application/vnd.publishare-delta-tree": [
+ "qps"
+],
+ "application/vnd.pvi.ptid1": [
+ "ptid"
+],
+ "application/vnd.quark.quarkxpress": [
+ "qxd",
+ "qxt",
+ "qwd",
+ "qwt",
+ "qxl",
+ "qxb"
+],
+ "application/vnd.realvnc.bed": [
+ "bed"
+],
+ "application/vnd.recordare.musicxml": [
+ "mxl"
+],
+ "application/vnd.recordare.musicxml+xml": [
+ "musicxml"
+],
+ "application/vnd.rig.cryptonote": [
+ "cryptonote"
+],
+ "application/vnd.rim.cod": [
+ "cod"
+],
+ "application/vnd.rn-realmedia": [
+ "rm"
+],
+ "application/vnd.rn-realmedia-vbr": [
+ "rmvb"
+],
+ "application/vnd.route66.link66+xml": [
+ "link66"
+],
+ "application/vnd.sailingtracker.track": [
+ "st"
+],
+ "application/vnd.seemail": [
+ "see"
+],
+ "application/vnd.sema": [
+ "sema"
+],
+ "application/vnd.semd": [
+ "semd"
+],
+ "application/vnd.semf": [
+ "semf"
+],
+ "application/vnd.shana.informed.formdata": [
+ "ifm"
+],
+ "application/vnd.shana.informed.formtemplate": [
+ "itp"
+],
+ "application/vnd.shana.informed.interchange": [
+ "iif"
+],
+ "application/vnd.shana.informed.package": [
+ "ipk"
+],
+ "application/vnd.simtech-mindmapper": [
+ "twd",
+ "twds"
+],
+ "application/vnd.smaf": [
+ "mmf"
+],
+ "application/vnd.smart.teacher": [
+ "teacher"
+],
+ "application/vnd.solent.sdkm+xml": [
+ "sdkm",
+ "sdkd"
+],
+ "application/vnd.spotfire.dxp": [
+ "dxp"
+],
+ "application/vnd.spotfire.sfs": [
+ "sfs"
+],
+ "application/vnd.stardivision.calc": [
+ "sdc"
+],
+ "application/vnd.stardivision.draw": [
+ "sda"
+],
+ "application/vnd.stardivision.impress": [
+ "sdd"
+],
+ "application/vnd.stardivision.math": [
+ "smf"
+],
+ "application/vnd.stardivision.writer": [
+ "sdw",
+ "vor"
+],
+ "application/vnd.stardivision.writer-global": [
+ "sgl"
+],
+ "application/vnd.stepmania.package": [
+ "smzip"
+],
+ "application/vnd.stepmania.stepchart": [
+ "sm"
+],
+ "application/vnd.sun.wadl+xml": [
+ "wadl"
+],
+ "application/vnd.sun.xml.calc": [
+ "sxc"
+],
+ "application/vnd.sun.xml.calc.template": [
+ "stc"
+],
+ "application/vnd.sun.xml.draw": [
+ "sxd"
+],
+ "application/vnd.sun.xml.draw.template": [
+ "std"
+],
+ "application/vnd.sun.xml.impress": [
+ "sxi"
+],
+ "application/vnd.sun.xml.impress.template": [
+ "sti"
+],
+ "application/vnd.sun.xml.math": [
+ "sxm"
+],
+ "application/vnd.sun.xml.writer": [
+ "sxw"
+],
+ "application/vnd.sun.xml.writer.global": [
+ "sxg"
+],
+ "application/vnd.sun.xml.writer.template": [
+ "stw"
+],
+ "application/vnd.sus-calendar": [
+ "sus",
+ "susp"
+],
+ "application/vnd.svd": [
+ "svd"
+],
+ "application/vnd.symbian.install": [
+ "sis",
+ "sisx"
+],
+ "application/vnd.syncml+xml": [
+ "xsm"
+],
+ "application/vnd.syncml.dm+wbxml": [
+ "bdm"
+],
+ "application/vnd.syncml.dm+xml": [
+ "xdm"
+],
+ "application/vnd.tao.intent-module-archive": [
+ "tao"
+],
+ "application/vnd.tcpdump.pcap": [
+ "pcap",
+ "cap",
+ "dmp"
+],
+ "application/vnd.tmobile-livetv": [
+ "tmo"
+],
+ "application/vnd.trid.tpt": [
+ "tpt"
+],
+ "application/vnd.triscape.mxs": [
+ "mxs"
+],
+ "application/vnd.trueapp": [
+ "tra"
+],
+ "application/vnd.ufdl": [
+ "ufd",
+ "ufdl"
+],
+ "application/vnd.uiq.theme": [
+ "utz"
+],
+ "application/vnd.umajin": [
+ "umj"
+],
+ "application/vnd.unity": [
+ "unityweb"
+],
+ "application/vnd.uoml+xml": [
+ "uoml"
+],
+ "application/vnd.vcx": [
+ "vcx"
+],
+ "application/vnd.visio": [
+ "vsd",
+ "vst",
+ "vss",
+ "vsw"
+],
+ "application/vnd.visionary": [
+ "vis"
+],
+ "application/vnd.vsf": [
+ "vsf"
+],
+ "application/vnd.wap.wbxml": [
+ "wbxml"
+],
+ "application/vnd.wap.wmlc": [
+ "wmlc"
+],
+ "application/vnd.wap.wmlscriptc": [
+ "wmlsc"
+],
+ "application/vnd.webturbo": [
+ "wtb"
+],
+ "application/vnd.wolfram.player": [
+ "nbp"
+],
+ "application/vnd.wordperfect": [
+ "wpd"
+],
+ "application/vnd.wqd": [
+ "wqd"
+],
+ "application/vnd.wt.stf": [
+ "stf"
+],
+ "application/vnd.xara": [
+ "xar"
+],
+ "application/vnd.xfdl": [
+ "xfdl"
+],
+ "application/vnd.yamaha.hv-dic": [
+ "hvd"
+],
+ "application/vnd.yamaha.hv-script": [
+ "hvs"
+],
+ "application/vnd.yamaha.hv-voice": [
+ "hvp"
+],
+ "application/vnd.yamaha.openscoreformat": [
+ "osf"
+],
+ "application/vnd.yamaha.openscoreformat.osfpvg+xml": [
+ "osfpvg"
+],
+ "application/vnd.yamaha.smaf-audio": [
+ "saf"
+],
+ "application/vnd.yamaha.smaf-phrase": [
+ "spf"
+],
+ "application/vnd.yellowriver-custom-menu": [
+ "cmp"
+],
+ "application/vnd.zul": [
+ "zir",
+ "zirz"
+],
+ "application/vnd.zzazz.deck+xml": [
+ "zaz"
+],
+ "application/voicexml+xml": [
+ "vxml"
+],
+ "application/wasm": [
+ "wasm"
+],
+ "application/widget": [
+ "wgt"
+],
+ "application/winhlp": [
+ "hlp"
+],
+ "application/wsdl+xml": [
+ "wsdl"
+],
+ "application/wspolicy+xml": [
+ "wspolicy"
+],
+ "application/x-7z-compressed": [
+ "7z"
+],
+ "application/x-abiword": [
+ "abw"
+],
+ "application/x-ace-compressed": [
+ "ace"
+],
+ "application/x-apple-diskimage": [
+],
+ "application/x-arj": [
+ "arj"
+],
+ "application/x-authorware-bin": [
+ "aab",
+ "x32",
+ "u32",
+ "vox"
+],
+ "application/x-authorware-map": [
+ "aam"
+],
+ "application/x-authorware-seg": [
+ "aas"
+],
+ "application/x-bcpio": [
+ "bcpio"
+],
+ "application/x-bdoc": [
+],
+ "application/x-bittorrent": [
+ "torrent"
+],
+ "application/x-blorb": [
+ "blb",
+ "blorb"
+],
+ "application/x-bzip": [
+ "bz"
+],
+ "application/x-bzip2": [
+ "bz2",
+ "boz"
+],
+ "application/x-cbr": [
+ "cbr",
+ "cba",
+ "cbt",
+ "cbz",
+ "cb7"
+],
+ "application/x-cdlink": [
+ "vcd"
+],
+ "application/x-cfs-compressed": [
+ "cfs"
+],
+ "application/x-chat": [
+ "chat"
+],
+ "application/x-chess-pgn": [
+ "pgn"
+],
+ "application/x-chrome-extension": [
+ "crx"
+],
+ "application/x-cocoa": [
+ "cco"
+],
+ "application/x-conference": [
+ "nsc"
+],
+ "application/x-cpio": [
+ "cpio"
+],
+ "application/x-csh": [
+ "csh"
+],
+ "application/x-debian-package": [
+ "udeb"
+],
+ "application/x-dgc-compressed": [
+ "dgc"
+],
+ "application/x-director": [
+ "dir",
+ "dcr",
+ "dxr",
+ "cst",
+ "cct",
+ "cxt",
+ "w3d",
+ "fgd",
+ "swa"
+],
+ "application/x-doom": [
+ "wad"
+],
+ "application/x-dtbncx+xml": [
+ "ncx"
+],
+ "application/x-dtbook+xml": [
+ "dtb"
+],
+ "application/x-dtbresource+xml": [
+ "res"
+],
+ "application/x-dvi": [
+ "dvi"
+],
+ "application/x-envoy": [
+ "evy"
+],
+ "application/x-eva": [
+ "eva"
+],
+ "application/x-font-bdf": [
+ "bdf"
+],
+ "application/x-font-ghostscript": [
+ "gsf"
+],
+ "application/x-font-linux-psf": [
+ "psf"
+],
+ "application/x-font-pcf": [
+ "pcf"
+],
+ "application/x-font-snf": [
+ "snf"
+],
+ "application/x-font-type1": [
+ "pfa",
+ "pfb",
+ "pfm",
+ "afm"
+],
+ "application/x-freearc": [
+ "arc"
+],
+ "application/x-futuresplash": [
+ "spl"
+],
+ "application/x-gca-compressed": [
+ "gca"
+],
+ "application/x-glulx": [
+ "ulx"
+],
+ "application/x-gnumeric": [
+ "gnumeric"
+],
+ "application/x-gramps-xml": [
+ "gramps"
+],
+ "application/x-gtar": [
+ "gtar"
+],
+ "application/x-hdf": [
+ "hdf"
+],
+ "application/x-httpd-php": [
+ "php"
+],
+ "application/x-install-instructions": [
+ "install"
+],
+ "application/x-iso9660-image": [
+],
+ "application/x-java-archive-diff": [
+ "jardiff"
+],
+ "application/x-java-jnlp-file": [
+ "jnlp"
+],
+ "application/x-latex": [
+ "latex"
+],
+ "application/x-lua-bytecode": [
+ "luac"
+],
+ "application/x-lzh-compressed": [
+ "lzh",
+ "lha"
+],
+ "application/x-makeself": [
+ "run"
+],
+ "application/x-mie": [
+ "mie"
+],
+ "application/x-mobipocket-ebook": [
+ "prc",
+ "mobi"
+],
+ "application/x-ms-application": [
+ "application"
+],
+ "application/x-ms-shortcut": [
+ "lnk"
+],
+ "application/x-ms-wmd": [
+ "wmd"
+],
+ "application/x-ms-wmz": [
+ "wmz"
+],
+ "application/x-ms-xbap": [
+ "xbap"
+],
+ "application/x-msaccess": [
+ "mdb"
+],
+ "application/x-msbinder": [
+ "obd"
+],
+ "application/x-mscardfile": [
+ "crd"
+],
+ "application/x-msclip": [
+ "clp"
+],
+ "application/x-msdos-program": [
+],
+ "application/x-msdownload": [
+ "com",
+ "bat"
+],
+ "application/x-msmediaview": [
+ "mvb",
+ "m13",
+ "m14"
+],
+ "application/x-msmetafile": [
+ "wmf",
+ "emf",
+ "emz"
+],
+ "application/x-msmoney": [
+ "mny"
+],
+ "application/x-mspublisher": [
+ "pub"
+],
+ "application/x-msschedule": [
+ "scd"
+],
+ "application/x-msterminal": [
+ "trm"
+],
+ "application/x-mswrite": [
+ "wri"
+],
+ "application/x-netcdf": [
+ "nc",
+ "cdf"
+],
+ "application/x-ns-proxy-autoconfig": [
+ "pac"
+],
+ "application/x-nzb": [
+ "nzb"
+],
+ "application/x-perl": [
+ "pl",
+ "pm"
+],
+ "application/x-pilot": [
+],
+ "application/x-pkcs12": [
+ "p12",
+ "pfx"
+],
+ "application/x-pkcs7-certificates": [
+ "p7b",
+ "spc"
+],
+ "application/x-pkcs7-certreqresp": [
+ "p7r"
+],
+ "application/x-rar-compressed": [
+ "rar"
+],
+ "application/x-redhat-package-manager": [
+ "rpm"
+],
+ "application/x-research-info-systems": [
+ "ris"
+],
+ "application/x-sea": [
+ "sea"
+],
+ "application/x-sh": [
+ "sh"
+],
+ "application/x-shar": [
+ "shar"
+],
+ "application/x-shockwave-flash": [
+ "swf"
+],
+ "application/x-silverlight-app": [
+ "xap"
+],
+ "application/x-sql": [
+ "sql"
+],
+ "application/x-stuffit": [
+ "sit"
+],
+ "application/x-stuffitx": [
+ "sitx"
+],
+ "application/x-subrip": [
+ "srt"
+],
+ "application/x-sv4cpio": [
+ "sv4cpio"
+],
+ "application/x-sv4crc": [
+ "sv4crc"
+],
+ "application/x-t3vm-image": [
+ "t3"
+],
+ "application/x-tads": [
+ "gam"
+],
+ "application/x-tar": [
+ "tar"
+],
+ "application/x-tcl": [
+ "tcl",
+ "tk"
+],
+ "application/x-tex": [
+ "tex"
+],
+ "application/x-tex-tfm": [
+ "tfm"
+],
+ "application/x-texinfo": [
+ "texinfo",
+ "texi"
+],
+ "application/x-tgif": [
+ "obj"
+],
+ "application/x-ustar": [
+ "ustar"
+],
+ "application/x-virtualbox-hdd": [
+ "hdd"
+],
+ "application/x-virtualbox-ova": [
+ "ova"
+],
+ "application/x-virtualbox-ovf": [
+ "ovf"
+],
+ "application/x-virtualbox-vbox": [
+ "vbox"
+],
+ "application/x-virtualbox-vbox-extpack": [
+ "vbox-extpack"
+],
+ "application/x-virtualbox-vdi": [
+ "vdi"
+],
+ "application/x-virtualbox-vhd": [
+ "vhd"
+],
+ "application/x-virtualbox-vmdk": [
+ "vmdk"
+],
+ "application/x-wais-source": [
+ "src"
+],
+ "application/x-web-app-manifest+json": [
+ "webapp"
+],
+ "application/x-x509-ca-cert": [
+ "der",
+ "crt",
+ "pem"
+],
+ "application/x-xfig": [
+ "fig"
+],
+ "application/x-xliff+xml": [
+ "xlf"
+],
+ "application/x-xpinstall": [
+ "xpi"
+],
+ "application/x-xz": [
+ "xz"
+],
+ "application/x-zmachine": [
+ "z1",
+ "z2",
+ "z3",
+ "z4",
+ "z5",
+ "z6",
+ "z7",
+ "z8"
+],
+ "application/xaml+xml": [
+ "xaml"
+],
+ "application/xcap-diff+xml": [
+ "xdf"
+],
+ "application/xenc+xml": [
+ "xenc"
+],
+ "application/xhtml+xml": [
+ "xhtml",
+ "xht"
+],
+ "application/xml": [
+ "xml",
+ "xsl",
+ "xsd",
+ "rng"
+],
+ "application/xml-dtd": [
+ "dtd"
+],
+ "application/xop+xml": [
+ "xop"
+],
+ "application/xproc+xml": [
+ "xpl"
+],
+ "application/xslt+xml": [
+ "xslt"
+],
+ "application/xspf+xml": [
+ "xspf"
+],
+ "application/xv+xml": [
+ "mxml",
+ "xhvml",
+ "xvml",
+ "xvm"
+],
+ "application/yang": [
+ "yang"
+],
+ "application/yin+xml": [
+ "yin"
+],
+ "application/zip": [
+ "zip"
+],
+ "audio/3gpp": [
+],
+ "audio/adpcm": [
+ "adp"
+],
+ "audio/basic": [
+ "au",
+ "snd"
+],
+ "audio/midi": [
+ "mid",
+ "midi",
+ "kar",
+ "rmi"
+],
+ "audio/mp3": [
+],
+ "audio/mp4": [
+ "m4a",
+ "mp4a"
+],
+ "audio/mpeg": [
+ "mpga",
+ "mp2",
+ "mp2a",
+ "mp3",
+ "m2a",
+ "m3a"
+],
+ "audio/ogg": [
+ "oga",
+ "ogg",
+ "spx"
+],
+ "audio/s3m": [
+ "s3m"
+],
+ "audio/silk": [
+ "sil"
+],
+ "audio/vnd.dece.audio": [
+ "uva",
+ "uvva"
+],
+ "audio/vnd.digital-winds": [
+ "eol"
+],
+ "audio/vnd.dra": [
+ "dra"
+],
+ "audio/vnd.dts": [
+ "dts"
+],
+ "audio/vnd.dts.hd": [
+ "dtshd"
+],
+ "audio/vnd.lucent.voice": [
+ "lvp"
+],
+ "audio/vnd.ms-playready.media.pya": [
+ "pya"
+],
+ "audio/vnd.nuera.ecelp4800": [
+ "ecelp4800"
+],
+ "audio/vnd.nuera.ecelp7470": [
+ "ecelp7470"
+],
+ "audio/vnd.nuera.ecelp9600": [
+ "ecelp9600"
+],
+ "audio/vnd.rip": [
+ "rip"
+],
+ "audio/wav": [
+ "wav"
+],
+ "audio/wave": [
+],
+ "audio/webm": [
+ "weba"
+],
+ "audio/x-aac": [
+ "aac"
+],
+ "audio/x-aiff": [
+ "aif",
+ "aiff",
+ "aifc"
+],
+ "audio/x-caf": [
+ "caf"
+],
+ "audio/x-flac": [
+ "flac"
+],
+ "audio/x-m4a": [
+],
+ "audio/x-matroska": [
+ "mka"
+],
+ "audio/x-mpegurl": [
+ "m3u"
+],
+ "audio/x-ms-wax": [
+ "wax"
+],
+ "audio/x-ms-wma": [
+ "wma"
+],
+ "audio/x-pn-realaudio": [
+ "ram",
+ "ra"
+],
+ "audio/x-pn-realaudio-plugin": [
+ "rmp"
+],
+ "audio/x-realaudio": [
+],
+ "audio/x-wav": [
+],
+ "audio/xm": [
+ "xm"
+],
+ "chemical/x-cdx": [
+ "cdx"
+],
+ "chemical/x-cif": [
+ "cif"
+],
+ "chemical/x-cmdf": [
+ "cmdf"
+],
+ "chemical/x-cml": [
+ "cml"
+],
+ "chemical/x-csml": [
+ "csml"
+],
+ "chemical/x-xyz": [
+ "xyz"
+],
+ "font/collection": [
+ "ttc"
+],
+ "font/otf": [
+ "otf"
+],
+ "font/ttf": [
+ "ttf"
+],
+ "font/woff": [
+ "woff"
+],
+ "font/woff2": [
+ "woff2"
+],
+ "image/apng": [
+ "apng"
+],
+ "image/bmp": [
+ "bmp"
+],
+ "image/cgm": [
+ "cgm"
+],
+ "image/g3fax": [
+ "g3"
+],
+ "image/gif": [
+ "gif"
+],
+ "image/ief": [
+ "ief"
+],
+ "image/jp2": [
+ "jp2",
+ "jpg2"
+],
+ "image/jpeg": [
+ "jpeg",
+ "jpg",
+ "jpe"
+],
+ "image/jpm": [
+ "jpm"
+],
+ "image/jpx": [
+ "jpx",
+ "jpf"
+],
+ "image/ktx": [
+ "ktx"
+],
+ "image/png": [
+ "png"
+],
+ "image/prs.btif": [
+ "btif"
+],
+ "image/sgi": [
+ "sgi"
+],
+ "image/svg+xml": [
+ "svg",
+ "svgz"
+],
+ "image/tiff": [
+ "tiff",
+ "tif"
+],
+ "image/vnd.adobe.photoshop": [
+ "psd"
+],
+ "image/vnd.dece.graphic": [
+ "uvi",
+ "uvvi",
+ "uvg",
+ "uvvg"
+],
+ "image/vnd.djvu": [
+ "djvu",
+ "djv"
+],
+ "image/vnd.dvb.subtitle": [
+],
+ "image/vnd.dwg": [
+ "dwg"
+],
+ "image/vnd.dxf": [
+ "dxf"
+],
+ "image/vnd.fastbidsheet": [
+ "fbs"
+],
+ "image/vnd.fpx": [
+ "fpx"
+],
+ "image/vnd.fst": [
+ "fst"
+],
+ "image/vnd.fujixerox.edmics-mmr": [
+ "mmr"
+],
+ "image/vnd.fujixerox.edmics-rlc": [
+ "rlc"
+],
+ "image/vnd.ms-modi": [
+ "mdi"
+],
+ "image/vnd.ms-photo": [
+ "wdp"
+],
+ "image/vnd.net-fpx": [
+ "npx"
+],
+ "image/vnd.wap.wbmp": [
+ "wbmp"
+],
+ "image/vnd.xiff": [
+ "xif"
+],
+ "image/webp": [
+ "webp"
+],
+ "image/x-3ds": [
+ "3ds"
+],
+ "image/x-cmu-raster": [
+ "ras"
+],
+ "image/x-cmx": [
+ "cmx"
+],
+ "image/x-freehand": [
+ "fh",
+ "fhc",
+ "fh4",
+ "fh5",
+ "fh7"
+],
+ "image/x-icon": [
+ "ico"
+],
+ "image/x-jng": [
+ "jng"
+],
+ "image/x-mrsid-image": [
+ "sid"
+],
+ "image/x-ms-bmp": [
+],
+ "image/x-pcx": [
+ "pcx"
+],
+ "image/x-pict": [
+ "pic",
+ "pct"
+],
+ "image/x-portable-anymap": [
+ "pnm"
+],
+ "image/x-portable-bitmap": [
+ "pbm"
+],
+ "image/x-portable-graymap": [
+ "pgm"
+],
+ "image/x-portable-pixmap": [
+ "ppm"
+],
+ "image/x-rgb": [
+ "rgb"
+],
+ "image/x-tga": [
+ "tga"
+],
+ "image/x-xbitmap": [
+ "xbm"
+],
+ "image/x-xpixmap": [
+ "xpm"
+],
+ "image/x-xwindowdump": [
+ "xwd"
+],
+ "message/rfc822": [
+ "eml",
+ "mime"
+],
+ "model/gltf+json": [
+ "gltf"
+],
+ "model/gltf-binary": [
+ "glb"
+],
+ "model/iges": [
+ "igs",
+ "iges"
+],
+ "model/mesh": [
+ "msh",
+ "mesh",
+ "silo"
+],
+ "model/vnd.collada+xml": [
+ "dae"
+],
+ "model/vnd.dwf": [
+ "dwf"
+],
+ "model/vnd.gdl": [
+ "gdl"
+],
+ "model/vnd.gtw": [
+ "gtw"
+],
+ "model/vnd.mts": [
+ "mts"
+],
+ "model/vnd.vtu": [
+ "vtu"
+],
+ "model/vrml": [
+ "wrl",
+ "vrml"
+],
+ "model/x3d+binary": [
+ "x3db",
+ "x3dbz"
+],
+ "model/x3d+vrml": [
+ "x3dv",
+ "x3dvz"
+],
+ "model/x3d+xml": [
+ "x3d",
+ "x3dz"
+],
+ "text/cache-manifest": [
+ "appcache",
+ "manifest"
+],
+ "text/calendar": [
+ "ics",
+ "ifb"
+],
+ "text/coffeescript": [
+ "coffee",
+ "litcoffee"
+],
+ "text/css": [
+ "css"
+],
+ "text/csv": [
+ "csv"
+],
+ "text/hjson": [
+ "hjson"
+],
+ "text/html": [
+ "html",
+ "htm",
+ "shtml"
+],
+ "text/jade": [
+ "jade"
+],
+ "text/jsx": [
+ "jsx"
+],
+ "text/less": [
+ "less"
+],
+ "text/markdown": [
+ "markdown",
+ "md"
+],
+ "text/mathml": [
+ "mml"
+],
+ "text/n3": [
+ "n3"
+],
+ "text/plain": [
+ "txt",
+ "text",
+ "conf",
+ "def",
+ "list",
+ "log",
+ "in",
+ "ini"
+],
+ "text/prs.lines.tag": [
+ "dsc"
+],
+ "text/richtext": [
+ "rtx"
+],
+ "text/rtf": [
+],
+ "text/sgml": [
+ "sgml",
+ "sgm"
+],
+ "text/slim": [
+ "slim",
+ "slm"
+],
+ "text/stylus": [
+ "stylus",
+ "styl"
+],
+ "text/tab-separated-values": [
+ "tsv"
+],
+ "text/troff": [
+ "t",
+ "tr",
+ "roff",
+ "man",
+ "me",
+ "ms"
+],
+ "text/turtle": [
+ "ttl"
+],
+ "text/uri-list": [
+ "uri",
+ "uris",
+ "urls"
+],
+ "text/vcard": [
+ "vcard"
+],
+ "text/vnd.curl": [
+ "curl"
+],
+ "text/vnd.curl.dcurl": [
+ "dcurl"
+],
+ "text/vnd.curl.mcurl": [
+ "mcurl"
+],
+ "text/vnd.curl.scurl": [
+ "scurl"
+],
+ "text/vnd.dvb.subtitle": [
+ "sub"
+],
+ "text/vnd.fly": [
+ "fly"
+],
+ "text/vnd.fmi.flexstor": [
+ "flx"
+],
+ "text/vnd.graphviz": [
+ "gv"
+],
+ "text/vnd.in3d.3dml": [
+ "3dml"
+],
+ "text/vnd.in3d.spot": [
+ "spot"
+],
+ "text/vnd.sun.j2me.app-descriptor": [
+ "jad"
+],
+ "text/vnd.wap.wml": [
+ "wml"
+],
+ "text/vnd.wap.wmlscript": [
+ "wmls"
+],
+ "text/vtt": [
+ "vtt"
+],
+ "text/x-asm": [
+ "s",
+ "asm"
+],
+ "text/x-c": [
+ "c",
+ "cc",
+ "cxx",
+ "cpp",
+ "h",
+ "hh",
+ "dic"
+],
+ "text/x-component": [
+ "htc"
+],
+ "text/x-fortran": [
+ "f",
+ "for",
+ "f77",
+ "f90"
+],
+ "text/x-handlebars-template": [
+ "hbs"
+],
+ "text/x-java-source": [
+ "java"
+],
+ "text/x-lua": [
+ "lua"
+],
+ "text/x-markdown": [
+ "mkd"
+],
+ "text/x-nfo": [
+ "nfo"
+],
+ "text/x-opml": [
+ "opml"
+],
+ "text/x-org": [
+],
+ "text/x-pascal": [
+ "p",
+ "pas"
+],
+ "text/x-processing": [
+ "pde"
+],
+ "text/x-sass": [
+ "sass"
+],
+ "text/x-scss": [
+ "scss"
+],
+ "text/x-setext": [
+ "etx"
+],
+ "text/x-sfv": [
+ "sfv"
+],
+ "text/x-suse-ymp": [
+ "ymp"
+],
+ "text/x-uuencode": [
+ "uu"
+],
+ "text/x-vcalendar": [
+ "vcs"
+],
+ "text/x-vcard": [
+ "vcf"
+],
+ "text/xml": [
+],
+ "text/yaml": [
+ "yaml",
+ "yml"
+],
+ "video/3gpp": [
+ "3gp",
+ "3gpp"
+],
+ "video/3gpp2": [
+ "3g2"
+],
+ "video/h261": [
+ "h261"
+],
+ "video/h263": [
+ "h263"
+],
+ "video/h264": [
+ "h264"
+],
+ "video/jpeg": [
+ "jpgv"
+],
+ "video/jpm": [
+ "jpgm"
+],
+ "video/mj2": [
+ "mj2",
+ "mjp2"
+],
+ "video/mp2t": [
+ "ts"
+],
+ "video/mp4": [
+ "mp4",
+ "mp4v",
+ "mpg4"
+],
+ "video/mpeg": [
+ "mpeg",
+ "mpg",
+ "mpe",
+ "m1v",
+ "m2v"
+],
+ "video/ogg": [
+ "ogv"
+],
+ "video/quicktime": [
+ "qt",
+ "mov"
+],
+ "video/vnd.dece.hd": [
+ "uvh",
+ "uvvh"
+],
+ "video/vnd.dece.mobile": [
+ "uvm",
+ "uvvm"
+],
+ "video/vnd.dece.pd": [
+ "uvp",
+ "uvvp"
+],
+ "video/vnd.dece.sd": [
+ "uvs",
+ "uvvs"
+],
+ "video/vnd.dece.video": [
+ "uvv",
+ "uvvv"
+],
+ "video/vnd.dvb.file": [
+ "dvb"
+],
+ "video/vnd.fvt": [
+ "fvt"
+],
+ "video/vnd.mpegurl": [
+ "mxu",
+ "m4u"
+],
+ "video/vnd.ms-playready.media.pyv": [
+ "pyv"
+],
+ "video/vnd.uvvu.mp4": [
+ "uvu",
+ "uvvu"
+],
+ "video/vnd.vivo": [
+ "viv"
+],
+ "video/webm": [
+ "webm"
+],
+ "video/x-f4v": [
+ "f4v"
+],
+ "video/x-fli": [
+ "fli"
+],
+ "video/x-flv": [
+ "flv"
+],
+ "video/x-m4v": [
+ "m4v"
+],
+ "video/x-matroska": [
+ "mkv",
+ "mk3d",
+ "mks"
+],
+ "video/x-mng": [
+ "mng"
+],
+ "video/x-ms-asf": [
+ "asf",
+ "asx"
+],
+ "video/x-ms-vob": [
+ "vob"
+],
+ "video/x-ms-wm": [
+ "wm"
+],
+ "video/x-ms-wmv": [
+ "wmv"
+],
+ "video/x-ms-wmx": [
+ "wmx"
+],
+ "video/x-ms-wvx": [
+ "wvx"
+],
+ "video/x-msvideo": [
+ "avi"
+],
+ "video/x-sgi-movie": [
+ "movie"
+],
+ "video/x-smv": [
+ "smv"
+],
+ "x-conference/x-cooltalk": [
+ "ice"
+]
+};
+
+var fs$i = require$$0$e;
+
+function Mime() {
+ // Map of extension -> mime type
+ this.types = Object.create(null);
+
+ // Map of mime type -> extension
+ this.extensions = Object.create(null);
+}
+
+/**
+ * Define mimetype -> extension mappings. Each key is a mime-type that maps
+ * to an array of extensions associated with the type. The first extension is
+ * used as the default extension for the type.
+ *
+ * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
+ *
+ * @param map (Object) type definitions
+ */
+Mime.prototype.define = function (map) {
+ for (var type in map) {
+ var exts = map[type];
+ for (var i = 0; i < exts.length; i++) {
+ if (process.env.DEBUG_MIME && this.types[exts[i]]) {
+ console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
+ this.types[exts[i]] + ' to ' + type);
+ }
+
+ this.types[exts[i]] = type;
+ }
+
+ // Default extension is the first one we encounter
+ if (!this.extensions[type]) {
+ this.extensions[type] = exts[0];
+ }
+ }
+};
+
+/**
+ * Load an Apache2-style ".types" file
+ *
+ * This may be called multiple times (it's expected). Where files declare
+ * overlapping types/extensions, the last file wins.
+ *
+ * @param file (String) path of file to load.
+ */
+Mime.prototype.load = function(file) {
+ this._loading = file;
+ // Read file and split into lines
+ var map = {},
+ content = fs$i.readFileSync(file, 'ascii'),
+ lines = content.split(/[\r\n]+/);
+
+ lines.forEach(function(line) {
+ // Clean up whitespace/comments, and split into fields
+ var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
+ map[fields.shift()] = fields;
+ });
+
+ this.define(map);
+
+ this._loading = null;
+};
+
+/**
+ * Lookup a mime type based on extension
+ */
+Mime.prototype.lookup = function(path, fallback) {
+ var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase();
+
+ return this.types[ext] || fallback || this.default_type;
+};
+
+/**
+ * Return file extension associated with a mime type
+ */
+Mime.prototype.extension = function(mimeType) {
+ var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
+ return this.extensions[type];
+};
+
+// Default instance
+var mime$4 = new Mime();
+
+// Define built-in types
+mime$4.define(require$$2$2);
+
+// Default type
+mime$4.default_type = mime$4.lookup('bin');
+
+//
+// Additional API specific to the default instance
+//
+
+mime$4.Mime = Mime;
+
+/**
+ * Lookup a charset based on mime type.
+ */
+mime$4.charsets = {
+ lookup: function(mimeType, fallback) {
+ // Assume text types are utf8
+ return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback;
+ }
+};
+
+var mime_1 = mime$4;
+
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m$1 = s * 60;
+var h$1 = m$1 * 60;
+var d = h$1 * 24;
+var w = d * 7;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+var ms$1 = function (val, options) {
+ options = options || {};
+ var type = typeof val;
+ if (type === 'string' && val.length > 0) {
+ return parse$a(val);
+ } else if (type === 'number' && isFinite(val)) {
+ return options.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ 'val is not a non-empty string or a valid number. val=' +
+ JSON.stringify(val)
+ );
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse$a(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+ case 'weeks':
+ case 'week':
+ case 'w':
+ return n * w;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h$1;
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m$1;
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+ default:
+ return undefined;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtShort(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+ if (msAbs >= h$1) {
+ return Math.round(ms / h$1) + 'h';
+ }
+ if (msAbs >= m$1) {
+ return Math.round(ms / m$1) + 'm';
+ }
+ if (msAbs >= s) {
+ return Math.round(ms / s) + 's';
+ }
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtLong(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return plural(ms, msAbs, d, 'day');
+ }
+ if (msAbs >= h$1) {
+ return plural(ms, msAbs, h$1, 'hour');
+ }
+ if (msAbs >= m$1) {
+ return plural(ms, msAbs, m$1, 'minute');
+ }
+ if (msAbs >= s) {
+ return plural(ms, msAbs, s, 'second');
+ }
+ return ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+}
+
+/*!
+ * range-parser
+ * Copyright(c) 2012-2014 TJ Holowaychuk
+ * Copyright(c) 2015-2016 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var rangeParser_1 = rangeParser;
+
+/**
+ * Parse "Range" header `str` relative to the given file `size`.
+ *
+ * @param {Number} size
+ * @param {String} str
+ * @param {Object} [options]
+ * @return {Array}
+ * @public
+ */
+
+function rangeParser (size, str, options) {
+ if (typeof str !== 'string') {
+ throw new TypeError('argument str must be a string')
+ }
+
+ var index = str.indexOf('=');
+
+ if (index === -1) {
+ return -2
+ }
+
+ // split the range string
+ var arr = str.slice(index + 1).split(',');
+ var ranges = [];
+
+ // add ranges type
+ ranges.type = str.slice(0, index);
+
+ // parse all ranges
+ for (var i = 0; i < arr.length; i++) {
+ var range = arr[i].split('-');
+ var start = parseInt(range[0], 10);
+ var end = parseInt(range[1], 10);
+
+ // -nnn
+ if (isNaN(start)) {
+ start = size - end;
+ end = size - 1;
+ // nnn-
+ } else if (isNaN(end)) {
+ end = size - 1;
+ }
+
+ // limit last-byte-pos to current length
+ if (end > size - 1) {
+ end = size - 1;
+ }
+
+ // invalid or unsatisifiable
+ if (isNaN(start) || isNaN(end) || start > end || start < 0) {
+ continue
+ }
+
+ // add range
+ ranges.push({
+ start: start,
+ end: end
+ });
+ }
+
+ if (ranges.length < 1) {
+ // unsatisifiable
+ return -1
+ }
+
+ return options && options.combine
+ ? combineRanges(ranges)
+ : ranges
+}
+
+/**
+ * Combine overlapping & adjacent ranges.
+ * @private
+ */
+
+function combineRanges (ranges) {
+ var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart);
+
+ for (var j = 0, i = 1; i < ordered.length; i++) {
+ var range = ordered[i];
+ var current = ordered[j];
+
+ if (range.start > current.end + 1) {
+ // next range
+ ordered[++j] = range;
+ } else if (range.end > current.end) {
+ // extend range
+ current.end = range.end;
+ current.index = Math.min(current.index, range.index);
+ }
+ }
+
+ // trim ordered array
+ ordered.length = j + 1;
+
+ // generate combined range
+ var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex);
+
+ // copy ranges type
+ combined.type = ranges.type;
+
+ return combined
+}
+
+/**
+ * Map function to add index value to ranges.
+ * @private
+ */
+
+function mapWithIndex (range, index) {
+ return {
+ start: range.start,
+ end: range.end,
+ index: index
+ }
+}
+
+/**
+ * Map function to remove index value from ranges.
+ * @private
+ */
+
+function mapWithoutIndex (range) {
+ return {
+ start: range.start,
+ end: range.end
+ }
+}
+
+/**
+ * Sort function to sort ranges by index.
+ * @private
+ */
+
+function sortByRangeIndex (a, b) {
+ return a.index - b.index
+}
+
+/**
+ * Sort function to sort ranges by start position.
+ * @private
+ */
+
+function sortByRangeStart (a, b) {
+ return a.start - b.start
+}
+
+/*!
+ * send
+ * Copyright(c) 2012 TJ Holowaychuk
+ * Copyright(c) 2014-2022 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var createError$1 = httpErrorsExports;
+var debug$2 = srcExports('send');
+var deprecate$2 = depd_1('send');
+var destroy$1 = requireDestroy();
+var encodeUrl$1 = encodeurl;
+var escapeHtml$1 = escapeHtml_1;
+var etag = etag_1;
+var fresh$1 = fresh_1;
+var fs$h = require$$0$e;
+var mime$3 = mime_1;
+var ms = ms$1;
+var onFinished$1 = onFinishedExports;
+var parseRange$1 = rangeParser_1;
+var path$j = require$$0$c;
+var statuses$1 = statuses$3;
+var Stream$1 = Stream$2;
+var util$6 = require$$1$7;
+
+/**
+ * Path function references.
+ * @private
+ */
+
+var extname$1 = path$j.extname;
+var join$2 = path$j.join;
+var normalize$1 = path$j.normalize;
+var resolve$2 = path$j.resolve;
+var sep = path$j.sep;
+
+/**
+ * Regular expression for identifying a bytes Range header.
+ * @private
+ */
+
+var BYTES_RANGE_REGEXP = /^ *bytes=/;
+
+/**
+ * Maximum value allowed for the max age.
+ * @private
+ */
+
+var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000; // 1 year
+
+/**
+ * Regular expression to match a path with a directory up component.
+ * @private
+ */
+
+var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
+
+/**
+ * Module exports.
+ * @public
+ */
+
+send$2.exports = send$1;
+sendExports.mime = mime$3;
+
+/**
+ * Return a `SendStream` for `req` and `path`.
+ *
+ * @param {object} req
+ * @param {string} path
+ * @param {object} [options]
+ * @return {SendStream}
+ * @public
+ */
+
+function send$1 (req, path, options) {
+ return new SendStream(req, path, options)
+}
+
+/**
+ * Initialize a `SendStream` with the given `path`.
+ *
+ * @param {Request} req
+ * @param {String} path
+ * @param {object} [options]
+ * @private
+ */
+
+function SendStream (req, path, options) {
+ Stream$1.call(this);
+
+ var opts = options || {};
+
+ this.options = opts;
+ this.path = path;
+ this.req = req;
+
+ this._acceptRanges = opts.acceptRanges !== undefined
+ ? Boolean(opts.acceptRanges)
+ : true;
+
+ this._cacheControl = opts.cacheControl !== undefined
+ ? Boolean(opts.cacheControl)
+ : true;
+
+ this._etag = opts.etag !== undefined
+ ? Boolean(opts.etag)
+ : true;
+
+ this._dotfiles = opts.dotfiles !== undefined
+ ? opts.dotfiles
+ : 'ignore';
+
+ if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') {
+ throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"')
+ }
+
+ this._hidden = Boolean(opts.hidden);
+
+ if (opts.hidden !== undefined) {
+ deprecate$2('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead');
+ }
+
+ // legacy support
+ if (opts.dotfiles === undefined) {
+ this._dotfiles = undefined;
+ }
+
+ this._extensions = opts.extensions !== undefined
+ ? normalizeList(opts.extensions, 'extensions option')
+ : [];
+
+ this._immutable = opts.immutable !== undefined
+ ? Boolean(opts.immutable)
+ : false;
+
+ this._index = opts.index !== undefined
+ ? normalizeList(opts.index, 'index option')
+ : ['index.html'];
+
+ this._lastModified = opts.lastModified !== undefined
+ ? Boolean(opts.lastModified)
+ : true;
+
+ this._maxage = opts.maxAge || opts.maxage;
+ this._maxage = typeof this._maxage === 'string'
+ ? ms(this._maxage)
+ : Number(this._maxage);
+ this._maxage = !isNaN(this._maxage)
+ ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
+ : 0;
+
+ this._root = opts.root
+ ? resolve$2(opts.root)
+ : null;
+
+ if (!this._root && opts.from) {
+ this.from(opts.from);
+ }
+}
+
+/**
+ * Inherits from `Stream`.
+ */
+
+util$6.inherits(SendStream, Stream$1);
+
+/**
+ * Enable or disable etag generation.
+ *
+ * @param {Boolean} val
+ * @return {SendStream}
+ * @api public
+ */
+
+SendStream.prototype.etag = deprecate$2.function(function etag (val) {
+ this._etag = Boolean(val);
+ debug$2('etag %s', this._etag);
+ return this
+}, 'send.etag: pass etag as option');
+
+/**
+ * Enable or disable "hidden" (dot) files.
+ *
+ * @param {Boolean} path
+ * @return {SendStream}
+ * @api public
+ */
+
+SendStream.prototype.hidden = deprecate$2.function(function hidden (val) {
+ this._hidden = Boolean(val);
+ this._dotfiles = undefined;
+ debug$2('hidden %s', this._hidden);
+ return this
+}, 'send.hidden: use dotfiles option');
+
+/**
+ * Set index `paths`, set to a falsy
+ * value to disable index support.
+ *
+ * @param {String|Boolean|Array} paths
+ * @return {SendStream}
+ * @api public
+ */
+
+SendStream.prototype.index = deprecate$2.function(function index (paths) {
+ var index = !paths ? [] : normalizeList(paths, 'paths argument');
+ debug$2('index %o', paths);
+ this._index = index;
+ return this
+}, 'send.index: pass index as option');
+
+/**
+ * Set root `path`.
+ *
+ * @param {String} path
+ * @return {SendStream}
+ * @api public
+ */
+
+SendStream.prototype.root = function root (path) {
+ this._root = resolve$2(String(path));
+ debug$2('root %s', this._root);
+ return this
+};
+
+SendStream.prototype.from = deprecate$2.function(SendStream.prototype.root,
+ 'send.from: pass root as option');
+
+SendStream.prototype.root = deprecate$2.function(SendStream.prototype.root,
+ 'send.root: pass root as option');
+
+/**
+ * Set max-age to `maxAge`.
+ *
+ * @param {Number} maxAge
+ * @return {SendStream}
+ * @api public
+ */
+
+SendStream.prototype.maxage = deprecate$2.function(function maxage (maxAge) {
+ this._maxage = typeof maxAge === 'string'
+ ? ms(maxAge)
+ : Number(maxAge);
+ this._maxage = !isNaN(this._maxage)
+ ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
+ : 0;
+ debug$2('max-age %d', this._maxage);
+ return this
+}, 'send.maxage: pass maxAge as option');
+
+/**
+ * Emit error with `status`.
+ *
+ * @param {number} status
+ * @param {Error} [err]
+ * @private
+ */
+
+SendStream.prototype.error = function error (status, err) {
+ // emit if listeners instead of responding
+ if (hasListeners(this, 'error')) {
+ return this.emit('error', createHttpError(status, err))
+ }
+
+ var res = this.res;
+ var msg = statuses$1.message[status] || String(status);
+ var doc = createHtmlDocument('Error', escapeHtml$1(msg));
+
+ // clear existing headers
+ clearHeaders(res);
+
+ // add error headers
+ if (err && err.headers) {
+ setHeaders(res, err.headers);
+ }
+
+ // send basic response
+ res.statusCode = status;
+ res.setHeader('Content-Type', 'text/html; charset=UTF-8');
+ res.setHeader('Content-Length', Buffer.byteLength(doc));
+ res.setHeader('Content-Security-Policy', "default-src 'none'");
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.end(doc);
+};
+
+/**
+ * Check if the pathname ends with "/".
+ *
+ * @return {boolean}
+ * @private
+ */
+
+SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () {
+ return this.path[this.path.length - 1] === '/'
+};
+
+/**
+ * Check if this is a conditional GET request.
+ *
+ * @return {Boolean}
+ * @api private
+ */
+
+SendStream.prototype.isConditionalGET = function isConditionalGET () {
+ return this.req.headers['if-match'] ||
+ this.req.headers['if-unmodified-since'] ||
+ this.req.headers['if-none-match'] ||
+ this.req.headers['if-modified-since']
+};
+
+/**
+ * Check if the request preconditions failed.
+ *
+ * @return {boolean}
+ * @private
+ */
+
+SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () {
+ var req = this.req;
+ var res = this.res;
+
+ // if-match
+ var match = req.headers['if-match'];
+ if (match) {
+ var etag = res.getHeader('ETag');
+ return !etag || (match !== '*' && parseTokenList(match).every(function (match) {
+ return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag
+ }))
+ }
+
+ // if-unmodified-since
+ var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']);
+ if (!isNaN(unmodifiedSince)) {
+ var lastModified = parseHttpDate(res.getHeader('Last-Modified'));
+ return isNaN(lastModified) || lastModified > unmodifiedSince
+ }
+
+ return false
+};
+
+/**
+ * Strip various content header fields for a change in entity.
+ *
+ * @private
+ */
+
+SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () {
+ var res = this.res;
+
+ res.removeHeader('Content-Encoding');
+ res.removeHeader('Content-Language');
+ res.removeHeader('Content-Length');
+ res.removeHeader('Content-Range');
+ res.removeHeader('Content-Type');
+};
+
+/**
+ * Respond with 304 not modified.
+ *
+ * @api private
+ */
+
+SendStream.prototype.notModified = function notModified () {
+ var res = this.res;
+ debug$2('not modified');
+ this.removeContentHeaderFields();
+ res.statusCode = 304;
+ res.end();
+};
+
+/**
+ * Raise error that headers already sent.
+ *
+ * @api private
+ */
+
+SendStream.prototype.headersAlreadySent = function headersAlreadySent () {
+ var err = new Error('Can\'t set headers after they are sent.');
+ debug$2('headers already sent');
+ this.error(500, err);
+};
+
+/**
+ * Check if the request is cacheable, aka
+ * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}).
+ *
+ * @return {Boolean}
+ * @api private
+ */
+
+SendStream.prototype.isCachable = function isCachable () {
+ var statusCode = this.res.statusCode;
+ return (statusCode >= 200 && statusCode < 300) ||
+ statusCode === 304
+};
+
+/**
+ * Handle stat() error.
+ *
+ * @param {Error} error
+ * @private
+ */
+
+SendStream.prototype.onStatError = function onStatError (error) {
+ switch (error.code) {
+ case 'ENAMETOOLONG':
+ case 'ENOENT':
+ case 'ENOTDIR':
+ this.error(404, error);
+ break
+ default:
+ this.error(500, error);
+ break
+ }
+};
+
+/**
+ * Check if the cache is fresh.
+ *
+ * @return {Boolean}
+ * @api private
+ */
+
+SendStream.prototype.isFresh = function isFresh () {
+ return fresh$1(this.req.headers, {
+ etag: this.res.getHeader('ETag'),
+ 'last-modified': this.res.getHeader('Last-Modified')
+ })
+};
+
+/**
+ * Check if the range is fresh.
+ *
+ * @return {Boolean}
+ * @api private
+ */
+
+SendStream.prototype.isRangeFresh = function isRangeFresh () {
+ var ifRange = this.req.headers['if-range'];
+
+ if (!ifRange) {
+ return true
+ }
+
+ // if-range as etag
+ if (ifRange.indexOf('"') !== -1) {
+ var etag = this.res.getHeader('ETag');
+ return Boolean(etag && ifRange.indexOf(etag) !== -1)
+ }
+
+ // if-range as modified date
+ var lastModified = this.res.getHeader('Last-Modified');
+ return parseHttpDate(lastModified) <= parseHttpDate(ifRange)
+};
+
+/**
+ * Redirect to path.
+ *
+ * @param {string} path
+ * @private
+ */
+
+SendStream.prototype.redirect = function redirect (path) {
+ var res = this.res;
+
+ if (hasListeners(this, 'directory')) {
+ this.emit('directory', res, path);
+ return
+ }
+
+ if (this.hasTrailingSlash()) {
+ this.error(403);
+ return
+ }
+
+ var loc = encodeUrl$1(collapseLeadingSlashes(this.path + '/'));
+ var doc = createHtmlDocument('Redirecting', 'Redirecting to ' +
+ escapeHtml$1(loc) + '');
+
+ // redirect
+ res.statusCode = 301;
+ res.setHeader('Content-Type', 'text/html; charset=UTF-8');
+ res.setHeader('Content-Length', Buffer.byteLength(doc));
+ res.setHeader('Content-Security-Policy', "default-src 'none'");
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.setHeader('Location', loc);
+ res.end(doc);
+};
+
+/**
+ * Pipe to `res.
+ *
+ * @param {Stream} res
+ * @return {Stream} res
+ * @api public
+ */
+
+SendStream.prototype.pipe = function pipe (res) {
+ // root path
+ var root = this._root;
+
+ // references
+ this.res = res;
+
+ // decode the path
+ var path = decode$3(this.path);
+ if (path === -1) {
+ this.error(400);
+ return res
+ }
+
+ // null byte(s)
+ if (~path.indexOf('\0')) {
+ this.error(400);
+ return res
+ }
+
+ var parts;
+ if (root !== null) {
+ // normalize
+ if (path) {
+ path = normalize$1('.' + sep + path);
+ }
+
+ // malicious path
+ if (UP_PATH_REGEXP.test(path)) {
+ debug$2('malicious path "%s"', path);
+ this.error(403);
+ return res
+ }
+
+ // explode path parts
+ parts = path.split(sep);
+
+ // join / normalize from optional root dir
+ path = normalize$1(join$2(root, path));
+ } else {
+ // ".." is malicious without "root"
+ if (UP_PATH_REGEXP.test(path)) {
+ debug$2('malicious path "%s"', path);
+ this.error(403);
+ return res
+ }
+
+ // explode path parts
+ parts = normalize$1(path).split(sep);
+
+ // resolve the path
+ path = resolve$2(path);
+ }
+
+ // dotfile handling
+ if (containsDotFile(parts)) {
+ var access = this._dotfiles;
+
+ // legacy support
+ if (access === undefined) {
+ access = parts[parts.length - 1][0] === '.'
+ ? (this._hidden ? 'allow' : 'ignore')
+ : 'allow';
+ }
+
+ debug$2('%s dotfile "%s"', access, path);
+ switch (access) {
+ case 'allow':
+ break
+ case 'deny':
+ this.error(403);
+ return res
+ case 'ignore':
+ default:
+ this.error(404);
+ return res
+ }
+ }
+
+ // index file support
+ if (this._index.length && this.hasTrailingSlash()) {
+ this.sendIndex(path);
+ return res
+ }
+
+ this.sendFile(path);
+ return res
+};
+
+/**
+ * Transfer `path`.
+ *
+ * @param {String} path
+ * @api public
+ */
+
+SendStream.prototype.send = function send (path, stat) {
+ var len = stat.size;
+ var options = this.options;
+ var opts = {};
+ var res = this.res;
+ var req = this.req;
+ var ranges = req.headers.range;
+ var offset = options.start || 0;
+
+ if (headersSent(res)) {
+ // impossible to send now
+ this.headersAlreadySent();
+ return
+ }
+
+ debug$2('pipe "%s"', path);
+
+ // set header fields
+ this.setHeader(path, stat);
+
+ // set content-type
+ this.type(path);
+
+ // conditional GET support
+ if (this.isConditionalGET()) {
+ if (this.isPreconditionFailure()) {
+ this.error(412);
+ return
+ }
+
+ if (this.isCachable() && this.isFresh()) {
+ this.notModified();
+ return
+ }
+ }
+
+ // adjust len to start/end options
+ len = Math.max(0, len - offset);
+ if (options.end !== undefined) {
+ var bytes = options.end - offset + 1;
+ if (len > bytes) len = bytes;
+ }
+
+ // Range support
+ if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) {
+ // parse
+ ranges = parseRange$1(len, ranges, {
+ combine: true
+ });
+
+ // If-Range support
+ if (!this.isRangeFresh()) {
+ debug$2('range stale');
+ ranges = -2;
+ }
+
+ // unsatisfiable
+ if (ranges === -1) {
+ debug$2('range unsatisfiable');
+
+ // Content-Range
+ res.setHeader('Content-Range', contentRange('bytes', len));
+
+ // 416 Requested Range Not Satisfiable
+ return this.error(416, {
+ headers: { 'Content-Range': res.getHeader('Content-Range') }
+ })
+ }
+
+ // valid (syntactically invalid/multiple ranges are treated as a regular response)
+ if (ranges !== -2 && ranges.length === 1) {
+ debug$2('range %j', ranges);
+
+ // Content-Range
+ res.statusCode = 206;
+ res.setHeader('Content-Range', contentRange('bytes', len, ranges[0]));
+
+ // adjust for requested range
+ offset += ranges[0].start;
+ len = ranges[0].end - ranges[0].start + 1;
+ }
+ }
+
+ // clone options
+ for (var prop in options) {
+ opts[prop] = options[prop];
+ }
+
+ // set read options
+ opts.start = offset;
+ opts.end = Math.max(offset, offset + len - 1);
+
+ // content-length
+ res.setHeader('Content-Length', len);
+
+ // HEAD support
+ if (req.method === 'HEAD') {
+ res.end();
+ return
+ }
+
+ this.stream(path, opts);
+};
+
+/**
+ * Transfer file for `path`.
+ *
+ * @param {String} path
+ * @api private
+ */
+SendStream.prototype.sendFile = function sendFile (path) {
+ var i = 0;
+ var self = this;
+
+ debug$2('stat "%s"', path);
+ fs$h.stat(path, function onstat (err, stat) {
+ if (err && err.code === 'ENOENT' && !extname$1(path) && path[path.length - 1] !== sep) {
+ // not found, check extensions
+ return next(err)
+ }
+ if (err) return self.onStatError(err)
+ if (stat.isDirectory()) return self.redirect(path)
+ self.emit('file', path, stat);
+ self.send(path, stat);
+ });
+
+ function next (err) {
+ if (self._extensions.length <= i) {
+ return err
+ ? self.onStatError(err)
+ : self.error(404)
+ }
+
+ var p = path + '.' + self._extensions[i++];
+
+ debug$2('stat "%s"', p);
+ fs$h.stat(p, function (err, stat) {
+ if (err) return next(err)
+ if (stat.isDirectory()) return next()
+ self.emit('file', p, stat);
+ self.send(p, stat);
+ });
+ }
+};
+
+/**
+ * Transfer index for `path`.
+ *
+ * @param {String} path
+ * @api private
+ */
+SendStream.prototype.sendIndex = function sendIndex (path) {
+ var i = -1;
+ var self = this;
+
+ function next (err) {
+ if (++i >= self._index.length) {
+ if (err) return self.onStatError(err)
+ return self.error(404)
+ }
+
+ var p = join$2(path, self._index[i]);
+
+ debug$2('stat "%s"', p);
+ fs$h.stat(p, function (err, stat) {
+ if (err) return next(err)
+ if (stat.isDirectory()) return next()
+ self.emit('file', p, stat);
+ self.send(p, stat);
+ });
+ }
+
+ next();
+};
+
+/**
+ * Stream `path` to the response.
+ *
+ * @param {String} path
+ * @param {Object} options
+ * @api private
+ */
+
+SendStream.prototype.stream = function stream (path, options) {
+ var self = this;
+ var res = this.res;
+
+ // pipe
+ var stream = fs$h.createReadStream(path, options);
+ this.emit('stream', stream);
+ stream.pipe(res);
+
+ // cleanup
+ function cleanup () {
+ destroy$1(stream, true);
+ }
+
+ // response finished, cleanup
+ onFinished$1(res, cleanup);
+
+ // error handling
+ stream.on('error', function onerror (err) {
+ // clean up stream early
+ cleanup();
+
+ // error
+ self.onStatError(err);
+ });
+
+ // end
+ stream.on('end', function onend () {
+ self.emit('end');
+ });
+};
+
+/**
+ * Set content-type based on `path`
+ * if it hasn't been explicitly set.
+ *
+ * @param {String} path
+ * @api private
+ */
+
+SendStream.prototype.type = function type (path) {
+ var res = this.res;
+
+ if (res.getHeader('Content-Type')) return
+
+ var type = mime$3.lookup(path);
+
+ if (!type) {
+ debug$2('no content-type');
+ return
+ }
+
+ var charset = mime$3.charsets.lookup(type);
+
+ debug$2('content-type %s', type);
+ res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
+};
+
+/**
+ * Set response header fields, most
+ * fields may be pre-defined.
+ *
+ * @param {String} path
+ * @param {Object} stat
+ * @api private
+ */
+
+SendStream.prototype.setHeader = function setHeader (path, stat) {
+ var res = this.res;
+
+ this.emit('headers', res, path, stat);
+
+ if (this._acceptRanges && !res.getHeader('Accept-Ranges')) {
+ debug$2('accept ranges');
+ res.setHeader('Accept-Ranges', 'bytes');
+ }
+
+ if (this._cacheControl && !res.getHeader('Cache-Control')) {
+ var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000);
+
+ if (this._immutable) {
+ cacheControl += ', immutable';
+ }
+
+ debug$2('cache-control %s', cacheControl);
+ res.setHeader('Cache-Control', cacheControl);
+ }
+
+ if (this._lastModified && !res.getHeader('Last-Modified')) {
+ var modified = stat.mtime.toUTCString();
+ debug$2('modified %s', modified);
+ res.setHeader('Last-Modified', modified);
+ }
+
+ if (this._etag && !res.getHeader('ETag')) {
+ var val = etag(stat);
+ debug$2('etag %s', val);
+ res.setHeader('ETag', val);
+ }
+};
+
+/**
+ * Clear all headers from a response.
+ *
+ * @param {object} res
+ * @private
+ */
+
+function clearHeaders (res) {
+ var headers = getHeaderNames(res);
+
+ for (var i = 0; i < headers.length; i++) {
+ res.removeHeader(headers[i]);
+ }
+}
+
+/**
+ * Collapse all leading slashes into a single slash
+ *
+ * @param {string} str
+ * @private
+ */
+function collapseLeadingSlashes (str) {
+ for (var i = 0; i < str.length; i++) {
+ if (str[i] !== '/') {
+ break
+ }
+ }
+
+ return i > 1
+ ? '/' + str.substr(i)
+ : str
+}
+
+/**
+ * Determine if path parts contain a dotfile.
+ *
+ * @api private
+ */
+
+function containsDotFile (parts) {
+ for (var i = 0; i < parts.length; i++) {
+ var part = parts[i];
+ if (part.length > 1 && part[0] === '.') {
+ return true
+ }
+ }
+
+ return false
+}
+
+/**
+ * Create a Content-Range header.
+ *
+ * @param {string} type
+ * @param {number} size
+ * @param {array} [range]
+ */
+
+function contentRange (type, size, range) {
+ return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size
+}
+
+/**
+ * Create a minimal HTML document.
+ *
+ * @param {string} title
+ * @param {string} body
+ * @private
+ */
+
+function createHtmlDocument (title, body) {
+ return '\n' +
+ '\n' +
+ '\n' +
+ '\n' +
+ '' + title + '\n' +
+ '\n' +
+ '\n' +
+ '' + body + '
\n' +
+ '\n' +
+ '\n'
+}
+
+/**
+ * Create a HttpError object from simple arguments.
+ *
+ * @param {number} status
+ * @param {Error|object} err
+ * @private
+ */
+
+function createHttpError (status, err) {
+ if (!err) {
+ return createError$1(status)
+ }
+
+ return err instanceof Error
+ ? createError$1(status, err, { expose: false })
+ : createError$1(status, err)
+}
+
+/**
+ * decodeURIComponent.
+ *
+ * Allows V8 to only deoptimize this fn instead of all
+ * of send().
+ *
+ * @param {String} path
+ * @api private
+ */
+
+function decode$3 (path) {
+ try {
+ return decodeURIComponent(path)
+ } catch (err) {
+ return -1
+ }
+}
+
+/**
+ * Get the header names on a respnse.
+ *
+ * @param {object} res
+ * @returns {array[string]}
+ * @private
+ */
+
+function getHeaderNames (res) {
+ return typeof res.getHeaderNames !== 'function'
+ ? Object.keys(res._headers || {})
+ : res.getHeaderNames()
+}
+
+/**
+ * Determine if emitter has listeners of a given type.
+ *
+ * The way to do this check is done three different ways in Node.js >= 0.8
+ * so this consolidates them into a minimal set using instance methods.
+ *
+ * @param {EventEmitter} emitter
+ * @param {string} type
+ * @returns {boolean}
+ * @private
+ */
+
+function hasListeners (emitter, type) {
+ var count = typeof emitter.listenerCount !== 'function'
+ ? emitter.listeners(type).length
+ : emitter.listenerCount(type);
+
+ return count > 0
+}
+
+/**
+ * Determine if the response headers have been sent.
+ *
+ * @param {object} res
+ * @returns {boolean}
+ * @private
+ */
+
+function headersSent (res) {
+ return typeof res.headersSent !== 'boolean'
+ ? Boolean(res._header)
+ : res.headersSent
+}
+
+/**
+ * Normalize the index option into an array.
+ *
+ * @param {boolean|string|array} val
+ * @param {string} name
+ * @private
+ */
+
+function normalizeList (val, name) {
+ var list = [].concat(val || []);
+
+ for (var i = 0; i < list.length; i++) {
+ if (typeof list[i] !== 'string') {
+ throw new TypeError(name + ' must be array of strings or false')
+ }
+ }
+
+ return list
+}
+
+/**
+ * Parse an HTTP Date into a number.
+ *
+ * @param {string} date
+ * @private
+ */
+
+function parseHttpDate (date) {
+ var timestamp = date && Date.parse(date);
+
+ return typeof timestamp === 'number'
+ ? timestamp
+ : NaN
+}
+
+/**
+ * Parse a HTTP token list.
+ *
+ * @param {string} str
+ * @private
+ */
+
+function parseTokenList (str) {
+ var end = 0;
+ var list = [];
+ var start = 0;
+
+ // gather tokens
+ for (var i = 0, len = str.length; i < len; i++) {
+ switch (str.charCodeAt(i)) {
+ case 0x20: /* */
+ if (start === end) {
+ start = end = i + 1;
+ }
+ break
+ case 0x2c: /* , */
+ if (start !== end) {
+ list.push(str.substring(start, end));
+ }
+ start = end = i + 1;
+ break
+ default:
+ end = i + 1;
+ break
+ }
+ }
+
+ // final token
+ if (start !== end) {
+ list.push(str.substring(start, end));
+ }
+
+ return list
+}
+
+/**
+ * Set an object of headers on a response.
+ *
+ * @param {object} res
+ * @param {object} headers
+ * @private
+ */
+
+function setHeaders (res, headers) {
+ var keys = Object.keys(headers);
+
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ res.setHeader(key, headers[key]);
+ }
+}
+
+var proxyAddrExports = {};
+var proxyAddr = {
+ get exports(){ return proxyAddrExports; },
+ set exports(v){ proxyAddrExports = v; },
+};
+
+/*!
+ * forwarded
+ * Copyright(c) 2014-2017 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var forwarded_1 = forwarded$1;
+
+/**
+ * Get all addresses in the request, using the `X-Forwarded-For` header.
+ *
+ * @param {object} req
+ * @return {array}
+ * @public
+ */
+
+function forwarded$1 (req) {
+ if (!req) {
+ throw new TypeError('argument req is required')
+ }
+
+ // simple header parsing
+ var proxyAddrs = parse$9(req.headers['x-forwarded-for'] || '');
+ var socketAddr = getSocketAddr(req);
+ var addrs = [socketAddr].concat(proxyAddrs);
+
+ // return all addresses
+ return addrs
+}
+
+/**
+ * Get the socket address for a request.
+ *
+ * @param {object} req
+ * @return {string}
+ * @private
+ */
+
+function getSocketAddr (req) {
+ return req.socket
+ ? req.socket.remoteAddress
+ : req.connection.remoteAddress
+}
+
+/**
+ * Parse the X-Forwarded-For header.
+ *
+ * @param {string} header
+ * @private
+ */
+
+function parse$9 (header) {
+ var end = header.length;
+ var list = [];
+ var start = header.length;
+
+ // gather addresses, backwards
+ for (var i = header.length - 1; i >= 0; i--) {
+ switch (header.charCodeAt(i)) {
+ case 0x20: /* */
+ if (start === end) {
+ start = end = i;
+ }
+ break
+ case 0x2c: /* , */
+ if (start !== end) {
+ list.push(header.substring(start, end));
+ }
+ start = end = i;
+ break
+ default:
+ start = i;
+ break
+ }
+ }
+
+ // final address
+ if (start !== end) {
+ list.push(header.substring(start, end));
+ }
+
+ return list
+}
+
+var ipaddrExports = {};
+var ipaddr$1 = {
+ get exports(){ return ipaddrExports; },
+ set exports(v){ ipaddrExports = v; },
+};
+
+(function (module) {
+ (function() {
+ var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex;
+
+ ipaddr = {};
+
+ root = this;
+
+ if ((module !== null) && module.exports) {
+ module.exports = ipaddr;
+ } else {
+ root['ipaddr'] = ipaddr;
+ }
+
+ matchCIDR = function(first, second, partSize, cidrBits) {
+ var part, shift;
+ if (first.length !== second.length) {
+ throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
+ }
+ part = 0;
+ while (cidrBits > 0) {
+ shift = partSize - cidrBits;
+ if (shift < 0) {
+ shift = 0;
+ }
+ if (first[part] >> shift !== second[part] >> shift) {
+ return false;
+ }
+ cidrBits -= partSize;
+ part += 1;
+ }
+ return true;
+ };
+
+ ipaddr.subnetMatch = function(address, rangeList, defaultName) {
+ var k, len, rangeName, rangeSubnets, subnet;
+ if (defaultName == null) {
+ defaultName = 'unicast';
+ }
+ for (rangeName in rangeList) {
+ rangeSubnets = rangeList[rangeName];
+ if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
+ rangeSubnets = [rangeSubnets];
+ }
+ for (k = 0, len = rangeSubnets.length; k < len; k++) {
+ subnet = rangeSubnets[k];
+ if (address.kind() === subnet[0].kind()) {
+ if (address.match.apply(address, subnet)) {
+ return rangeName;
+ }
+ }
+ }
+ }
+ return defaultName;
+ };
+
+ ipaddr.IPv4 = (function() {
+ function IPv4(octets) {
+ var k, len, octet;
+ if (octets.length !== 4) {
+ throw new Error("ipaddr: ipv4 octet count should be 4");
+ }
+ for (k = 0, len = octets.length; k < len; k++) {
+ octet = octets[k];
+ if (!((0 <= octet && octet <= 255))) {
+ throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
+ }
+ }
+ this.octets = octets;
+ }
+
+ IPv4.prototype.kind = function() {
+ return 'ipv4';
+ };
+
+ IPv4.prototype.toString = function() {
+ return this.octets.join(".");
+ };
+
+ IPv4.prototype.toNormalizedString = function() {
+ return this.toString();
+ };
+
+ IPv4.prototype.toByteArray = function() {
+ return this.octets.slice(0);
+ };
+
+ IPv4.prototype.match = function(other, cidrRange) {
+ var ref;
+ if (cidrRange === void 0) {
+ ref = other, other = ref[0], cidrRange = ref[1];
+ }
+ if (other.kind() !== 'ipv4') {
+ throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
+ }
+ return matchCIDR(this.octets, other.octets, 8, cidrRange);
+ };
+
+ IPv4.prototype.SpecialRanges = {
+ unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
+ broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
+ multicast: [[new IPv4([224, 0, 0, 0]), 4]],
+ linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
+ loopback: [[new IPv4([127, 0, 0, 0]), 8]],
+ carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
+ "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
+ reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
+ };
+
+ IPv4.prototype.range = function() {
+ return ipaddr.subnetMatch(this, this.SpecialRanges);
+ };
+
+ IPv4.prototype.toIPv4MappedAddress = function() {
+ return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
+ };
+
+ IPv4.prototype.prefixLengthFromSubnetMask = function() {
+ var cidr, i, k, octet, stop, zeros, zerotable;
+ zerotable = {
+ 0: 8,
+ 128: 7,
+ 192: 6,
+ 224: 5,
+ 240: 4,
+ 248: 3,
+ 252: 2,
+ 254: 1,
+ 255: 0
+ };
+ cidr = 0;
+ stop = false;
+ for (i = k = 3; k >= 0; i = k += -1) {
+ octet = this.octets[i];
+ if (octet in zerotable) {
+ zeros = zerotable[octet];
+ if (stop && zeros !== 0) {
+ return null;
+ }
+ if (zeros !== 8) {
+ stop = true;
+ }
+ cidr += zeros;
+ } else {
+ return null;
+ }
+ }
+ return 32 - cidr;
+ };
+
+ return IPv4;
+
+ })();
+
+ ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
+
+ ipv4Regexes = {
+ fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
+ longValue: new RegExp("^" + ipv4Part + "$", 'i')
+ };
+
+ ipaddr.IPv4.parser = function(string) {
+ var match, parseIntAuto, part, shift, value;
+ parseIntAuto = function(string) {
+ if (string[0] === "0" && string[1] !== "x") {
+ return parseInt(string, 8);
+ } else {
+ return parseInt(string);
+ }
+ };
+ if (match = string.match(ipv4Regexes.fourOctet)) {
+ return (function() {
+ var k, len, ref, results;
+ ref = match.slice(1, 6);
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(parseIntAuto(part));
+ }
+ return results;
+ })();
+ } else if (match = string.match(ipv4Regexes.longValue)) {
+ value = parseIntAuto(match[1]);
+ if (value > 0xffffffff || value < 0) {
+ throw new Error("ipaddr: address outside defined range");
+ }
+ return ((function() {
+ var k, results;
+ results = [];
+ for (shift = k = 0; k <= 24; shift = k += 8) {
+ results.push((value >> shift) & 0xff);
+ }
+ return results;
+ })()).reverse();
+ } else {
+ return null;
+ }
+ };
+
+ ipaddr.IPv6 = (function() {
+ function IPv6(parts, zoneId) {
+ var i, k, l, len, part, ref;
+ if (parts.length === 16) {
+ this.parts = [];
+ for (i = k = 0; k <= 14; i = k += 2) {
+ this.parts.push((parts[i] << 8) | parts[i + 1]);
+ }
+ } else if (parts.length === 8) {
+ this.parts = parts;
+ } else {
+ throw new Error("ipaddr: ipv6 part count should be 8 or 16");
+ }
+ ref = this.parts;
+ for (l = 0, len = ref.length; l < len; l++) {
+ part = ref[l];
+ if (!((0 <= part && part <= 0xffff))) {
+ throw new Error("ipaddr: ipv6 part should fit in 16 bits");
+ }
+ }
+ if (zoneId) {
+ this.zoneId = zoneId;
+ }
+ }
+
+ IPv6.prototype.kind = function() {
+ return 'ipv6';
+ };
+
+ IPv6.prototype.toString = function() {
+ return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::');
+ };
+
+ IPv6.prototype.toRFC5952String = function() {
+ var bestMatchIndex, bestMatchLength, match, regex, string;
+ regex = /((^|:)(0(:|$)){2,})/g;
+ string = this.toNormalizedString();
+ bestMatchIndex = 0;
+ bestMatchLength = -1;
+ while ((match = regex.exec(string))) {
+ if (match[0].length > bestMatchLength) {
+ bestMatchIndex = match.index;
+ bestMatchLength = match[0].length;
+ }
+ }
+ if (bestMatchLength < 0) {
+ return string;
+ }
+ return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength);
+ };
+
+ IPv6.prototype.toByteArray = function() {
+ var bytes, k, len, part, ref;
+ bytes = [];
+ ref = this.parts;
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ bytes.push(part >> 8);
+ bytes.push(part & 0xff);
+ }
+ return bytes;
+ };
+
+ IPv6.prototype.toNormalizedString = function() {
+ var addr, part, suffix;
+ addr = ((function() {
+ var k, len, ref, results;
+ ref = this.parts;
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(part.toString(16));
+ }
+ return results;
+ }).call(this)).join(":");
+ suffix = '';
+ if (this.zoneId) {
+ suffix = '%' + this.zoneId;
+ }
+ return addr + suffix;
+ };
+
+ IPv6.prototype.toFixedLengthString = function() {
+ var addr, part, suffix;
+ addr = ((function() {
+ var k, len, ref, results;
+ ref = this.parts;
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(part.toString(16).padStart(4, '0'));
+ }
+ return results;
+ }).call(this)).join(":");
+ suffix = '';
+ if (this.zoneId) {
+ suffix = '%' + this.zoneId;
+ }
+ return addr + suffix;
+ };
+
+ IPv6.prototype.match = function(other, cidrRange) {
+ var ref;
+ if (cidrRange === void 0) {
+ ref = other, other = ref[0], cidrRange = ref[1];
+ }
+ if (other.kind() !== 'ipv6') {
+ throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
+ }
+ return matchCIDR(this.parts, other.parts, 16, cidrRange);
+ };
+
+ IPv6.prototype.SpecialRanges = {
+ unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
+ linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
+ multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
+ loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
+ uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
+ ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
+ rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
+ rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
+ '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
+ teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
+ reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
+ };
+
+ IPv6.prototype.range = function() {
+ return ipaddr.subnetMatch(this, this.SpecialRanges);
+ };
+
+ IPv6.prototype.isIPv4MappedAddress = function() {
+ return this.range() === 'ipv4Mapped';
+ };
+
+ IPv6.prototype.toIPv4Address = function() {
+ var high, low, ref;
+ if (!this.isIPv4MappedAddress()) {
+ throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
+ }
+ ref = this.parts.slice(-2), high = ref[0], low = ref[1];
+ return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
+ };
+
+ IPv6.prototype.prefixLengthFromSubnetMask = function() {
+ var cidr, i, k, part, stop, zeros, zerotable;
+ zerotable = {
+ 0: 16,
+ 32768: 15,
+ 49152: 14,
+ 57344: 13,
+ 61440: 12,
+ 63488: 11,
+ 64512: 10,
+ 65024: 9,
+ 65280: 8,
+ 65408: 7,
+ 65472: 6,
+ 65504: 5,
+ 65520: 4,
+ 65528: 3,
+ 65532: 2,
+ 65534: 1,
+ 65535: 0
+ };
+ cidr = 0;
+ stop = false;
+ for (i = k = 7; k >= 0; i = k += -1) {
+ part = this.parts[i];
+ if (part in zerotable) {
+ zeros = zerotable[part];
+ if (stop && zeros !== 0) {
+ return null;
+ }
+ if (zeros !== 16) {
+ stop = true;
+ }
+ cidr += zeros;
+ } else {
+ return null;
+ }
+ }
+ return 128 - cidr;
+ };
+
+ return IPv6;
+
+ })();
+
+ ipv6Part = "(?:[0-9a-f]+::?)+";
+
+ zoneIndex = "%[0-9a-z]{1,}";
+
+ ipv6Regexes = {
+ zoneIndex: new RegExp(zoneIndex, 'i'),
+ "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'),
+ transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i')
+ };
+
+ expandIPv6 = function(string, parts) {
+ var colonCount, lastColon, part, replacement, replacementCount, zoneId;
+ if (string.indexOf('::') !== string.lastIndexOf('::')) {
+ return null;
+ }
+ zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0];
+ if (zoneId) {
+ zoneId = zoneId.substring(1);
+ string = string.replace(/%.+$/, '');
+ }
+ colonCount = 0;
+ lastColon = -1;
+ while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
+ colonCount++;
+ }
+ if (string.substr(0, 2) === '::') {
+ colonCount--;
+ }
+ if (string.substr(-2, 2) === '::') {
+ colonCount--;
+ }
+ if (colonCount > parts) {
+ return null;
+ }
+ replacementCount = parts - colonCount;
+ replacement = ':';
+ while (replacementCount--) {
+ replacement += '0:';
+ }
+ string = string.replace('::', replacement);
+ if (string[0] === ':') {
+ string = string.slice(1);
+ }
+ if (string[string.length - 1] === ':') {
+ string = string.slice(0, -1);
+ }
+ parts = (function() {
+ var k, len, ref, results;
+ ref = string.split(":");
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(parseInt(part, 16));
+ }
+ return results;
+ })();
+ return {
+ parts: parts,
+ zoneId: zoneId
+ };
+ };
+
+ ipaddr.IPv6.parser = function(string) {
+ var addr, k, len, match, octet, octets, zoneId;
+ if (ipv6Regexes['native'].test(string)) {
+ return expandIPv6(string, 8);
+ } else if (match = string.match(ipv6Regexes['transitional'])) {
+ zoneId = match[6] || '';
+ addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
+ if (addr.parts) {
+ octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
+ for (k = 0, len = octets.length; k < len; k++) {
+ octet = octets[k];
+ if (!((0 <= octet && octet <= 255))) {
+ return null;
+ }
+ }
+ addr.parts.push(octets[0] << 8 | octets[1]);
+ addr.parts.push(octets[2] << 8 | octets[3]);
+ return {
+ parts: addr.parts,
+ zoneId: addr.zoneId
+ };
+ }
+ }
+ return null;
+ };
+
+ ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
+ return this.parser(string) !== null;
+ };
+
+ ipaddr.IPv4.isValid = function(string) {
+ try {
+ new this(this.parser(string));
+ return true;
+ } catch (error1) {
+ return false;
+ }
+ };
+
+ ipaddr.IPv4.isValidFourPartDecimal = function(string) {
+ if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
+ return true;
+ } else {
+ return false;
+ }
+ };
+
+ ipaddr.IPv6.isValid = function(string) {
+ var addr;
+ if (typeof string === "string" && string.indexOf(":") === -1) {
+ return false;
+ }
+ try {
+ addr = this.parser(string);
+ new this(addr.parts, addr.zoneId);
+ return true;
+ } catch (error1) {
+ return false;
+ }
+ };
+
+ ipaddr.IPv4.parse = function(string) {
+ var parts;
+ parts = this.parser(string);
+ if (parts === null) {
+ throw new Error("ipaddr: string is not formatted like ip address");
+ }
+ return new this(parts);
+ };
+
+ ipaddr.IPv6.parse = function(string) {
+ var addr;
+ addr = this.parser(string);
+ if (addr.parts === null) {
+ throw new Error("ipaddr: string is not formatted like ip address");
+ }
+ return new this(addr.parts, addr.zoneId);
+ };
+
+ ipaddr.IPv4.parseCIDR = function(string) {
+ var maskLength, match, parsed;
+ if (match = string.match(/^(.+)\/(\d+)$/)) {
+ maskLength = parseInt(match[2]);
+ if (maskLength >= 0 && maskLength <= 32) {
+ parsed = [this.parse(match[1]), maskLength];
+ Object.defineProperty(parsed, 'toString', {
+ value: function() {
+ return this.join('/');
+ }
+ });
+ return parsed;
+ }
+ }
+ throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
+ };
+
+ ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
+ var filledOctetCount, j, octets;
+ prefix = parseInt(prefix);
+ if (prefix < 0 || prefix > 32) {
+ throw new Error('ipaddr: invalid IPv4 prefix length');
+ }
+ octets = [0, 0, 0, 0];
+ j = 0;
+ filledOctetCount = Math.floor(prefix / 8);
+ while (j < filledOctetCount) {
+ octets[j] = 255;
+ j++;
+ }
+ if (filledOctetCount < 4) {
+ octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
+ }
+ return new this(octets);
+ };
+
+ ipaddr.IPv4.broadcastAddressFromCIDR = function(string) {
+ var cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
+ try {
+ cidr = this.parseCIDR(string);
+ ipInterfaceOctets = cidr[0].toByteArray();
+ subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
+ octets = [];
+ i = 0;
+ while (i < 4) {
+ octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
+ i++;
+ }
+ return new this(octets);
+ } catch (error1) {
+ throw new Error('ipaddr: the address does not have IPv4 CIDR format');
+ }
+ };
+
+ ipaddr.IPv4.networkAddressFromCIDR = function(string) {
+ var cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
+ try {
+ cidr = this.parseCIDR(string);
+ ipInterfaceOctets = cidr[0].toByteArray();
+ subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
+ octets = [];
+ i = 0;
+ while (i < 4) {
+ octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
+ i++;
+ }
+ return new this(octets);
+ } catch (error1) {
+ throw new Error('ipaddr: the address does not have IPv4 CIDR format');
+ }
+ };
+
+ ipaddr.IPv6.parseCIDR = function(string) {
+ var maskLength, match, parsed;
+ if (match = string.match(/^(.+)\/(\d+)$/)) {
+ maskLength = parseInt(match[2]);
+ if (maskLength >= 0 && maskLength <= 128) {
+ parsed = [this.parse(match[1]), maskLength];
+ Object.defineProperty(parsed, 'toString', {
+ value: function() {
+ return this.join('/');
+ }
+ });
+ return parsed;
+ }
+ }
+ throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
+ };
+
+ ipaddr.isValid = function(string) {
+ return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
+ };
+
+ ipaddr.parse = function(string) {
+ if (ipaddr.IPv6.isValid(string)) {
+ return ipaddr.IPv6.parse(string);
+ } else if (ipaddr.IPv4.isValid(string)) {
+ return ipaddr.IPv4.parse(string);
+ } else {
+ throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
+ }
+ };
+
+ ipaddr.parseCIDR = function(string) {
+ try {
+ return ipaddr.IPv6.parseCIDR(string);
+ } catch (error1) {
+ try {
+ return ipaddr.IPv4.parseCIDR(string);
+ } catch (error1) {
+ throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
+ }
+ }
+ };
+
+ ipaddr.fromByteArray = function(bytes) {
+ var length;
+ length = bytes.length;
+ if (length === 4) {
+ return new ipaddr.IPv4(bytes);
+ } else if (length === 16) {
+ return new ipaddr.IPv6(bytes);
+ } else {
+ throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
+ }
+ };
+
+ ipaddr.process = function(string) {
+ var addr;
+ addr = this.parse(string);
+ if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
+ return addr.toIPv4Address();
+ } else {
+ return addr;
+ }
+ };
+
+ }).call(commonjsGlobal);
+} (ipaddr$1));
+
+/*!
+ * proxy-addr
+ * Copyright(c) 2014-2016 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+proxyAddr.exports = proxyaddr$1;
+proxyAddrExports.all = alladdrs;
+proxyAddrExports.compile = compile$1;
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var forwarded = forwarded_1;
+var ipaddr = ipaddrExports;
+
+/**
+ * Variables.
+ * @private
+ */
+
+var DIGIT_REGEXP = /^[0-9]+$/;
+var isip = ipaddr.isValid;
+var parseip = ipaddr.parse;
+
+/**
+ * Pre-defined IP ranges.
+ * @private
+ */
+
+var IP_RANGES = {
+ linklocal: ['169.254.0.0/16', 'fe80::/10'],
+ loopback: ['127.0.0.1/8', '::1/128'],
+ uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7']
+};
+
+/**
+ * Get all addresses in the request, optionally stopping
+ * at the first untrusted.
+ *
+ * @param {Object} request
+ * @param {Function|Array|String} [trust]
+ * @public
+ */
+
+function alladdrs (req, trust) {
+ // get addresses
+ var addrs = forwarded(req);
+
+ if (!trust) {
+ // Return all addresses
+ return addrs
+ }
+
+ if (typeof trust !== 'function') {
+ trust = compile$1(trust);
+ }
+
+ for (var i = 0; i < addrs.length - 1; i++) {
+ if (trust(addrs[i], i)) continue
+
+ addrs.length = i + 1;
+ }
+
+ return addrs
+}
+
+/**
+ * Compile argument into trust function.
+ *
+ * @param {Array|String} val
+ * @private
+ */
+
+function compile$1 (val) {
+ if (!val) {
+ throw new TypeError('argument is required')
+ }
+
+ var trust;
+
+ if (typeof val === 'string') {
+ trust = [val];
+ } else if (Array.isArray(val)) {
+ trust = val.slice();
+ } else {
+ throw new TypeError('unsupported trust argument')
+ }
+
+ for (var i = 0; i < trust.length; i++) {
+ val = trust[i];
+
+ if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) {
+ continue
+ }
+
+ // Splice in pre-defined range
+ val = IP_RANGES[val];
+ trust.splice.apply(trust, [i, 1].concat(val));
+ i += val.length - 1;
+ }
+
+ return compileTrust(compileRangeSubnets(trust))
+}
+
+/**
+ * Compile `arr` elements into range subnets.
+ *
+ * @param {Array} arr
+ * @private
+ */
+
+function compileRangeSubnets (arr) {
+ var rangeSubnets = new Array(arr.length);
+
+ for (var i = 0; i < arr.length; i++) {
+ rangeSubnets[i] = parseipNotation(arr[i]);
+ }
+
+ return rangeSubnets
+}
+
+/**
+ * Compile range subnet array into trust function.
+ *
+ * @param {Array} rangeSubnets
+ * @private
+ */
+
+function compileTrust (rangeSubnets) {
+ // Return optimized function based on length
+ var len = rangeSubnets.length;
+ return len === 0
+ ? trustNone
+ : len === 1
+ ? trustSingle(rangeSubnets[0])
+ : trustMulti(rangeSubnets)
+}
+
+/**
+ * Parse IP notation string into range subnet.
+ *
+ * @param {String} note
+ * @private
+ */
+
+function parseipNotation (note) {
+ var pos = note.lastIndexOf('/');
+ var str = pos !== -1
+ ? note.substring(0, pos)
+ : note;
+
+ if (!isip(str)) {
+ throw new TypeError('invalid IP address: ' + str)
+ }
+
+ var ip = parseip(str);
+
+ if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {
+ // Store as IPv4
+ ip = ip.toIPv4Address();
+ }
+
+ var max = ip.kind() === 'ipv6'
+ ? 128
+ : 32;
+
+ var range = pos !== -1
+ ? note.substring(pos + 1, note.length)
+ : null;
+
+ if (range === null) {
+ range = max;
+ } else if (DIGIT_REGEXP.test(range)) {
+ range = parseInt(range, 10);
+ } else if (ip.kind() === 'ipv4' && isip(range)) {
+ range = parseNetmask(range);
+ } else {
+ range = null;
+ }
+
+ if (range <= 0 || range > max) {
+ throw new TypeError('invalid range on address: ' + note)
+ }
+
+ return [ip, range]
+}
+
+/**
+ * Parse netmask string into CIDR range.
+ *
+ * @param {String} netmask
+ * @private
+ */
+
+function parseNetmask (netmask) {
+ var ip = parseip(netmask);
+ var kind = ip.kind();
+
+ return kind === 'ipv4'
+ ? ip.prefixLengthFromSubnetMask()
+ : null
+}
+
+/**
+ * Determine address of proxied request.
+ *
+ * @param {Object} request
+ * @param {Function|Array|String} trust
+ * @public
+ */
+
+function proxyaddr$1 (req, trust) {
+ if (!req) {
+ throw new TypeError('req argument is required')
+ }
+
+ if (!trust) {
+ throw new TypeError('trust argument is required')
+ }
+
+ var addrs = alladdrs(req, trust);
+ var addr = addrs[addrs.length - 1];
+
+ return addr
+}
+
+/**
+ * Static trust function to trust nothing.
+ *
+ * @private
+ */
+
+function trustNone () {
+ return false
+}
+
+/**
+ * Compile trust function for multiple subnets.
+ *
+ * @param {Array} subnets
+ * @private
+ */
+
+function trustMulti (subnets) {
+ return function trust (addr) {
+ if (!isip(addr)) return false
+
+ var ip = parseip(addr);
+ var ipconv;
+ var kind = ip.kind();
+
+ for (var i = 0; i < subnets.length; i++) {
+ var subnet = subnets[i];
+ var subnetip = subnet[0];
+ var subnetkind = subnetip.kind();
+ var subnetrange = subnet[1];
+ var trusted = ip;
+
+ if (kind !== subnetkind) {
+ if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) {
+ // Incompatible IP addresses
+ continue
+ }
+
+ if (!ipconv) {
+ // Convert IP to match subnet IP kind
+ ipconv = subnetkind === 'ipv4'
+ ? ip.toIPv4Address()
+ : ip.toIPv4MappedAddress();
+ }
+
+ trusted = ipconv;
+ }
+
+ if (trusted.match(subnetip, subnetrange)) {
+ return true
+ }
+ }
+
+ return false
+ }
+}
+
+/**
+ * Compile trust function for single subnet.
+ *
+ * @param {Object} subnet
+ * @private
+ */
+
+function trustSingle (subnet) {
+ var subnetip = subnet[0];
+ var subnetkind = subnetip.kind();
+ var subnetisipv4 = subnetkind === 'ipv4';
+ var subnetrange = subnet[1];
+
+ return function trust (addr) {
+ if (!isip(addr)) return false
+
+ var ip = parseip(addr);
+ var kind = ip.kind();
+
+ if (kind !== subnetkind) {
+ if (subnetisipv4 && !ip.isIPv4MappedAddress()) {
+ // Incompatible IP addresses
+ return false
+ }
+
+ // Convert IP to match subnet IP kind
+ ip = subnetisipv4
+ ? ip.toIPv4Address()
+ : ip.toIPv4MappedAddress();
+ }
+
+ return ip.match(subnetip, subnetrange)
+ }
+}
+
+/*!
+ * express
+ * Copyright(c) 2009-2013 TJ Holowaychuk
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+(function (exports) {
+
+ /**
+ * Module dependencies.
+ * @api private
+ */
+
+ var Buffer = safeBufferExports.Buffer;
+ var contentDisposition = contentDispositionExports;
+ var contentType$1 = contentType;
+ var deprecate = depd_1('express');
+ var flatten = arrayFlatten_1;
+ var mime = sendExports.mime;
+ var etag = etag_1;
+ var proxyaddr = proxyAddrExports;
+ var qs = lib$2;
+ var querystring = require$$8$1;
+
+ /**
+ * Return strong ETag for `body`.
+ *
+ * @param {String|Buffer} body
+ * @param {String} [encoding]
+ * @return {String}
+ * @api private
+ */
+
+ exports.etag = createETagGenerator({ weak: false });
+
+ /**
+ * Return weak ETag for `body`.
+ *
+ * @param {String|Buffer} body
+ * @param {String} [encoding]
+ * @return {String}
+ * @api private
+ */
+
+ exports.wetag = createETagGenerator({ weak: true });
+
+ /**
+ * Check if `path` looks absolute.
+ *
+ * @param {String} path
+ * @return {Boolean}
+ * @api private
+ */
+
+ exports.isAbsolute = function(path){
+ if ('/' === path[0]) return true;
+ if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path
+ if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path
+ };
+
+ /**
+ * Flatten the given `arr`.
+ *
+ * @param {Array} arr
+ * @return {Array}
+ * @api private
+ */
+
+ exports.flatten = deprecate.function(flatten,
+ 'utils.flatten: use array-flatten npm module instead');
+
+ /**
+ * Normalize the given `type`, for example "html" becomes "text/html".
+ *
+ * @param {String} type
+ * @return {Object}
+ * @api private
+ */
+
+ exports.normalizeType = function(type){
+ return ~type.indexOf('/')
+ ? acceptParams(type)
+ : { value: mime.lookup(type), params: {} };
+ };
+
+ /**
+ * Normalize `types`, for example "html" becomes "text/html".
+ *
+ * @param {Array} types
+ * @return {Array}
+ * @api private
+ */
+
+ exports.normalizeTypes = function(types){
+ var ret = [];
+
+ for (var i = 0; i < types.length; ++i) {
+ ret.push(exports.normalizeType(types[i]));
+ }
+
+ return ret;
+ };
+
+ /**
+ * Generate Content-Disposition header appropriate for the filename.
+ * non-ascii filenames are urlencoded and a filename* parameter is added
+ *
+ * @param {String} filename
+ * @return {String}
+ * @api private
+ */
+
+ exports.contentDisposition = deprecate.function(contentDisposition,
+ 'utils.contentDisposition: use content-disposition npm module instead');
+
+ /**
+ * Parse accept params `str` returning an
+ * object with `.value`, `.quality` and `.params`.
+ * also includes `.originalIndex` for stable sorting
+ *
+ * @param {String} str
+ * @param {Number} index
+ * @return {Object}
+ * @api private
+ */
+
+ function acceptParams(str, index) {
+ var parts = str.split(/ *; */);
+ var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };
+
+ for (var i = 1; i < parts.length; ++i) {
+ var pms = parts[i].split(/ *= */);
+ if ('q' === pms[0]) {
+ ret.quality = parseFloat(pms[1]);
+ } else {
+ ret.params[pms[0]] = pms[1];
+ }
+ }
+
+ return ret;
+ }
+
+ /**
+ * Compile "etag" value to function.
+ *
+ * @param {Boolean|String|Function} val
+ * @return {Function}
+ * @api private
+ */
+
+ exports.compileETag = function(val) {
+ var fn;
+
+ if (typeof val === 'function') {
+ return val;
+ }
+
+ switch (val) {
+ case true:
+ case 'weak':
+ fn = exports.wetag;
+ break;
+ case false:
+ break;
+ case 'strong':
+ fn = exports.etag;
+ break;
+ default:
+ throw new TypeError('unknown value for etag function: ' + val);
+ }
+
+ return fn;
+ };
+
+ /**
+ * Compile "query parser" value to function.
+ *
+ * @param {String|Function} val
+ * @return {Function}
+ * @api private
+ */
+
+ exports.compileQueryParser = function compileQueryParser(val) {
+ var fn;
+
+ if (typeof val === 'function') {
+ return val;
+ }
+
+ switch (val) {
+ case true:
+ case 'simple':
+ fn = querystring.parse;
+ break;
+ case false:
+ fn = newObject;
+ break;
+ case 'extended':
+ fn = parseExtendedQueryString;
+ break;
+ default:
+ throw new TypeError('unknown value for query parser function: ' + val);
+ }
+
+ return fn;
+ };
+
+ /**
+ * Compile "proxy trust" value to function.
+ *
+ * @param {Boolean|String|Number|Array|Function} val
+ * @return {Function}
+ * @api private
+ */
+
+ exports.compileTrust = function(val) {
+ if (typeof val === 'function') return val;
+
+ if (val === true) {
+ // Support plain true/false
+ return function(){ return true };
+ }
+
+ if (typeof val === 'number') {
+ // Support trusting hop count
+ return function(a, i){ return i < val };
+ }
+
+ if (typeof val === 'string') {
+ // Support comma-separated values
+ val = val.split(',')
+ .map(function (v) { return v.trim() });
+ }
+
+ return proxyaddr.compile(val || []);
+ };
+
+ /**
+ * Set the charset in a given Content-Type string.
+ *
+ * @param {String} type
+ * @param {String} charset
+ * @return {String}
+ * @api private
+ */
+
+ exports.setCharset = function setCharset(type, charset) {
+ if (!type || !charset) {
+ return type;
+ }
+
+ // parse type
+ var parsed = contentType$1.parse(type);
+
+ // set charset
+ parsed.parameters.charset = charset;
+
+ // format type
+ return contentType$1.format(parsed);
+ };
+
+ /**
+ * Create an ETag generator function, generating ETags with
+ * the given options.
+ *
+ * @param {object} options
+ * @return {function}
+ * @private
+ */
+
+ function createETagGenerator (options) {
+ return function generateETag (body, encoding) {
+ var buf = !Buffer.isBuffer(body)
+ ? Buffer.from(body, encoding)
+ : body;
+
+ return etag(buf, options)
+ }
+ }
+
+ /**
+ * Parse an extended query string with qs.
+ *
+ * @return {Object}
+ * @private
+ */
+
+ function parseExtendedQueryString(str) {
+ return qs.parse(str, {
+ allowPrototypes: true
+ });
+ }
+
+ /**
+ * Return new empty object.
+ *
+ * @return {Object}
+ * @api private
+ */
+
+ function newObject() {
+ return {};
+ }
+} (utils$3));
+
+/*!
+ * express
+ * Copyright(c) 2009-2013 TJ Holowaychuk
+ * Copyright(c) 2013 Roman Shtylman
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+(function (module, exports) {
+
+ /**
+ * Module dependencies.
+ * @private
+ */
+
+ var finalhandler = finalhandler_1;
+ var Router = routerExports;
+ var methods = methods$2;
+ var middleware = init;
+ var query$1 = query;
+ var debug = srcExports$1('express:application');
+ var View = view;
+ var http = http$6;
+ var compileETag = utils$3.compileETag;
+ var compileQueryParser = utils$3.compileQueryParser;
+ var compileTrust = utils$3.compileTrust;
+ var deprecate = depd_1('express');
+ var flatten = arrayFlatten_1;
+ var merge = utilsMergeExports;
+ var resolve = require$$0$c.resolve;
+ var setPrototypeOf = setprototypeof;
+
+ /**
+ * Module variables.
+ * @private
+ */
+
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ var slice = Array.prototype.slice;
+
+ /**
+ * Application prototype.
+ */
+
+ var app = module.exports = {};
+
+ /**
+ * Variable for trust proxy inheritance back-compat
+ * @private
+ */
+
+ var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
+
+ /**
+ * Initialize the server.
+ *
+ * - setup default configuration
+ * - setup default middleware
+ * - setup route reflection methods
+ *
+ * @private
+ */
+
+ app.init = function init() {
+ this.cache = {};
+ this.engines = {};
+ this.settings = {};
+
+ this.defaultConfiguration();
+ };
+
+ /**
+ * Initialize application configuration.
+ * @private
+ */
+
+ app.defaultConfiguration = function defaultConfiguration() {
+ var env = process.env.NODE_ENV || 'development';
+
+ // default settings
+ this.enable('x-powered-by');
+ this.set('etag', 'weak');
+ this.set('env', env);
+ this.set('query parser', 'extended');
+ this.set('subdomain offset', 2);
+ this.set('trust proxy', false);
+
+ // trust proxy inherit back-compat
+ Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
+ configurable: true,
+ value: true
+ });
+
+ debug('booting in %s mode', env);
+
+ this.on('mount', function onmount(parent) {
+ // inherit trust proxy
+ if (this.settings[trustProxyDefaultSymbol] === true
+ && typeof parent.settings['trust proxy fn'] === 'function') {
+ delete this.settings['trust proxy'];
+ delete this.settings['trust proxy fn'];
+ }
+
+ // inherit protos
+ setPrototypeOf(this.request, parent.request);
+ setPrototypeOf(this.response, parent.response);
+ setPrototypeOf(this.engines, parent.engines);
+ setPrototypeOf(this.settings, parent.settings);
+ });
+
+ // setup locals
+ this.locals = Object.create(null);
+
+ // top-most app is mounted at /
+ this.mountpath = '/';
+
+ // default locals
+ this.locals.settings = this.settings;
+
+ // default configuration
+ this.set('view', View);
+ this.set('views', resolve('views'));
+ this.set('jsonp callback name', 'callback');
+
+ if (env === 'production') {
+ this.enable('view cache');
+ }
+
+ Object.defineProperty(this, 'router', {
+ get: function() {
+ throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
+ }
+ });
+ };
+
+ /**
+ * lazily adds the base router if it has not yet been added.
+ *
+ * We cannot add the base router in the defaultConfiguration because
+ * it reads app settings which might be set after that has run.
+ *
+ * @private
+ */
+ app.lazyrouter = function lazyrouter() {
+ if (!this._router) {
+ this._router = new Router({
+ caseSensitive: this.enabled('case sensitive routing'),
+ strict: this.enabled('strict routing')
+ });
+
+ this._router.use(query$1(this.get('query parser fn')));
+ this._router.use(middleware.init(this));
+ }
+ };
+
+ /**
+ * Dispatch a req, res pair into the application. Starts pipeline processing.
+ *
+ * If no callback is provided, then default error handlers will respond
+ * in the event of an error bubbling through the stack.
+ *
+ * @private
+ */
+
+ app.handle = function handle(req, res, callback) {
+ var router = this._router;
+
+ // final handler
+ var done = callback || finalhandler(req, res, {
+ env: this.get('env'),
+ onerror: logerror.bind(this)
+ });
+
+ // no routes
+ if (!router) {
+ debug('no routes defined on app');
+ done();
+ return;
+ }
+
+ router.handle(req, res, done);
+ };
+
+ /**
+ * Proxy `Router#use()` to add middleware to the app router.
+ * See Router#use() documentation for details.
+ *
+ * If the _fn_ parameter is an express app, then it will be
+ * mounted at the _route_ specified.
+ *
+ * @public
+ */
+
+ app.use = function use(fn) {
+ var offset = 0;
+ var path = '/';
+
+ // default path to '/'
+ // disambiguate app.use([fn])
+ if (typeof fn !== 'function') {
+ var arg = fn;
+
+ while (Array.isArray(arg) && arg.length !== 0) {
+ arg = arg[0];
+ }
+
+ // first arg is the path
+ if (typeof arg !== 'function') {
+ offset = 1;
+ path = fn;
+ }
+ }
+
+ var fns = flatten(slice.call(arguments, offset));
+
+ if (fns.length === 0) {
+ throw new TypeError('app.use() requires a middleware function')
+ }
+
+ // setup router
+ this.lazyrouter();
+ var router = this._router;
+
+ fns.forEach(function (fn) {
+ // non-express app
+ if (!fn || !fn.handle || !fn.set) {
+ return router.use(path, fn);
+ }
+
+ debug('.use app under %s', path);
+ fn.mountpath = path;
+ fn.parent = this;
+
+ // restore .app property on req and res
+ router.use(path, function mounted_app(req, res, next) {
+ var orig = req.app;
+ fn.handle(req, res, function (err) {
+ setPrototypeOf(req, orig.request);
+ setPrototypeOf(res, orig.response);
+ next(err);
+ });
+ });
+
+ // mounted an app
+ fn.emit('mount', this);
+ }, this);
+
+ return this;
+ };
+
+ /**
+ * Proxy to the app `Router#route()`
+ * Returns a new `Route` instance for the _path_.
+ *
+ * Routes are isolated middleware stacks for specific paths.
+ * See the Route api docs for details.
+ *
+ * @public
+ */
+
+ app.route = function route(path) {
+ this.lazyrouter();
+ return this._router.route(path);
+ };
+
+ /**
+ * Register the given template engine callback `fn`
+ * as `ext`.
+ *
+ * By default will `require()` the engine based on the
+ * file extension. For example if you try to render
+ * a "foo.ejs" file Express will invoke the following internally:
+ *
+ * app.engine('ejs', require('ejs').__express);
+ *
+ * For engines that do not provide `.__express` out of the box,
+ * or if you wish to "map" a different extension to the template engine
+ * you may use this method. For example mapping the EJS template engine to
+ * ".html" files:
+ *
+ * app.engine('html', require('ejs').renderFile);
+ *
+ * In this case EJS provides a `.renderFile()` method with
+ * the same signature that Express expects: `(path, options, callback)`,
+ * though note that it aliases this method as `ejs.__express` internally
+ * so if you're using ".ejs" extensions you don't need to do anything.
+ *
+ * Some template engines do not follow this convention, the
+ * [Consolidate.js](https://github.com/tj/consolidate.js)
+ * library was created to map all of node's popular template
+ * engines to follow this convention, thus allowing them to
+ * work seamlessly within Express.
+ *
+ * @param {String} ext
+ * @param {Function} fn
+ * @return {app} for chaining
+ * @public
+ */
+
+ app.engine = function engine(ext, fn) {
+ if (typeof fn !== 'function') {
+ throw new Error('callback function required');
+ }
+
+ // get file extension
+ var extension = ext[0] !== '.'
+ ? '.' + ext
+ : ext;
+
+ // store engine
+ this.engines[extension] = fn;
+
+ return this;
+ };
+
+ /**
+ * Proxy to `Router#param()` with one added api feature. The _name_ parameter
+ * can be an array of names.
+ *
+ * See the Router#param() docs for more details.
+ *
+ * @param {String|Array} name
+ * @param {Function} fn
+ * @return {app} for chaining
+ * @public
+ */
+
+ app.param = function param(name, fn) {
+ this.lazyrouter();
+
+ if (Array.isArray(name)) {
+ for (var i = 0; i < name.length; i++) {
+ this.param(name[i], fn);
+ }
+
+ return this;
+ }
+
+ this._router.param(name, fn);
+
+ return this;
+ };
+
+ /**
+ * Assign `setting` to `val`, or return `setting`'s value.
+ *
+ * app.set('foo', 'bar');
+ * app.set('foo');
+ * // => "bar"
+ *
+ * Mounted servers inherit their parent server's settings.
+ *
+ * @param {String} setting
+ * @param {*} [val]
+ * @return {Server} for chaining
+ * @public
+ */
+
+ app.set = function set(setting, val) {
+ if (arguments.length === 1) {
+ // app.get(setting)
+ var settings = this.settings;
+
+ while (settings && settings !== Object.prototype) {
+ if (hasOwnProperty.call(settings, setting)) {
+ return settings[setting]
+ }
+
+ settings = Object.getPrototypeOf(settings);
+ }
+
+ return undefined
+ }
+
+ debug('set "%s" to %o', setting, val);
+
+ // set value
+ this.settings[setting] = val;
+
+ // trigger matched settings
+ switch (setting) {
+ case 'etag':
+ this.set('etag fn', compileETag(val));
+ break;
+ case 'query parser':
+ this.set('query parser fn', compileQueryParser(val));
+ break;
+ case 'trust proxy':
+ this.set('trust proxy fn', compileTrust(val));
+
+ // trust proxy inherit back-compat
+ Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
+ configurable: true,
+ value: false
+ });
+
+ break;
+ }
+
+ return this;
+ };
+
+ /**
+ * Return the app's absolute pathname
+ * based on the parent(s) that have
+ * mounted it.
+ *
+ * For example if the application was
+ * mounted as "/admin", which itself
+ * was mounted as "/blog" then the
+ * return value would be "/blog/admin".
+ *
+ * @return {String}
+ * @private
+ */
+
+ app.path = function path() {
+ return this.parent
+ ? this.parent.path() + this.mountpath
+ : '';
+ };
+
+ /**
+ * Check if `setting` is enabled (truthy).
+ *
+ * app.enabled('foo')
+ * // => false
+ *
+ * app.enable('foo')
+ * app.enabled('foo')
+ * // => true
+ *
+ * @param {String} setting
+ * @return {Boolean}
+ * @public
+ */
+
+ app.enabled = function enabled(setting) {
+ return Boolean(this.set(setting));
+ };
+
+ /**
+ * Check if `setting` is disabled.
+ *
+ * app.disabled('foo')
+ * // => true
+ *
+ * app.enable('foo')
+ * app.disabled('foo')
+ * // => false
+ *
+ * @param {String} setting
+ * @return {Boolean}
+ * @public
+ */
+
+ app.disabled = function disabled(setting) {
+ return !this.set(setting);
+ };
+
+ /**
+ * Enable `setting`.
+ *
+ * @param {String} setting
+ * @return {app} for chaining
+ * @public
+ */
+
+ app.enable = function enable(setting) {
+ return this.set(setting, true);
+ };
+
+ /**
+ * Disable `setting`.
+ *
+ * @param {String} setting
+ * @return {app} for chaining
+ * @public
+ */
+
+ app.disable = function disable(setting) {
+ return this.set(setting, false);
+ };
+
+ /**
+ * Delegate `.VERB(...)` calls to `router.VERB(...)`.
+ */
+
+ methods.forEach(function(method){
+ app[method] = function(path){
+ if (method === 'get' && arguments.length === 1) {
+ // app.get(setting)
+ return this.set(path);
+ }
+
+ this.lazyrouter();
+
+ var route = this._router.route(path);
+ route[method].apply(route, slice.call(arguments, 1));
+ return this;
+ };
+ });
+
+ /**
+ * Special-cased "all" method, applying the given route `path`,
+ * middleware, and callback to _every_ HTTP method.
+ *
+ * @param {String} path
+ * @param {Function} ...
+ * @return {app} for chaining
+ * @public
+ */
+
+ app.all = function all(path) {
+ this.lazyrouter();
+
+ var route = this._router.route(path);
+ var args = slice.call(arguments, 1);
+
+ for (var i = 0; i < methods.length; i++) {
+ route[methods[i]].apply(route, args);
+ }
+
+ return this;
+ };
+
+ // del -> delete alias
+
+ app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
+
+ /**
+ * Render the given view `name` name with `options`
+ * and a callback accepting an error and the
+ * rendered template string.
+ *
+ * Example:
+ *
+ * app.render('email', { name: 'Tobi' }, function(err, html){
+ * // ...
+ * })
+ *
+ * @param {String} name
+ * @param {Object|Function} options or fn
+ * @param {Function} callback
+ * @public
+ */
+
+ app.render = function render(name, options, callback) {
+ var cache = this.cache;
+ var done = callback;
+ var engines = this.engines;
+ var opts = options;
+ var renderOptions = {};
+ var view;
+
+ // support callback function as second arg
+ if (typeof options === 'function') {
+ done = options;
+ opts = {};
+ }
+
+ // merge app.locals
+ merge(renderOptions, this.locals);
+
+ // merge options._locals
+ if (opts._locals) {
+ merge(renderOptions, opts._locals);
+ }
+
+ // merge options
+ merge(renderOptions, opts);
+
+ // set .cache unless explicitly provided
+ if (renderOptions.cache == null) {
+ renderOptions.cache = this.enabled('view cache');
+ }
+
+ // primed cache
+ if (renderOptions.cache) {
+ view = cache[name];
+ }
+
+ // view
+ if (!view) {
+ var View = this.get('view');
+
+ view = new View(name, {
+ defaultEngine: this.get('view engine'),
+ root: this.get('views'),
+ engines: engines
+ });
+
+ if (!view.path) {
+ var dirs = Array.isArray(view.root) && view.root.length > 1
+ ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
+ : 'directory "' + view.root + '"';
+ var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
+ err.view = view;
+ return done(err);
+ }
+
+ // prime the cache
+ if (renderOptions.cache) {
+ cache[name] = view;
+ }
+ }
+
+ // render
+ tryRender(view, renderOptions, done);
+ };
+
+ /**
+ * Listen for connections.
+ *
+ * A node `http.Server` is returned, with this
+ * application (which is a `Function`) as its
+ * callback. If you wish to create both an HTTP
+ * and HTTPS server you may do so with the "http"
+ * and "https" modules as shown here:
+ *
+ * var http = require('http')
+ * , https = require('https')
+ * , express = require('express')
+ * , app = express();
+ *
+ * http.createServer(app).listen(80);
+ * https.createServer({ ... }, app).listen(443);
+ *
+ * @return {http.Server}
+ * @public
+ */
+
+ app.listen = function listen() {
+ var server = http.createServer(this);
+ return server.listen.apply(server, arguments);
+ };
+
+ /**
+ * Log error using console.error.
+ *
+ * @param {Error} err
+ * @private
+ */
+
+ function logerror(err) {
+ /* istanbul ignore next */
+ if (this.get('env') !== 'test') console.error(err.stack || err.toString());
+ }
+
+ /**
+ * Try rendering a view.
+ * @private
+ */
+
+ function tryRender(view, options, callback) {
+ try {
+ view.render(options, callback);
+ } catch (err) {
+ callback(err);
+ }
+ }
+} (application));
+
+var negotiatorExports = {};
+var negotiator = {
+ get exports(){ return negotiatorExports; },
+ set exports(v){ negotiatorExports = v; },
+};
+
+var charsetExports = {};
+var charset = {
+ get exports(){ return charsetExports; },
+ set exports(v){ charsetExports = v; },
+};
+
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+charset.exports = preferredCharsets$1;
+charsetExports.preferredCharsets = preferredCharsets$1;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
+
+/**
+ * Parse the Accept-Charset header.
+ * @private
+ */
+
+function parseAcceptCharset(accept) {
+ var accepts = accept.split(',');
+
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var charset = parseCharset(accepts[i].trim(), i);
+
+ if (charset) {
+ accepts[j++] = charset;
+ }
+ }
+
+ // trim accepts
+ accepts.length = j;
+
+ return accepts;
+}
+
+/**
+ * Parse a charset from the Accept-Charset header.
+ * @private
+ */
+
+function parseCharset(str, i) {
+ var match = simpleCharsetRegExp.exec(str);
+ if (!match) return null;
+
+ var charset = match[1];
+ var q = 1;
+ if (match[2]) {
+ var params = match[2].split(';');
+ for (var j = 0; j < params.length; j++) {
+ var p = params[j].trim().split('=');
+ if (p[0] === 'q') {
+ q = parseFloat(p[1]);
+ break;
+ }
+ }
+ }
+
+ return {
+ charset: charset,
+ q: q,
+ i: i
+ };
+}
+
+/**
+ * Get the priority of a charset.
+ * @private
+ */
+
+function getCharsetPriority(charset, accepted, index) {
+ var priority = {o: -1, q: 0, s: 0};
+
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify$3(charset, accepted[i], index);
+
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+
+ return priority;
+}
+
+/**
+ * Get the specificity of the charset.
+ * @private
+ */
+
+function specify$3(charset, spec, index) {
+ var s = 0;
+ if(spec.charset.toLowerCase() === charset.toLowerCase()){
+ s |= 1;
+ } else if (spec.charset !== '*' ) {
+ return null
+ }
+
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s: s
+ }
+}
+
+/**
+ * Get the preferred charsets from an Accept-Charset header.
+ * @public
+ */
+
+function preferredCharsets$1(accept, provided) {
+ // RFC 2616 sec 14.2: no header = *
+ var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');
+
+ if (!provided) {
+ // sorted list of all charsets
+ return accepts
+ .filter(isQuality$3)
+ .sort(compareSpecs$3)
+ .map(getFullCharset);
+ }
+
+ var priorities = provided.map(function getPriority(type, index) {
+ return getCharsetPriority(type, accepts, index);
+ });
+
+ // sorted list of accepted charsets
+ return priorities.filter(isQuality$3).sort(compareSpecs$3).map(function getCharset(priority) {
+ return provided[priorities.indexOf(priority)];
+ });
+}
+
+/**
+ * Compare two specs.
+ * @private
+ */
+
+function compareSpecs$3(a, b) {
+ return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+}
+
+/**
+ * Get full charset string.
+ * @private
+ */
+
+function getFullCharset(spec) {
+ return spec.charset;
+}
+
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
+
+function isQuality$3(spec) {
+ return spec.q > 0;
+}
+
+var encodingExports = {};
+var encoding = {
+ get exports(){ return encodingExports; },
+ set exports(v){ encodingExports = v; },
+};
+
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+encoding.exports = preferredEncodings$1;
+encodingExports.preferredEncodings = preferredEncodings$1;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
+
+/**
+ * Parse the Accept-Encoding header.
+ * @private
+ */
+
+function parseAcceptEncoding(accept) {
+ var accepts = accept.split(',');
+ var hasIdentity = false;
+ var minQuality = 1;
+
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var encoding = parseEncoding(accepts[i].trim(), i);
+
+ if (encoding) {
+ accepts[j++] = encoding;
+ hasIdentity = hasIdentity || specify$2('identity', encoding);
+ minQuality = Math.min(minQuality, encoding.q || 1);
+ }
+ }
+
+ if (!hasIdentity) {
+ /*
+ * If identity doesn't explicitly appear in the accept-encoding header,
+ * it's added to the list of acceptable encoding with the lowest q
+ */
+ accepts[j++] = {
+ encoding: 'identity',
+ q: minQuality,
+ i: i
+ };
+ }
+
+ // trim accepts
+ accepts.length = j;
+
+ return accepts;
+}
+
+/**
+ * Parse an encoding from the Accept-Encoding header.
+ * @private
+ */
+
+function parseEncoding(str, i) {
+ var match = simpleEncodingRegExp.exec(str);
+ if (!match) return null;
+
+ var encoding = match[1];
+ var q = 1;
+ if (match[2]) {
+ var params = match[2].split(';');
+ for (var j = 0; j < params.length; j++) {
+ var p = params[j].trim().split('=');
+ if (p[0] === 'q') {
+ q = parseFloat(p[1]);
+ break;
+ }
+ }
+ }
+
+ return {
+ encoding: encoding,
+ q: q,
+ i: i
+ };
+}
+
+/**
+ * Get the priority of an encoding.
+ * @private
+ */
+
+function getEncodingPriority(encoding, accepted, index) {
+ var priority = {o: -1, q: 0, s: 0};
+
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify$2(encoding, accepted[i], index);
+
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+
+ return priority;
+}
+
+/**
+ * Get the specificity of the encoding.
+ * @private
+ */
+
+function specify$2(encoding, spec, index) {
+ var s = 0;
+ if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
+ s |= 1;
+ } else if (spec.encoding !== '*' ) {
+ return null
+ }
+
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s: s
+ }
+}
+/**
+ * Get the preferred encodings from an Accept-Encoding header.
+ * @public
+ */
+
+function preferredEncodings$1(accept, provided) {
+ var accepts = parseAcceptEncoding(accept || '');
+
+ if (!provided) {
+ // sorted list of all encodings
+ return accepts
+ .filter(isQuality$2)
+ .sort(compareSpecs$2)
+ .map(getFullEncoding);
+ }
+
+ var priorities = provided.map(function getPriority(type, index) {
+ return getEncodingPriority(type, accepts, index);
+ });
+
+ // sorted list of accepted encodings
+ return priorities.filter(isQuality$2).sort(compareSpecs$2).map(function getEncoding(priority) {
+ return provided[priorities.indexOf(priority)];
+ });
+}
+
+/**
+ * Compare two specs.
+ * @private
+ */
+
+function compareSpecs$2(a, b) {
+ return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+}
+
+/**
+ * Get full encoding string.
+ * @private
+ */
+
+function getFullEncoding(spec) {
+ return spec.encoding;
+}
+
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
+
+function isQuality$2(spec) {
+ return spec.q > 0;
+}
+
+var languageExports = {};
+var language = {
+ get exports(){ return languageExports; },
+ set exports(v){ languageExports = v; },
+};
+
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+language.exports = preferredLanguages$1;
+languageExports.preferredLanguages = preferredLanguages$1;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
+
+/**
+ * Parse the Accept-Language header.
+ * @private
+ */
+
+function parseAcceptLanguage(accept) {
+ var accepts = accept.split(',');
+
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var language = parseLanguage(accepts[i].trim(), i);
+
+ if (language) {
+ accepts[j++] = language;
+ }
+ }
+
+ // trim accepts
+ accepts.length = j;
+
+ return accepts;
+}
+
+/**
+ * Parse a language from the Accept-Language header.
+ * @private
+ */
+
+function parseLanguage(str, i) {
+ var match = simpleLanguageRegExp.exec(str);
+ if (!match) return null;
+
+ var prefix = match[1];
+ var suffix = match[2];
+ var full = prefix;
+
+ if (suffix) full += "-" + suffix;
+
+ var q = 1;
+ if (match[3]) {
+ var params = match[3].split(';');
+ for (var j = 0; j < params.length; j++) {
+ var p = params[j].split('=');
+ if (p[0] === 'q') q = parseFloat(p[1]);
+ }
+ }
+
+ return {
+ prefix: prefix,
+ suffix: suffix,
+ q: q,
+ i: i,
+ full: full
+ };
+}
+
+/**
+ * Get the priority of a language.
+ * @private
+ */
+
+function getLanguagePriority(language, accepted, index) {
+ var priority = {o: -1, q: 0, s: 0};
+
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify$1(language, accepted[i], index);
+
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+
+ return priority;
+}
+
+/**
+ * Get the specificity of the language.
+ * @private
+ */
+
+function specify$1(language, spec, index) {
+ var p = parseLanguage(language);
+ if (!p) return null;
+ var s = 0;
+ if(spec.full.toLowerCase() === p.full.toLowerCase()){
+ s |= 4;
+ } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
+ s |= 2;
+ } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
+ s |= 1;
+ } else if (spec.full !== '*' ) {
+ return null
+ }
+
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s: s
+ }
+}
+/**
+ * Get the preferred languages from an Accept-Language header.
+ * @public
+ */
+
+function preferredLanguages$1(accept, provided) {
+ // RFC 2616 sec 14.4: no header = *
+ var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');
+
+ if (!provided) {
+ // sorted list of all languages
+ return accepts
+ .filter(isQuality$1)
+ .sort(compareSpecs$1)
+ .map(getFullLanguage);
+ }
+
+ var priorities = provided.map(function getPriority(type, index) {
+ return getLanguagePriority(type, accepts, index);
+ });
+
+ // sorted list of accepted languages
+ return priorities.filter(isQuality$1).sort(compareSpecs$1).map(function getLanguage(priority) {
+ return provided[priorities.indexOf(priority)];
+ });
+}
+
+/**
+ * Compare two specs.
+ * @private
+ */
+
+function compareSpecs$1(a, b) {
+ return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+}
+
+/**
+ * Get full language string.
+ * @private
+ */
+
+function getFullLanguage(spec) {
+ return spec.full;
+}
+
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
+
+function isQuality$1(spec) {
+ return spec.q > 0;
+}
+
+var mediaTypeExports = {};
+var mediaType = {
+ get exports(){ return mediaTypeExports; },
+ set exports(v){ mediaTypeExports = v; },
+};
+
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+mediaType.exports = preferredMediaTypes$1;
+mediaTypeExports.preferredMediaTypes = preferredMediaTypes$1;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
+
+/**
+ * Parse the Accept header.
+ * @private
+ */
+
+function parseAccept(accept) {
+ var accepts = splitMediaTypes(accept);
+
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var mediaType = parseMediaType(accepts[i].trim(), i);
+
+ if (mediaType) {
+ accepts[j++] = mediaType;
+ }
+ }
+
+ // trim accepts
+ accepts.length = j;
+
+ return accepts;
+}
+
+/**
+ * Parse a media type from the Accept header.
+ * @private
+ */
+
+function parseMediaType(str, i) {
+ var match = simpleMediaTypeRegExp.exec(str);
+ if (!match) return null;
+
+ var params = Object.create(null);
+ var q = 1;
+ var subtype = match[2];
+ var type = match[1];
+
+ if (match[3]) {
+ var kvps = splitParameters(match[3]).map(splitKeyValuePair);
+
+ for (var j = 0; j < kvps.length; j++) {
+ var pair = kvps[j];
+ var key = pair[0].toLowerCase();
+ var val = pair[1];
+
+ // get the value, unwrapping quotes
+ var value = val && val[0] === '"' && val[val.length - 1] === '"'
+ ? val.substr(1, val.length - 2)
+ : val;
+
+ if (key === 'q') {
+ q = parseFloat(value);
+ break;
+ }
+
+ // store parameter
+ params[key] = value;
+ }
+ }
+
+ return {
+ type: type,
+ subtype: subtype,
+ params: params,
+ q: q,
+ i: i
+ };
+}
+
+/**
+ * Get the priority of a media type.
+ * @private
+ */
+
+function getMediaTypePriority(type, accepted, index) {
+ var priority = {o: -1, q: 0, s: 0};
+
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify(type, accepted[i], index);
+
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+
+ return priority;
+}
+
+/**
+ * Get the specificity of the media type.
+ * @private
+ */
+
+function specify(type, spec, index) {
+ var p = parseMediaType(type);
+ var s = 0;
+
+ if (!p) {
+ return null;
+ }
+
+ if(spec.type.toLowerCase() == p.type.toLowerCase()) {
+ s |= 4;
+ } else if(spec.type != '*') {
+ return null;
+ }
+
+ if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
+ s |= 2;
+ } else if(spec.subtype != '*') {
+ return null;
+ }
+
+ var keys = Object.keys(spec.params);
+ if (keys.length > 0) {
+ if (keys.every(function (k) {
+ return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
+ })) {
+ s |= 1;
+ } else {
+ return null
+ }
+ }
+
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s: s,
+ }
+}
+
+/**
+ * Get the preferred media types from an Accept header.
+ * @public
+ */
+
+function preferredMediaTypes$1(accept, provided) {
+ // RFC 2616 sec 14.2: no header = */*
+ var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');
+
+ if (!provided) {
+ // sorted list of all types
+ return accepts
+ .filter(isQuality)
+ .sort(compareSpecs)
+ .map(getFullType);
+ }
+
+ var priorities = provided.map(function getPriority(type, index) {
+ return getMediaTypePriority(type, accepts, index);
+ });
+
+ // sorted list of accepted types
+ return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
+ return provided[priorities.indexOf(priority)];
+ });
+}
+
+/**
+ * Compare two specs.
+ * @private
+ */
+
+function compareSpecs(a, b) {
+ return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+}
+
+/**
+ * Get full type string.
+ * @private
+ */
+
+function getFullType(spec) {
+ return spec.type + '/' + spec.subtype;
+}
+
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
+
+function isQuality(spec) {
+ return spec.q > 0;
+}
+
+/**
+ * Count the number of quotes in a string.
+ * @private
+ */
+
+function quoteCount(string) {
+ var count = 0;
+ var index = 0;
+
+ while ((index = string.indexOf('"', index)) !== -1) {
+ count++;
+ index++;
+ }
+
+ return count;
+}
+
+/**
+ * Split a key value pair.
+ * @private
+ */
+
+function splitKeyValuePair(str) {
+ var index = str.indexOf('=');
+ var key;
+ var val;
+
+ if (index === -1) {
+ key = str;
+ } else {
+ key = str.substr(0, index);
+ val = str.substr(index + 1);
+ }
+
+ return [key, val];
+}
+
+/**
+ * Split an Accept header into media types.
+ * @private
+ */
+
+function splitMediaTypes(accept) {
+ var accepts = accept.split(',');
+
+ for (var i = 1, j = 0; i < accepts.length; i++) {
+ if (quoteCount(accepts[j]) % 2 == 0) {
+ accepts[++j] = accepts[i];
+ } else {
+ accepts[j] += ',' + accepts[i];
+ }
+ }
+
+ // trim accepts
+ accepts.length = j + 1;
+
+ return accepts;
+}
+
+/**
+ * Split a string of parameters.
+ * @private
+ */
+
+function splitParameters(str) {
+ var parameters = str.split(';');
+
+ for (var i = 1, j = 0; i < parameters.length; i++) {
+ if (quoteCount(parameters[j]) % 2 == 0) {
+ parameters[++j] = parameters[i];
+ } else {
+ parameters[j] += ';' + parameters[i];
+ }
+ }
+
+ // trim parameters
+ parameters.length = j + 1;
+
+ for (var i = 0; i < parameters.length; i++) {
+ parameters[i] = parameters[i].trim();
+ }
+
+ return parameters;
+}
+
+/*!
+ * negotiator
+ * Copyright(c) 2012 Federico Romero
+ * Copyright(c) 2012-2014 Isaac Z. Schlueter
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+var preferredCharsets = charsetExports;
+var preferredEncodings = encodingExports;
+var preferredLanguages = languageExports;
+var preferredMediaTypes = mediaTypeExports;
+
+/**
+ * Module exports.
+ * @public
+ */
+
+negotiator.exports = Negotiator$1;
+negotiatorExports.Negotiator = Negotiator$1;
+
+/**
+ * Create a Negotiator instance from a request.
+ * @param {object} request
+ * @public
+ */
+
+function Negotiator$1(request) {
+ if (!(this instanceof Negotiator$1)) {
+ return new Negotiator$1(request);
+ }
+
+ this.request = request;
+}
+
+Negotiator$1.prototype.charset = function charset(available) {
+ var set = this.charsets(available);
+ return set && set[0];
+};
+
+Negotiator$1.prototype.charsets = function charsets(available) {
+ return preferredCharsets(this.request.headers['accept-charset'], available);
+};
+
+Negotiator$1.prototype.encoding = function encoding(available) {
+ var set = this.encodings(available);
+ return set && set[0];
+};
+
+Negotiator$1.prototype.encodings = function encodings(available) {
+ return preferredEncodings(this.request.headers['accept-encoding'], available);
+};
+
+Negotiator$1.prototype.language = function language(available) {
+ var set = this.languages(available);
+ return set && set[0];
+};
+
+Negotiator$1.prototype.languages = function languages(available) {
+ return preferredLanguages(this.request.headers['accept-language'], available);
+};
+
+Negotiator$1.prototype.mediaType = function mediaType(available) {
+ var set = this.mediaTypes(available);
+ return set && set[0];
+};
+
+Negotiator$1.prototype.mediaTypes = function mediaTypes(available) {
+ return preferredMediaTypes(this.request.headers.accept, available);
+};
+
+// Backwards compatibility
+Negotiator$1.prototype.preferredCharset = Negotiator$1.prototype.charset;
+Negotiator$1.prototype.preferredCharsets = Negotiator$1.prototype.charsets;
+Negotiator$1.prototype.preferredEncoding = Negotiator$1.prototype.encoding;
+Negotiator$1.prototype.preferredEncodings = Negotiator$1.prototype.encodings;
+Negotiator$1.prototype.preferredLanguage = Negotiator$1.prototype.language;
+Negotiator$1.prototype.preferredLanguages = Negotiator$1.prototype.languages;
+Negotiator$1.prototype.preferredMediaType = Negotiator$1.prototype.mediaType;
+Negotiator$1.prototype.preferredMediaTypes = Negotiator$1.prototype.mediaTypes;
+
+/*!
+ * accepts
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var Negotiator = negotiatorExports;
+var mime$2 = mimeTypes;
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var accepts$1 = Accepts;
+
+/**
+ * Create a new Accepts object for the given req.
+ *
+ * @param {object} req
+ * @public
+ */
+
+function Accepts (req) {
+ if (!(this instanceof Accepts)) {
+ return new Accepts(req)
+ }
+
+ this.headers = req.headers;
+ this.negotiator = new Negotiator(req);
+}
+
+/**
+ * Check if the given `type(s)` is acceptable, returning
+ * the best match when true, otherwise `undefined`, in which
+ * case you should respond with 406 "Not Acceptable".
+ *
+ * The `type` value may be a single mime type string
+ * such as "application/json", the extension name
+ * such as "json" or an array `["json", "html", "text/plain"]`. When a list
+ * or array is given the _best_ match, if any is returned.
+ *
+ * Examples:
+ *
+ * // Accept: text/html
+ * this.types('html');
+ * // => "html"
+ *
+ * // Accept: text/*, application/json
+ * this.types('html');
+ * // => "html"
+ * this.types('text/html');
+ * // => "text/html"
+ * this.types('json', 'text');
+ * // => "json"
+ * this.types('application/json');
+ * // => "application/json"
+ *
+ * // Accept: text/*, application/json
+ * this.types('image/png');
+ * this.types('png');
+ * // => undefined
+ *
+ * // Accept: text/*;q=.5, application/json
+ * this.types(['html', 'json']);
+ * this.types('html', 'json');
+ * // => "json"
+ *
+ * @param {String|Array} types...
+ * @return {String|Array|Boolean}
+ * @public
+ */
+
+Accepts.prototype.type =
+Accepts.prototype.types = function (types_) {
+ var types = types_;
+
+ // support flattened arguments
+ if (types && !Array.isArray(types)) {
+ types = new Array(arguments.length);
+ for (var i = 0; i < types.length; i++) {
+ types[i] = arguments[i];
+ }
+ }
+
+ // no types, return all requested types
+ if (!types || types.length === 0) {
+ return this.negotiator.mediaTypes()
+ }
+
+ // no accept header, return first given type
+ if (!this.headers.accept) {
+ return types[0]
+ }
+
+ var mimes = types.map(extToMime);
+ var accepts = this.negotiator.mediaTypes(mimes.filter(validMime));
+ var first = accepts[0];
+
+ return first
+ ? types[mimes.indexOf(first)]
+ : false
+};
+
+/**
+ * Return accepted encodings or best fit based on `encodings`.
+ *
+ * Given `Accept-Encoding: gzip, deflate`
+ * an array sorted by quality is returned:
+ *
+ * ['gzip', 'deflate']
+ *
+ * @param {String|Array} encodings...
+ * @return {String|Array}
+ * @public
+ */
+
+Accepts.prototype.encoding =
+Accepts.prototype.encodings = function (encodings_) {
+ var encodings = encodings_;
+
+ // support flattened arguments
+ if (encodings && !Array.isArray(encodings)) {
+ encodings = new Array(arguments.length);
+ for (var i = 0; i < encodings.length; i++) {
+ encodings[i] = arguments[i];
+ }
+ }
+
+ // no encodings, return all requested encodings
+ if (!encodings || encodings.length === 0) {
+ return this.negotiator.encodings()
+ }
+
+ return this.negotiator.encodings(encodings)[0] || false
+};
+
+/**
+ * Return accepted charsets or best fit based on `charsets`.
+ *
+ * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
+ * an array sorted by quality is returned:
+ *
+ * ['utf-8', 'utf-7', 'iso-8859-1']
+ *
+ * @param {String|Array} charsets...
+ * @return {String|Array}
+ * @public
+ */
+
+Accepts.prototype.charset =
+Accepts.prototype.charsets = function (charsets_) {
+ var charsets = charsets_;
+
+ // support flattened arguments
+ if (charsets && !Array.isArray(charsets)) {
+ charsets = new Array(arguments.length);
+ for (var i = 0; i < charsets.length; i++) {
+ charsets[i] = arguments[i];
+ }
+ }
+
+ // no charsets, return all requested charsets
+ if (!charsets || charsets.length === 0) {
+ return this.negotiator.charsets()
+ }
+
+ return this.negotiator.charsets(charsets)[0] || false
+};
+
+/**
+ * Return accepted languages or best fit based on `langs`.
+ *
+ * Given `Accept-Language: en;q=0.8, es, pt`
+ * an array sorted by quality is returned:
+ *
+ * ['es', 'pt', 'en']
+ *
+ * @param {String|Array} langs...
+ * @return {Array|String}
+ * @public
+ */
+
+Accepts.prototype.lang =
+Accepts.prototype.langs =
+Accepts.prototype.language =
+Accepts.prototype.languages = function (languages_) {
+ var languages = languages_;
+
+ // support flattened arguments
+ if (languages && !Array.isArray(languages)) {
+ languages = new Array(arguments.length);
+ for (var i = 0; i < languages.length; i++) {
+ languages[i] = arguments[i];
+ }
+ }
+
+ // no languages, return all requested languages
+ if (!languages || languages.length === 0) {
+ return this.negotiator.languages()
+ }
+
+ return this.negotiator.languages(languages)[0] || false
+};
+
+/**
+ * Convert extnames to mime.
+ *
+ * @param {String} type
+ * @return {String}
+ * @private
+ */
+
+function extToMime (type) {
+ return type.indexOf('/') === -1
+ ? mime$2.lookup(type)
+ : type
+}
+
+/**
+ * Check if mime is valid.
+ *
+ * @param {String} type
+ * @return {String}
+ * @private
+ */
+
+function validMime (type) {
+ return typeof type === 'string'
+}
+
+/*!
+ * express
+ * Copyright(c) 2009-2013 TJ Holowaychuk
+ * Copyright(c) 2013 Roman Shtylman
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var accepts = accepts$1;
+var deprecate$1 = depd_1('express');
+var isIP$1 = require$$4$2.isIP;
+var typeis = typeIsExports;
+var http$4 = http$6;
+var fresh = fresh_1;
+var parseRange = rangeParser_1;
+var parse$8 = parseurlExports;
+var proxyaddr = proxyAddrExports;
+
+/**
+ * Request prototype.
+ * @public
+ */
+
+var req$2 = Object.create(http$4.IncomingMessage.prototype);
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var request = req$2;
+
+/**
+ * Return request header.
+ *
+ * The `Referrer` header field is special-cased,
+ * both `Referrer` and `Referer` are interchangeable.
+ *
+ * Examples:
+ *
+ * req.get('Content-Type');
+ * // => "text/plain"
+ *
+ * req.get('content-type');
+ * // => "text/plain"
+ *
+ * req.get('Something');
+ * // => undefined
+ *
+ * Aliased as `req.header()`.
+ *
+ * @param {String} name
+ * @return {String}
+ * @public
+ */
+
+req$2.get =
+req$2.header = function header(name) {
+ if (!name) {
+ throw new TypeError('name argument is required to req.get');
+ }
+
+ if (typeof name !== 'string') {
+ throw new TypeError('name must be a string to req.get');
+ }
+
+ var lc = name.toLowerCase();
+
+ switch (lc) {
+ case 'referer':
+ case 'referrer':
+ return this.headers.referrer
+ || this.headers.referer;
+ default:
+ return this.headers[lc];
+ }
+};
+
+/**
+ * To do: update docs.
+ *
+ * Check if the given `type(s)` is acceptable, returning
+ * the best match when true, otherwise `undefined`, in which
+ * case you should respond with 406 "Not Acceptable".
+ *
+ * The `type` value may be a single MIME type string
+ * such as "application/json", an extension name
+ * such as "json", a comma-delimited list such as "json, html, text/plain",
+ * an argument list such as `"json", "html", "text/plain"`,
+ * or an array `["json", "html", "text/plain"]`. When a list
+ * or array is given, the _best_ match, if any is returned.
+ *
+ * Examples:
+ *
+ * // Accept: text/html
+ * req.accepts('html');
+ * // => "html"
+ *
+ * // Accept: text/*, application/json
+ * req.accepts('html');
+ * // => "html"
+ * req.accepts('text/html');
+ * // => "text/html"
+ * req.accepts('json, text');
+ * // => "json"
+ * req.accepts('application/json');
+ * // => "application/json"
+ *
+ * // Accept: text/*, application/json
+ * req.accepts('image/png');
+ * req.accepts('png');
+ * // => undefined
+ *
+ * // Accept: text/*;q=.5, application/json
+ * req.accepts(['html', 'json']);
+ * req.accepts('html', 'json');
+ * req.accepts('html, json');
+ * // => "json"
+ *
+ * @param {String|Array} type(s)
+ * @return {String|Array|Boolean}
+ * @public
+ */
+
+req$2.accepts = function(){
+ var accept = accepts(this);
+ return accept.types.apply(accept, arguments);
+};
+
+/**
+ * Check if the given `encoding`s are accepted.
+ *
+ * @param {String} ...encoding
+ * @return {String|Array}
+ * @public
+ */
+
+req$2.acceptsEncodings = function(){
+ var accept = accepts(this);
+ return accept.encodings.apply(accept, arguments);
+};
+
+req$2.acceptsEncoding = deprecate$1.function(req$2.acceptsEncodings,
+ 'req.acceptsEncoding: Use acceptsEncodings instead');
+
+/**
+ * Check if the given `charset`s are acceptable,
+ * otherwise you should respond with 406 "Not Acceptable".
+ *
+ * @param {String} ...charset
+ * @return {String|Array}
+ * @public
+ */
+
+req$2.acceptsCharsets = function(){
+ var accept = accepts(this);
+ return accept.charsets.apply(accept, arguments);
+};
+
+req$2.acceptsCharset = deprecate$1.function(req$2.acceptsCharsets,
+ 'req.acceptsCharset: Use acceptsCharsets instead');
+
+/**
+ * Check if the given `lang`s are acceptable,
+ * otherwise you should respond with 406 "Not Acceptable".
+ *
+ * @param {String} ...lang
+ * @return {String|Array}
+ * @public
+ */
+
+req$2.acceptsLanguages = function(){
+ var accept = accepts(this);
+ return accept.languages.apply(accept, arguments);
+};
+
+req$2.acceptsLanguage = deprecate$1.function(req$2.acceptsLanguages,
+ 'req.acceptsLanguage: Use acceptsLanguages instead');
+
+/**
+ * Parse Range header field, capping to the given `size`.
+ *
+ * Unspecified ranges such as "0-" require knowledge of your resource length. In
+ * the case of a byte range this is of course the total number of bytes. If the
+ * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
+ * and `-2` when syntactically invalid.
+ *
+ * When ranges are returned, the array has a "type" property which is the type of
+ * range that is required (most commonly, "bytes"). Each array element is an object
+ * with a "start" and "end" property for the portion of the range.
+ *
+ * The "combine" option can be set to `true` and overlapping & adjacent ranges
+ * will be combined into a single range.
+ *
+ * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
+ * should respond with 4 users when available, not 3.
+ *
+ * @param {number} size
+ * @param {object} [options]
+ * @param {boolean} [options.combine=false]
+ * @return {number|array}
+ * @public
+ */
+
+req$2.range = function range(size, options) {
+ var range = this.get('Range');
+ if (!range) return;
+ return parseRange(size, range, options);
+};
+
+/**
+ * Return the value of param `name` when present or `defaultValue`.
+ *
+ * - Checks route placeholders, ex: _/user/:id_
+ * - Checks body params, ex: id=12, {"id":12}
+ * - Checks query string params, ex: ?id=12
+ *
+ * To utilize request bodies, `req.body`
+ * should be an object. This can be done by using
+ * the `bodyParser()` middleware.
+ *
+ * @param {String} name
+ * @param {Mixed} [defaultValue]
+ * @return {String}
+ * @public
+ */
+
+req$2.param = function param(name, defaultValue) {
+ var params = this.params || {};
+ var body = this.body || {};
+ var query = this.query || {};
+
+ var args = arguments.length === 1
+ ? 'name'
+ : 'name, default';
+ deprecate$1('req.param(' + args + '): Use req.params, req.body, or req.query instead');
+
+ if (null != params[name] && params.hasOwnProperty(name)) return params[name];
+ if (null != body[name]) return body[name];
+ if (null != query[name]) return query[name];
+
+ return defaultValue;
+};
+
+/**
+ * Check if the incoming request contains the "Content-Type"
+ * header field, and it contains the given mime `type`.
+ *
+ * Examples:
+ *
+ * // With Content-Type: text/html; charset=utf-8
+ * req.is('html');
+ * req.is('text/html');
+ * req.is('text/*');
+ * // => true
+ *
+ * // When Content-Type is application/json
+ * req.is('json');
+ * req.is('application/json');
+ * req.is('application/*');
+ * // => true
+ *
+ * req.is('html');
+ * // => false
+ *
+ * @param {String|Array} types...
+ * @return {String|false|null}
+ * @public
+ */
+
+req$2.is = function is(types) {
+ var arr = types;
+
+ // support flattened arguments
+ if (!Array.isArray(types)) {
+ arr = new Array(arguments.length);
+ for (var i = 0; i < arr.length; i++) {
+ arr[i] = arguments[i];
+ }
+ }
+
+ return typeis(this, arr);
+};
+
+/**
+ * Return the protocol string "http" or "https"
+ * when requested with TLS. When the "trust proxy"
+ * setting trusts the socket address, the
+ * "X-Forwarded-Proto" header field will be trusted
+ * and used if present.
+ *
+ * If you're running behind a reverse proxy that
+ * supplies https for you this may be enabled.
+ *
+ * @return {String}
+ * @public
+ */
+
+defineGetter(req$2, 'protocol', function protocol(){
+ var proto = this.connection.encrypted
+ ? 'https'
+ : 'http';
+ var trust = this.app.get('trust proxy fn');
+
+ if (!trust(this.connection.remoteAddress, 0)) {
+ return proto;
+ }
+
+ // Note: X-Forwarded-Proto is normally only ever a
+ // single value, but this is to be safe.
+ var header = this.get('X-Forwarded-Proto') || proto;
+ var index = header.indexOf(',');
+
+ return index !== -1
+ ? header.substring(0, index).trim()
+ : header.trim()
+});
+
+/**
+ * Short-hand for:
+ *
+ * req.protocol === 'https'
+ *
+ * @return {Boolean}
+ * @public
+ */
+
+defineGetter(req$2, 'secure', function secure(){
+ return this.protocol === 'https';
+});
+
+/**
+ * Return the remote address from the trusted proxy.
+ *
+ * The is the remote address on the socket unless
+ * "trust proxy" is set.
+ *
+ * @return {String}
+ * @public
+ */
+
+defineGetter(req$2, 'ip', function ip(){
+ var trust = this.app.get('trust proxy fn');
+ return proxyaddr(this, trust);
+});
+
+/**
+ * When "trust proxy" is set, trusted proxy addresses + client.
+ *
+ * For example if the value were "client, proxy1, proxy2"
+ * you would receive the array `["client", "proxy1", "proxy2"]`
+ * where "proxy2" is the furthest down-stream and "proxy1" and
+ * "proxy2" were trusted.
+ *
+ * @return {Array}
+ * @public
+ */
+
+defineGetter(req$2, 'ips', function ips() {
+ var trust = this.app.get('trust proxy fn');
+ var addrs = proxyaddr.all(this, trust);
+
+ // reverse the order (to farthest -> closest)
+ // and remove socket address
+ addrs.reverse().pop();
+
+ return addrs
+});
+
+/**
+ * Return subdomains as an array.
+ *
+ * Subdomains are the dot-separated parts of the host before the main domain of
+ * the app. By default, the domain of the app is assumed to be the last two
+ * parts of the host. This can be changed by setting "subdomain offset".
+ *
+ * For example, if the domain is "tobi.ferrets.example.com":
+ * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
+ * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
+ *
+ * @return {Array}
+ * @public
+ */
+
+defineGetter(req$2, 'subdomains', function subdomains() {
+ var hostname = this.hostname;
+
+ if (!hostname) return [];
+
+ var offset = this.app.get('subdomain offset');
+ var subdomains = !isIP$1(hostname)
+ ? hostname.split('.').reverse()
+ : [hostname];
+
+ return subdomains.slice(offset);
+});
+
+/**
+ * Short-hand for `url.parse(req.url).pathname`.
+ *
+ * @return {String}
+ * @public
+ */
+
+defineGetter(req$2, 'path', function path() {
+ return parse$8(this).pathname;
+});
+
+/**
+ * Parse the "Host" header field to a hostname.
+ *
+ * When the "trust proxy" setting trusts the socket
+ * address, the "X-Forwarded-Host" header field will
+ * be trusted.
+ *
+ * @return {String}
+ * @public
+ */
+
+defineGetter(req$2, 'hostname', function hostname(){
+ var trust = this.app.get('trust proxy fn');
+ var host = this.get('X-Forwarded-Host');
+
+ if (!host || !trust(this.connection.remoteAddress, 0)) {
+ host = this.get('Host');
+ } else if (host.indexOf(',') !== -1) {
+ // Note: X-Forwarded-Host is normally only ever a
+ // single value, but this is to be safe.
+ host = host.substring(0, host.indexOf(',')).trimRight();
+ }
+
+ if (!host) return;
+
+ // IPv6 literal support
+ var offset = host[0] === '['
+ ? host.indexOf(']') + 1
+ : 0;
+ var index = host.indexOf(':', offset);
+
+ return index !== -1
+ ? host.substring(0, index)
+ : host;
+});
+
+// TODO: change req.host to return host in next major
+
+defineGetter(req$2, 'host', deprecate$1.function(function host(){
+ return this.hostname;
+}, 'req.host: Use req.hostname instead'));
+
+/**
+ * Check if the request is fresh, aka
+ * Last-Modified and/or the ETag
+ * still match.
+ *
+ * @return {Boolean}
+ * @public
+ */
+
+defineGetter(req$2, 'fresh', function(){
+ var method = this.method;
+ var res = this.res;
+ var status = res.statusCode;
+
+ // GET or HEAD for weak freshness validation only
+ if ('GET' !== method && 'HEAD' !== method) return false;
+
+ // 2xx or 304 as per rfc2616 14.26
+ if ((status >= 200 && status < 300) || 304 === status) {
+ return fresh(this.headers, {
+ 'etag': res.get('ETag'),
+ 'last-modified': res.get('Last-Modified')
+ })
+ }
+
+ return false;
+});
+
+/**
+ * Check if the request is stale, aka
+ * "Last-Modified" and / or the "ETag" for the
+ * resource has changed.
+ *
+ * @return {Boolean}
+ * @public
+ */
+
+defineGetter(req$2, 'stale', function stale(){
+ return !this.fresh;
+});
+
+/**
+ * Check if the request was an _XMLHttpRequest_.
+ *
+ * @return {Boolean}
+ * @public
+ */
+
+defineGetter(req$2, 'xhr', function xhr(){
+ var val = this.get('X-Requested-With') || '';
+ return val.toLowerCase() === 'xmlhttprequest';
+});
+
+/**
+ * Helper function for creating a getter on an object.
+ *
+ * @param {Object} obj
+ * @param {String} name
+ * @param {Function} getter
+ * @private
+ */
+function defineGetter(obj, name, getter) {
+ Object.defineProperty(obj, name, {
+ configurable: true,
+ enumerable: true,
+ get: getter
+ });
+}
+
+var cookieSignature = {};
+
+/**
+ * Module dependencies.
+ */
+
+(function (exports) {
+ var crypto = require$$0$j;
+
+ /**
+ * Sign the given `val` with `secret`.
+ *
+ * @param {String} val
+ * @param {String} secret
+ * @return {String}
+ * @api private
+ */
+
+ exports.sign = function(val, secret){
+ if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string.");
+ if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
+ return val + '.' + crypto
+ .createHmac('sha256', secret)
+ .update(val)
+ .digest('base64')
+ .replace(/\=+$/, '');
+ };
+
+ /**
+ * Unsign and decode the given `val` with `secret`,
+ * returning `false` if the signature is invalid.
+ *
+ * @param {String} val
+ * @param {String} secret
+ * @return {String|Boolean}
+ * @api private
+ */
+
+ exports.unsign = function(val, secret){
+ if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided.");
+ if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
+ var str = val.slice(0, val.lastIndexOf('.'))
+ , mac = exports.sign(str, secret);
+
+ return sha1(mac) == sha1(val) ? str : false;
+ };
+
+ /**
+ * Private
+ */
+
+ function sha1(str){
+ return crypto.createHash('sha1').update(str).digest('hex');
+ }
+} (cookieSignature));
+
+var cookie$1 = {};
+
+/*!
+ * cookie
+ * Copyright(c) 2012-2014 Roman Shtylman
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ * @public
+ */
+
+cookie$1.parse = parse$7;
+cookie$1.serialize = serialize;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var __toString = Object.prototype.toString;
+
+/**
+ * RegExp to match field-content in RFC 7230 sec 3.2
+ *
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+ * field-vchar = VCHAR / obs-text
+ * obs-text = %x80-FF
+ */
+
+var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
+
+/**
+ * Parse a cookie header.
+ *
+ * Parse the given cookie header string into an object
+ * The object has the various cookies as keys(names) => values
+ *
+ * @param {string} str
+ * @param {object} [options]
+ * @return {object}
+ * @public
+ */
+
+function parse$7(str, options) {
+ if (typeof str !== 'string') {
+ throw new TypeError('argument str must be a string');
+ }
+
+ var obj = {};
+ var opt = options || {};
+ var dec = opt.decode || decode$2;
+
+ var index = 0;
+ while (index < str.length) {
+ var eqIdx = str.indexOf('=', index);
+
+ // no more cookie pairs
+ if (eqIdx === -1) {
+ break
+ }
+
+ var endIdx = str.indexOf(';', index);
+
+ if (endIdx === -1) {
+ endIdx = str.length;
+ } else if (endIdx < eqIdx) {
+ // backtrack on prior semicolon
+ index = str.lastIndexOf(';', eqIdx - 1) + 1;
+ continue
+ }
+
+ var key = str.slice(index, eqIdx).trim();
+
+ // only assign once
+ if (undefined === obj[key]) {
+ var val = str.slice(eqIdx + 1, endIdx).trim();
+
+ // quoted values
+ if (val.charCodeAt(0) === 0x22) {
+ val = val.slice(1, -1);
+ }
+
+ obj[key] = tryDecode(val, dec);
+ }
+
+ index = endIdx + 1;
+ }
+
+ return obj;
+}
+
+/**
+ * Serialize data into a cookie header.
+ *
+ * Serialize the a name value pair into a cookie string suitable for
+ * http headers. An optional options object specified cookie parameters.
+ *
+ * serialize('foo', 'bar', { httpOnly: true })
+ * => "foo=bar; httpOnly"
+ *
+ * @param {string} name
+ * @param {string} val
+ * @param {object} [options]
+ * @return {string}
+ * @public
+ */
+
+function serialize(name, val, options) {
+ var opt = options || {};
+ var enc = opt.encode || encode$2;
+
+ if (typeof enc !== 'function') {
+ throw new TypeError('option encode is invalid');
+ }
+
+ if (!fieldContentRegExp.test(name)) {
+ throw new TypeError('argument name is invalid');
+ }
+
+ var value = enc(val);
+
+ if (value && !fieldContentRegExp.test(value)) {
+ throw new TypeError('argument val is invalid');
+ }
+
+ var str = name + '=' + value;
+
+ if (null != opt.maxAge) {
+ var maxAge = opt.maxAge - 0;
+
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
+ throw new TypeError('option maxAge is invalid')
+ }
+
+ str += '; Max-Age=' + Math.floor(maxAge);
+ }
+
+ if (opt.domain) {
+ if (!fieldContentRegExp.test(opt.domain)) {
+ throw new TypeError('option domain is invalid');
+ }
+
+ str += '; Domain=' + opt.domain;
+ }
+
+ if (opt.path) {
+ if (!fieldContentRegExp.test(opt.path)) {
+ throw new TypeError('option path is invalid');
+ }
+
+ str += '; Path=' + opt.path;
+ }
+
+ if (opt.expires) {
+ var expires = opt.expires;
+
+ if (!isDate$1(expires) || isNaN(expires.valueOf())) {
+ throw new TypeError('option expires is invalid');
+ }
+
+ str += '; Expires=' + expires.toUTCString();
+ }
+
+ if (opt.httpOnly) {
+ str += '; HttpOnly';
+ }
+
+ if (opt.secure) {
+ str += '; Secure';
+ }
+
+ if (opt.priority) {
+ var priority = typeof opt.priority === 'string'
+ ? opt.priority.toLowerCase()
+ : opt.priority;
+
+ switch (priority) {
+ case 'low':
+ str += '; Priority=Low';
+ break
+ case 'medium':
+ str += '; Priority=Medium';
+ break
+ case 'high':
+ str += '; Priority=High';
+ break
+ default:
+ throw new TypeError('option priority is invalid')
+ }
+ }
+
+ if (opt.sameSite) {
+ var sameSite = typeof opt.sameSite === 'string'
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
+
+ switch (sameSite) {
+ case true:
+ str += '; SameSite=Strict';
+ break;
+ case 'lax':
+ str += '; SameSite=Lax';
+ break;
+ case 'strict':
+ str += '; SameSite=Strict';
+ break;
+ case 'none':
+ str += '; SameSite=None';
+ break;
+ default:
+ throw new TypeError('option sameSite is invalid');
+ }
+ }
+
+ return str;
+}
+
+/**
+ * URL-decode string value. Optimized to skip native call when no %.
+ *
+ * @param {string} str
+ * @returns {string}
+ */
+
+function decode$2 (str) {
+ return str.indexOf('%') !== -1
+ ? decodeURIComponent(str)
+ : str
+}
+
+/**
+ * URL-encode value.
+ *
+ * @param {string} str
+ * @returns {string}
+ */
+
+function encode$2 (val) {
+ return encodeURIComponent(val)
+}
+
+/**
+ * Determine if value is a Date.
+ *
+ * @param {*} val
+ * @private
+ */
+
+function isDate$1 (val) {
+ return __toString.call(val) === '[object Date]' ||
+ val instanceof Date
+}
+
+/**
+ * Try decoding a string using a decoding function.
+ *
+ * @param {string} str
+ * @param {function} decode
+ * @private
+ */
+
+function tryDecode(str, decode) {
+ try {
+ return decode(str);
+ } catch (e) {
+ return str;
+ }
+}
+
+var varyExports = {};
+var vary$2 = {
+ get exports(){ return varyExports; },
+ set exports(v){ varyExports = v; },
+};
+
+/*!
+ * vary
+ * Copyright(c) 2014-2017 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module exports.
+ */
+
+vary$2.exports = vary$1;
+varyExports.append = append;
+
+/**
+ * RegExp to match field-name in RFC 7230 sec 3.2
+ *
+ * field-name = token
+ * token = 1*tchar
+ * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
+ * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
+ * / DIGIT / ALPHA
+ * ; any VCHAR, except delimiters
+ */
+
+var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
+
+/**
+ * Append a field to a vary header.
+ *
+ * @param {String} header
+ * @param {String|Array} field
+ * @return {String}
+ * @public
+ */
+
+function append (header, field) {
+ if (typeof header !== 'string') {
+ throw new TypeError('header argument is required')
+ }
+
+ if (!field) {
+ throw new TypeError('field argument is required')
+ }
+
+ // get fields array
+ var fields = !Array.isArray(field)
+ ? parse$6(String(field))
+ : field;
+
+ // assert on invalid field names
+ for (var j = 0; j < fields.length; j++) {
+ if (!FIELD_NAME_REGEXP.test(fields[j])) {
+ throw new TypeError('field argument contains an invalid header name')
+ }
+ }
+
+ // existing, unspecified vary
+ if (header === '*') {
+ return header
+ }
+
+ // enumerate current values
+ var val = header;
+ var vals = parse$6(header.toLowerCase());
+
+ // unspecified vary
+ if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
+ return '*'
+ }
+
+ for (var i = 0; i < fields.length; i++) {
+ var fld = fields[i].toLowerCase();
+
+ // append value (case-preserving)
+ if (vals.indexOf(fld) === -1) {
+ vals.push(fld);
+ val = val
+ ? val + ', ' + fields[i]
+ : fields[i];
+ }
+ }
+
+ return val
+}
+
+/**
+ * Parse a vary header into an array.
+ *
+ * @param {String} header
+ * @return {Array}
+ * @private
+ */
+
+function parse$6 (header) {
+ var end = 0;
+ var list = [];
+ var start = 0;
+
+ // gather tokens
+ for (var i = 0, len = header.length; i < len; i++) {
+ switch (header.charCodeAt(i)) {
+ case 0x20: /* */
+ if (start === end) {
+ start = end = i + 1;
+ }
+ break
+ case 0x2c: /* , */
+ list.push(header.substring(start, end));
+ start = end = i + 1;
+ break
+ default:
+ end = i + 1;
+ break
+ }
+ }
+
+ // final token
+ list.push(header.substring(start, end));
+
+ return list
+}
+
+/**
+ * Mark that a request is varied on a header field.
+ *
+ * @param {Object} res
+ * @param {String|Array} field
+ * @public
+ */
+
+function vary$1 (res, field) {
+ if (!res || !res.getHeader || !res.setHeader) {
+ // quack quack
+ throw new TypeError('res argument is required')
+ }
+
+ // get existing header
+ var val = res.getHeader('Vary') || '';
+ var header = Array.isArray(val)
+ ? val.join(', ')
+ : String(val);
+
+ // set new header
+ if ((val = append(header, field))) {
+ res.setHeader('Vary', val);
+ }
+}
+
+/*!
+ * express
+ * Copyright(c) 2009-2013 TJ Holowaychuk
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var Buffer$1 = safeBufferExports.Buffer;
+var contentDisposition = contentDispositionExports;
+var createError = httpErrorsExports;
+var deprecate = depd_1('express');
+var encodeUrl = encodeurl;
+var escapeHtml = escapeHtml_1;
+var http$3 = http$6;
+var isAbsolute$2 = utils$3.isAbsolute;
+var onFinished = onFinishedExports;
+var path$i = require$$0$c;
+var statuses = statuses$3;
+var merge$2 = utilsMergeExports;
+var sign = cookieSignature.sign;
+var normalizeType = utils$3.normalizeType;
+var normalizeTypes = utils$3.normalizeTypes;
+var setCharset = utils$3.setCharset;
+var cookie = cookie$1;
+var send = sendExports;
+var extname = path$i.extname;
+var mime$1 = send.mime;
+var resolve$1 = path$i.resolve;
+var vary = varyExports;
+
+/**
+ * Response prototype.
+ * @public
+ */
+
+var res$2 = Object.create(http$3.ServerResponse.prototype);
+
+/**
+ * Module exports.
+ * @public
+ */
+
+var response$1 = res$2;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var charsetRegExp = /;\s*charset\s*=/;
+
+/**
+ * Set status `code`.
+ *
+ * @param {Number} code
+ * @return {ServerResponse}
+ * @public
+ */
+
+res$2.status = function status(code) {
+ if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) {
+ deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead');
+ }
+ this.statusCode = code;
+ return this;
+};
+
+/**
+ * Set Link header field with the given `links`.
+ *
+ * Examples:
+ *
+ * res.links({
+ * next: 'http://api.example.com/users?page=2',
+ * last: 'http://api.example.com/users?page=5'
+ * });
+ *
+ * @param {Object} links
+ * @return {ServerResponse}
+ * @public
+ */
+
+res$2.links = function(links){
+ var link = this.get('Link') || '';
+ if (link) link += ', ';
+ return this.set('Link', link + Object.keys(links).map(function(rel){
+ return '<' + links[rel] + '>; rel="' + rel + '"';
+ }).join(', '));
+};
+
+/**
+ * Send a response.
+ *
+ * Examples:
+ *
+ * res.send(Buffer.from('wahoo'));
+ * res.send({ some: 'json' });
+ * res.send('some html
');
+ *
+ * @param {string|number|boolean|object|Buffer} body
+ * @public
+ */
+
+res$2.send = function send(body) {
+ var chunk = body;
+ var encoding;
+ var req = this.req;
+ var type;
+
+ // settings
+ var app = this.app;
+
+ // allow status / body
+ if (arguments.length === 2) {
+ // res.send(body, status) backwards compat
+ if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {
+ deprecate('res.send(body, status): Use res.status(status).send(body) instead');
+ this.statusCode = arguments[1];
+ } else {
+ deprecate('res.send(status, body): Use res.status(status).send(body) instead');
+ this.statusCode = arguments[0];
+ chunk = arguments[1];
+ }
+ }
+
+ // disambiguate res.send(status) and res.send(status, num)
+ if (typeof chunk === 'number' && arguments.length === 1) {
+ // res.send(status) will set status message as text string
+ if (!this.get('Content-Type')) {
+ this.type('txt');
+ }
+
+ deprecate('res.send(status): Use res.sendStatus(status) instead');
+ this.statusCode = chunk;
+ chunk = statuses.message[chunk];
+ }
+
+ switch (typeof chunk) {
+ // string defaulting to html
+ case 'string':
+ if (!this.get('Content-Type')) {
+ this.type('html');
+ }
+ break;
+ case 'boolean':
+ case 'number':
+ case 'object':
+ if (chunk === null) {
+ chunk = '';
+ } else if (Buffer$1.isBuffer(chunk)) {
+ if (!this.get('Content-Type')) {
+ this.type('bin');
+ }
+ } else {
+ return this.json(chunk);
+ }
+ break;
+ }
+
+ // write strings in utf-8
+ if (typeof chunk === 'string') {
+ encoding = 'utf8';
+ type = this.get('Content-Type');
+
+ // reflect this in content-type
+ if (typeof type === 'string') {
+ this.set('Content-Type', setCharset(type, 'utf-8'));
+ }
+ }
+
+ // determine if ETag should be generated
+ var etagFn = app.get('etag fn');
+ var generateETag = !this.get('ETag') && typeof etagFn === 'function';
+
+ // populate Content-Length
+ var len;
+ if (chunk !== undefined) {
+ if (Buffer$1.isBuffer(chunk)) {
+ // get length of Buffer
+ len = chunk.length;
+ } else if (!generateETag && chunk.length < 1000) {
+ // just calculate length when no ETag + small chunk
+ len = Buffer$1.byteLength(chunk, encoding);
+ } else {
+ // convert chunk to Buffer and calculate
+ chunk = Buffer$1.from(chunk, encoding);
+ encoding = undefined;
+ len = chunk.length;
+ }
+
+ this.set('Content-Length', len);
+ }
+
+ // populate ETag
+ var etag;
+ if (generateETag && len !== undefined) {
+ if ((etag = etagFn(chunk, encoding))) {
+ this.set('ETag', etag);
+ }
+ }
+
+ // freshness
+ if (req.fresh) this.statusCode = 304;
+
+ // strip irrelevant headers
+ if (204 === this.statusCode || 304 === this.statusCode) {
+ this.removeHeader('Content-Type');
+ this.removeHeader('Content-Length');
+ this.removeHeader('Transfer-Encoding');
+ chunk = '';
+ }
+
+ // alter headers for 205
+ if (this.statusCode === 205) {
+ this.set('Content-Length', '0');
+ this.removeHeader('Transfer-Encoding');
+ chunk = '';
+ }
+
+ if (req.method === 'HEAD') {
+ // skip body for HEAD
+ this.end();
+ } else {
+ // respond
+ this.end(chunk, encoding);
+ }
+
+ return this;
+};
+
+/**
+ * Send JSON response.
+ *
+ * Examples:
+ *
+ * res.json(null);
+ * res.json({ user: 'tj' });
+ *
+ * @param {string|number|boolean|object} obj
+ * @public
+ */
+
+res$2.json = function json(obj) {
+ var val = obj;
+
+ // allow status / body
+ if (arguments.length === 2) {
+ // res.json(body, status) backwards compat
+ if (typeof arguments[1] === 'number') {
+ deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
+ this.statusCode = arguments[1];
+ } else {
+ deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
+ this.statusCode = arguments[0];
+ val = arguments[1];
+ }
+ }
+
+ // settings
+ var app = this.app;
+ var escape = app.get('json escape');
+ var replacer = app.get('json replacer');
+ var spaces = app.get('json spaces');
+ var body = stringify$5(val, replacer, spaces, escape);
+
+ // content-type
+ if (!this.get('Content-Type')) {
+ this.set('Content-Type', 'application/json');
+ }
+
+ return this.send(body);
+};
+
+/**
+ * Send JSON response with JSONP callback support.
+ *
+ * Examples:
+ *
+ * res.jsonp(null);
+ * res.jsonp({ user: 'tj' });
+ *
+ * @param {string|number|boolean|object} obj
+ * @public
+ */
+
+res$2.jsonp = function jsonp(obj) {
+ var val = obj;
+
+ // allow status / body
+ if (arguments.length === 2) {
+ // res.jsonp(body, status) backwards compat
+ if (typeof arguments[1] === 'number') {
+ deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead');
+ this.statusCode = arguments[1];
+ } else {
+ deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');
+ this.statusCode = arguments[0];
+ val = arguments[1];
+ }
+ }
+
+ // settings
+ var app = this.app;
+ var escape = app.get('json escape');
+ var replacer = app.get('json replacer');
+ var spaces = app.get('json spaces');
+ var body = stringify$5(val, replacer, spaces, escape);
+ var callback = this.req.query[app.get('jsonp callback name')];
+
+ // content-type
+ if (!this.get('Content-Type')) {
+ this.set('X-Content-Type-Options', 'nosniff');
+ this.set('Content-Type', 'application/json');
+ }
+
+ // fixup callback
+ if (Array.isArray(callback)) {
+ callback = callback[0];
+ }
+
+ // jsonp
+ if (typeof callback === 'string' && callback.length !== 0) {
+ this.set('X-Content-Type-Options', 'nosniff');
+ this.set('Content-Type', 'text/javascript');
+
+ // restrict callback charset
+ callback = callback.replace(/[^\[\]\w$.]/g, '');
+
+ if (body === undefined) {
+ // empty argument
+ body = '';
+ } else if (typeof body === 'string') {
+ // replace chars not allowed in JavaScript that are in JSON
+ body = body
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029');
+ }
+
+ // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
+ // the typeof check is just to reduce client error noise
+ body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
+ }
+
+ return this.send(body);
+};
+
+/**
+ * Send given HTTP status code.
+ *
+ * Sets the response status to `statusCode` and the body of the
+ * response to the standard description from node's http.STATUS_CODES
+ * or the statusCode number if no description.
+ *
+ * Examples:
+ *
+ * res.sendStatus(200);
+ *
+ * @param {number} statusCode
+ * @public
+ */
+
+res$2.sendStatus = function sendStatus(statusCode) {
+ var body = statuses.message[statusCode] || String(statusCode);
+
+ this.statusCode = statusCode;
+ this.type('txt');
+
+ return this.send(body);
+};
+
+/**
+ * Transfer the file at the given `path`.
+ *
+ * Automatically sets the _Content-Type_ response header field.
+ * The callback `callback(err)` is invoked when the transfer is complete
+ * or when an error occurs. Be sure to check `res.headersSent`
+ * if you wish to attempt responding, as the header and some data
+ * may have already been transferred.
+ *
+ * Options:
+ *
+ * - `maxAge` defaulting to 0 (can be string converted by `ms`)
+ * - `root` root directory for relative filenames
+ * - `headers` object of headers to serve with file
+ * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
+ *
+ * Other options are passed along to `send`.
+ *
+ * Examples:
+ *
+ * The following example illustrates how `res.sendFile()` may
+ * be used as an alternative for the `static()` middleware for
+ * dynamic situations. The code backing `res.sendFile()` is actually
+ * the same code, so HTTP cache support etc is identical.
+ *
+ * app.get('/user/:uid/photos/:file', function(req, res){
+ * var uid = req.params.uid
+ * , file = req.params.file;
+ *
+ * req.user.mayViewFilesFrom(uid, function(yes){
+ * if (yes) {
+ * res.sendFile('/uploads/' + uid + '/' + file);
+ * } else {
+ * res.send(403, 'Sorry! you cant see that.');
+ * }
+ * });
+ * });
+ *
+ * @public
+ */
+
+res$2.sendFile = function sendFile(path, options, callback) {
+ var done = callback;
+ var req = this.req;
+ var res = this;
+ var next = req.next;
+ var opts = options || {};
+
+ if (!path) {
+ throw new TypeError('path argument is required to res.sendFile');
+ }
+
+ if (typeof path !== 'string') {
+ throw new TypeError('path must be a string to res.sendFile')
+ }
+
+ // support function as second arg
+ if (typeof options === 'function') {
+ done = options;
+ opts = {};
+ }
+
+ if (!opts.root && !isAbsolute$2(path)) {
+ throw new TypeError('path must be absolute or specify root to res.sendFile');
+ }
+
+ // create file stream
+ var pathname = encodeURI(path);
+ var file = send(req, pathname, opts);
+
+ // transfer
+ sendfile(res, file, opts, function (err) {
+ if (done) return done(err);
+ if (err && err.code === 'EISDIR') return next();
+
+ // next() all but write errors
+ if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
+ next(err);
+ }
+ });
+};
+
+/**
+ * Transfer the file at the given `path`.
+ *
+ * Automatically sets the _Content-Type_ response header field.
+ * The callback `callback(err)` is invoked when the transfer is complete
+ * or when an error occurs. Be sure to check `res.headersSent`
+ * if you wish to attempt responding, as the header and some data
+ * may have already been transferred.
+ *
+ * Options:
+ *
+ * - `maxAge` defaulting to 0 (can be string converted by `ms`)
+ * - `root` root directory for relative filenames
+ * - `headers` object of headers to serve with file
+ * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
+ *
+ * Other options are passed along to `send`.
+ *
+ * Examples:
+ *
+ * The following example illustrates how `res.sendfile()` may
+ * be used as an alternative for the `static()` middleware for
+ * dynamic situations. The code backing `res.sendfile()` is actually
+ * the same code, so HTTP cache support etc is identical.
+ *
+ * app.get('/user/:uid/photos/:file', function(req, res){
+ * var uid = req.params.uid
+ * , file = req.params.file;
+ *
+ * req.user.mayViewFilesFrom(uid, function(yes){
+ * if (yes) {
+ * res.sendfile('/uploads/' + uid + '/' + file);
+ * } else {
+ * res.send(403, 'Sorry! you cant see that.');
+ * }
+ * });
+ * });
+ *
+ * @public
+ */
+
+res$2.sendfile = function (path, options, callback) {
+ var done = callback;
+ var req = this.req;
+ var res = this;
+ var next = req.next;
+ var opts = options || {};
+
+ // support function as second arg
+ if (typeof options === 'function') {
+ done = options;
+ opts = {};
+ }
+
+ // create file stream
+ var file = send(req, path, opts);
+
+ // transfer
+ sendfile(res, file, opts, function (err) {
+ if (done) return done(err);
+ if (err && err.code === 'EISDIR') return next();
+
+ // next() all but write errors
+ if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
+ next(err);
+ }
+ });
+};
+
+res$2.sendfile = deprecate.function(res$2.sendfile,
+ 'res.sendfile: Use res.sendFile instead');
+
+/**
+ * Transfer the file at the given `path` as an attachment.
+ *
+ * Optionally providing an alternate attachment `filename`,
+ * and optional callback `callback(err)`. The callback is invoked
+ * when the data transfer is complete, or when an error has
+ * occurred. Be sure to check `res.headersSent` if you plan to respond.
+ *
+ * Optionally providing an `options` object to use with `res.sendFile()`.
+ * This function will set the `Content-Disposition` header, overriding
+ * any `Content-Disposition` header passed as header options in order
+ * to set the attachment and filename.
+ *
+ * This method uses `res.sendFile()`.
+ *
+ * @public
+ */
+
+res$2.download = function download (path, filename, options, callback) {
+ var done = callback;
+ var name = filename;
+ var opts = options || null;
+
+ // support function as second or third arg
+ if (typeof filename === 'function') {
+ done = filename;
+ name = null;
+ opts = null;
+ } else if (typeof options === 'function') {
+ done = options;
+ opts = null;
+ }
+
+ // support optional filename, where options may be in it's place
+ if (typeof filename === 'object' &&
+ (typeof options === 'function' || options === undefined)) {
+ name = null;
+ opts = filename;
+ }
+
+ // set Content-Disposition when file is sent
+ var headers = {
+ 'Content-Disposition': contentDisposition(name || path)
+ };
+
+ // merge user-provided headers
+ if (opts && opts.headers) {
+ var keys = Object.keys(opts.headers);
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ if (key.toLowerCase() !== 'content-disposition') {
+ headers[key] = opts.headers[key];
+ }
+ }
+ }
+
+ // merge user-provided options
+ opts = Object.create(opts);
+ opts.headers = headers;
+
+ // Resolve the full path for sendFile
+ var fullPath = !opts.root
+ ? resolve$1(path)
+ : path;
+
+ // send file
+ return this.sendFile(fullPath, opts, done)
+};
+
+/**
+ * Set _Content-Type_ response header with `type` through `mime.lookup()`
+ * when it does not contain "/", or set the Content-Type to `type` otherwise.
+ *
+ * Examples:
+ *
+ * res.type('.html');
+ * res.type('html');
+ * res.type('json');
+ * res.type('application/json');
+ * res.type('png');
+ *
+ * @param {String} type
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.contentType =
+res$2.type = function contentType(type) {
+ var ct = type.indexOf('/') === -1
+ ? mime$1.lookup(type)
+ : type;
+
+ return this.set('Content-Type', ct);
+};
+
+/**
+ * Respond to the Acceptable formats using an `obj`
+ * of mime-type callbacks.
+ *
+ * This method uses `req.accepted`, an array of
+ * acceptable types ordered by their quality values.
+ * When "Accept" is not present the _first_ callback
+ * is invoked, otherwise the first match is used. When
+ * no match is performed the server responds with
+ * 406 "Not Acceptable".
+ *
+ * Content-Type is set for you, however if you choose
+ * you may alter this within the callback using `res.type()`
+ * or `res.set('Content-Type', ...)`.
+ *
+ * res.format({
+ * 'text/plain': function(){
+ * res.send('hey');
+ * },
+ *
+ * 'text/html': function(){
+ * res.send('hey
');
+ * },
+ *
+ * 'application/json': function () {
+ * res.send({ message: 'hey' });
+ * }
+ * });
+ *
+ * In addition to canonicalized MIME types you may
+ * also use extnames mapped to these types:
+ *
+ * res.format({
+ * text: function(){
+ * res.send('hey');
+ * },
+ *
+ * html: function(){
+ * res.send('hey
');
+ * },
+ *
+ * json: function(){
+ * res.send({ message: 'hey' });
+ * }
+ * });
+ *
+ * By default Express passes an `Error`
+ * with a `.status` of 406 to `next(err)`
+ * if a match is not made. If you provide
+ * a `.default` callback it will be invoked
+ * instead.
+ *
+ * @param {Object} obj
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.format = function(obj){
+ var req = this.req;
+ var next = req.next;
+
+ var keys = Object.keys(obj)
+ .filter(function (v) { return v !== 'default' });
+
+ var key = keys.length > 0
+ ? req.accepts(keys)
+ : false;
+
+ this.vary("Accept");
+
+ if (key) {
+ this.set('Content-Type', normalizeType(key).value);
+ obj[key](req, this, next);
+ } else if (obj.default) {
+ obj.default(req, this, next);
+ } else {
+ next(createError(406, {
+ types: normalizeTypes(keys).map(function (o) { return o.value })
+ }));
+ }
+
+ return this;
+};
+
+/**
+ * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
+ *
+ * @param {String} filename
+ * @return {ServerResponse}
+ * @public
+ */
+
+res$2.attachment = function attachment(filename) {
+ if (filename) {
+ this.type(extname(filename));
+ }
+
+ this.set('Content-Disposition', contentDisposition(filename));
+
+ return this;
+};
+
+/**
+ * Append additional header `field` with value `val`.
+ *
+ * Example:
+ *
+ * res.append('Link', ['', '']);
+ * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
+ * res.append('Warning', '199 Miscellaneous warning');
+ *
+ * @param {String} field
+ * @param {String|Array} val
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.append = function append(field, val) {
+ var prev = this.get(field);
+ var value = val;
+
+ if (prev) {
+ // concat the new and prev vals
+ value = Array.isArray(prev) ? prev.concat(val)
+ : Array.isArray(val) ? [prev].concat(val)
+ : [prev, val];
+ }
+
+ return this.set(field, value);
+};
+
+/**
+ * Set header `field` to `val`, or pass
+ * an object of header fields.
+ *
+ * Examples:
+ *
+ * res.set('Foo', ['bar', 'baz']);
+ * res.set('Accept', 'application/json');
+ * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
+ *
+ * Aliased as `res.header()`.
+ *
+ * @param {String|Object} field
+ * @param {String|Array} val
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.set =
+res$2.header = function header(field, val) {
+ if (arguments.length === 2) {
+ var value = Array.isArray(val)
+ ? val.map(String)
+ : String(val);
+
+ // add charset to content-type
+ if (field.toLowerCase() === 'content-type') {
+ if (Array.isArray(value)) {
+ throw new TypeError('Content-Type cannot be set to an Array');
+ }
+ if (!charsetRegExp.test(value)) {
+ var charset = mime$1.charsets.lookup(value.split(';')[0]);
+ if (charset) value += '; charset=' + charset.toLowerCase();
+ }
+ }
+
+ this.setHeader(field, value);
+ } else {
+ for (var key in field) {
+ this.set(key, field[key]);
+ }
+ }
+ return this;
+};
+
+/**
+ * Get value for header `field`.
+ *
+ * @param {String} field
+ * @return {String}
+ * @public
+ */
+
+res$2.get = function(field){
+ return this.getHeader(field);
+};
+
+/**
+ * Clear cookie `name`.
+ *
+ * @param {String} name
+ * @param {Object} [options]
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.clearCookie = function clearCookie(name, options) {
+ var opts = merge$2({ expires: new Date(1), path: '/' }, options);
+
+ return this.cookie(name, '', opts);
+};
+
+/**
+ * Set cookie `name` to `value`, with the given `options`.
+ *
+ * Options:
+ *
+ * - `maxAge` max-age in milliseconds, converted to `expires`
+ * - `signed` sign the cookie
+ * - `path` defaults to "/"
+ *
+ * Examples:
+ *
+ * // "Remember Me" for 15 minutes
+ * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
+ *
+ * // same as above
+ * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
+ *
+ * @param {String} name
+ * @param {String|Object} value
+ * @param {Object} [options]
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.cookie = function (name, value, options) {
+ var opts = merge$2({}, options);
+ var secret = this.req.secret;
+ var signed = opts.signed;
+
+ if (signed && !secret) {
+ throw new Error('cookieParser("secret") required for signed cookies');
+ }
+
+ var val = typeof value === 'object'
+ ? 'j:' + JSON.stringify(value)
+ : String(value);
+
+ if (signed) {
+ val = 's:' + sign(val, secret);
+ }
+
+ if (opts.maxAge != null) {
+ var maxAge = opts.maxAge - 0;
+
+ if (!isNaN(maxAge)) {
+ opts.expires = new Date(Date.now() + maxAge);
+ opts.maxAge = Math.floor(maxAge / 1000);
+ }
+ }
+
+ if (opts.path == null) {
+ opts.path = '/';
+ }
+
+ this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
+
+ return this;
+};
+
+/**
+ * Set the location header to `url`.
+ *
+ * The given `url` can also be "back", which redirects
+ * to the _Referrer_ or _Referer_ headers or "/".
+ *
+ * Examples:
+ *
+ * res.location('/foo/bar').;
+ * res.location('http://example.com');
+ * res.location('../login');
+ *
+ * @param {String} url
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.location = function location(url) {
+ var loc = url;
+
+ // "back" is an alias for the referrer
+ if (url === 'back') {
+ loc = this.req.get('Referrer') || '/';
+ }
+
+ // set location
+ return this.set('Location', encodeUrl(loc));
+};
+
+/**
+ * Redirect to the given `url` with optional response `status`
+ * defaulting to 302.
+ *
+ * The resulting `url` is determined by `res.location()`, so
+ * it will play nicely with mounted apps, relative paths,
+ * `"back"` etc.
+ *
+ * Examples:
+ *
+ * res.redirect('/foo/bar');
+ * res.redirect('http://example.com');
+ * res.redirect(301, 'http://example.com');
+ * res.redirect('../login'); // /blog/post/1 -> /blog/login
+ *
+ * @public
+ */
+
+res$2.redirect = function redirect(url) {
+ var address = url;
+ var body;
+ var status = 302;
+
+ // allow status / url
+ if (arguments.length === 2) {
+ if (typeof arguments[0] === 'number') {
+ status = arguments[0];
+ address = arguments[1];
+ } else {
+ deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
+ status = arguments[1];
+ }
+ }
+
+ // Set location header
+ address = this.location(address).get('Location');
+
+ // Support text/{plain,html} by default
+ this.format({
+ text: function(){
+ body = statuses.message[status] + '. Redirecting to ' + address;
+ },
+
+ html: function(){
+ var u = escapeHtml(address);
+ body = '' + statuses.message[status] + '. Redirecting to ' + u + '
';
+ },
+
+ default: function(){
+ body = '';
+ }
+ });
+
+ // Respond
+ this.statusCode = status;
+ this.set('Content-Length', Buffer$1.byteLength(body));
+
+ if (this.req.method === 'HEAD') {
+ this.end();
+ } else {
+ this.end(body);
+ }
+};
+
+/**
+ * Add `field` to Vary. If already present in the Vary set, then
+ * this call is simply ignored.
+ *
+ * @param {Array|String} field
+ * @return {ServerResponse} for chaining
+ * @public
+ */
+
+res$2.vary = function(field){
+ // checks for back-compat
+ if (!field || (Array.isArray(field) && !field.length)) {
+ deprecate('res.vary(): Provide a field name');
+ return this;
+ }
+
+ vary(this, field);
+
+ return this;
+};
+
+/**
+ * Render `view` with the given `options` and optional callback `fn`.
+ * When a callback function is given a response will _not_ be made
+ * automatically, otherwise a response of _200_ and _text/html_ is given.
+ *
+ * Options:
+ *
+ * - `cache` boolean hinting to the engine it should cache
+ * - `filename` filename of the view being rendered
+ *
+ * @public
+ */
+
+res$2.render = function render(view, options, callback) {
+ var app = this.req.app;
+ var done = callback;
+ var opts = options || {};
+ var req = this.req;
+ var self = this;
+
+ // support callback function as second arg
+ if (typeof options === 'function') {
+ done = options;
+ opts = {};
+ }
+
+ // merge res.locals
+ opts._locals = self.locals;
+
+ // default callback to respond
+ done = done || function (err, str) {
+ if (err) return req.next(err);
+ self.send(str);
+ };
+
+ // render
+ app.render(view, opts, done);
+};
+
+// pipe the send file stream
+function sendfile(res, file, options, callback) {
+ var done = false;
+ var streaming;
+
+ // request aborted
+ function onaborted() {
+ if (done) return;
+ done = true;
+
+ var err = new Error('Request aborted');
+ err.code = 'ECONNABORTED';
+ callback(err);
+ }
+
+ // directory
+ function ondirectory() {
+ if (done) return;
+ done = true;
+
+ var err = new Error('EISDIR, read');
+ err.code = 'EISDIR';
+ callback(err);
+ }
+
+ // errors
+ function onerror(err) {
+ if (done) return;
+ done = true;
+ callback(err);
+ }
+
+ // ended
+ function onend() {
+ if (done) return;
+ done = true;
+ callback();
+ }
+
+ // file
+ function onfile() {
+ streaming = false;
+ }
+
+ // finished
+ function onfinish(err) {
+ if (err && err.code === 'ECONNRESET') return onaborted();
+ if (err) return onerror(err);
+ if (done) return;
+
+ setImmediate(function () {
+ if (streaming !== false && !done) {
+ onaborted();
+ return;
+ }
+
+ if (done) return;
+ done = true;
+ callback();
+ });
+ }
+
+ // streaming
+ function onstream() {
+ streaming = true;
+ }
+
+ file.on('directory', ondirectory);
+ file.on('end', onend);
+ file.on('error', onerror);
+ file.on('file', onfile);
+ file.on('stream', onstream);
+ onFinished(res, onfinish);
+
+ if (options.headers) {
+ // set headers on successful transfer
+ file.on('headers', function headers(res) {
+ var obj = options.headers;
+ var keys = Object.keys(obj);
+
+ for (var i = 0; i < keys.length; i++) {
+ var k = keys[i];
+ res.setHeader(k, obj[k]);
+ }
+ });
+ }
+
+ // pipe
+ file.pipe(res);
+}
+
+/**
+ * Stringify JSON, like JSON.stringify, but v8 optimized, with the
+ * ability to escape characters that can trigger HTML sniffing.
+ *
+ * @param {*} value
+ * @param {function} replacer
+ * @param {number} spaces
+ * @param {boolean} escape
+ * @returns {string}
+ * @private
+ */
+
+function stringify$5 (value, replacer, spaces, escape) {
+ // v8 checks arguments.length for optimizing simple call
+ // https://bugs.chromium.org/p/v8/issues/detail?id=4730
+ var json = replacer || spaces
+ ? JSON.stringify(value, replacer, spaces)
+ : JSON.stringify(value);
+
+ if (escape && typeof json === 'string') {
+ json = json.replace(/[<>&]/g, function (c) {
+ switch (c.charCodeAt(0)) {
+ case 0x3c:
+ return '\\u003c'
+ case 0x3e:
+ return '\\u003e'
+ case 0x26:
+ return '\\u0026'
+ /* istanbul ignore next: unreachable default */
+ default:
+ return c
+ }
+ });
+ }
+
+ return json
+}
+
+var serveStaticExports = {};
+var serveStatic = {
+ get exports(){ return serveStaticExports; },
+ set exports(v){ serveStaticExports = v; },
+};
+
+/*!
+ * serve-static
+ * Copyright(c) 2010 Sencha Inc.
+ * Copyright(c) 2011 TJ Holowaychuk
+ * Copyright(c) 2014-2016 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+var hasRequiredServeStatic;
+
+function requireServeStatic () {
+ if (hasRequiredServeStatic) return serveStaticExports;
+ hasRequiredServeStatic = 1;
+
+ /**
+ * Module dependencies.
+ * @private
+ */
+
+ var encodeUrl = encodeurl;
+ var escapeHtml = escapeHtml_1;
+ var parseUrl = parseurlExports;
+ var resolve = require$$0$c.resolve;
+ var send = sendExports;
+ var url = Url$2;
+
+ /**
+ * Module exports.
+ * @public
+ */
+
+ serveStatic.exports = serveStatic$1;
+ serveStaticExports.mime = send.mime;
+
+ /**
+ * @param {string} root
+ * @param {object} [options]
+ * @return {function}
+ * @public
+ */
+
+ function serveStatic$1 (root, options) {
+ if (!root) {
+ throw new TypeError('root path required')
+ }
+
+ if (typeof root !== 'string') {
+ throw new TypeError('root path must be a string')
+ }
+
+ // copy options object
+ var opts = Object.create(options || null);
+
+ // fall-though
+ var fallthrough = opts.fallthrough !== false;
+
+ // default redirect
+ var redirect = opts.redirect !== false;
+
+ // headers listener
+ var setHeaders = opts.setHeaders;
+
+ if (setHeaders && typeof setHeaders !== 'function') {
+ throw new TypeError('option setHeaders must be function')
+ }
+
+ // setup options for send
+ opts.maxage = opts.maxage || opts.maxAge || 0;
+ opts.root = resolve(root);
+
+ // construct directory listener
+ var onDirectory = redirect
+ ? createRedirectDirectoryListener()
+ : createNotFoundDirectoryListener();
+
+ return function serveStatic (req, res, next) {
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ if (fallthrough) {
+ return next()
+ }
+
+ // method not allowed
+ res.statusCode = 405;
+ res.setHeader('Allow', 'GET, HEAD');
+ res.setHeader('Content-Length', '0');
+ res.end();
+ return
+ }
+
+ var forwardError = !fallthrough;
+ var originalUrl = parseUrl.original(req);
+ var path = parseUrl(req).pathname;
+
+ // make sure redirect occurs at mount
+ if (path === '/' && originalUrl.pathname.substr(-1) !== '/') {
+ path = '';
+ }
+
+ // create send stream
+ var stream = send(req, path, opts);
+
+ // add directory handler
+ stream.on('directory', onDirectory);
+
+ // add headers listener
+ if (setHeaders) {
+ stream.on('headers', setHeaders);
+ }
+
+ // add file listener for fallthrough
+ if (fallthrough) {
+ stream.on('file', function onFile () {
+ // once file is determined, always forward error
+ forwardError = true;
+ });
+ }
+
+ // forward errors
+ stream.on('error', function error (err) {
+ if (forwardError || !(err.statusCode < 500)) {
+ next(err);
+ return
+ }
+
+ next();
+ });
+
+ // pipe
+ stream.pipe(res);
+ }
+ }
+
+ /**
+ * Collapse all leading slashes into a single slash
+ * @private
+ */
+ function collapseLeadingSlashes (str) {
+ for (var i = 0; i < str.length; i++) {
+ if (str.charCodeAt(i) !== 0x2f /* / */) {
+ break
+ }
+ }
+
+ return i > 1
+ ? '/' + str.substr(i)
+ : str
+ }
+
+ /**
+ * Create a minimal HTML document.
+ *
+ * @param {string} title
+ * @param {string} body
+ * @private
+ */
+
+ function createHtmlDocument (title, body) {
+ return '\n' +
+ '\n' +
+ '\n' +
+ '\n' +
+ '' + title + '\n' +
+ '\n' +
+ '\n' +
+ '' + body + '
\n' +
+ '\n' +
+ '\n'
+ }
+
+ /**
+ * Create a directory listener that just 404s.
+ * @private
+ */
+
+ function createNotFoundDirectoryListener () {
+ return function notFound () {
+ this.error(404);
+ }
+ }
+
+ /**
+ * Create a directory listener that performs a redirect.
+ * @private
+ */
+
+ function createRedirectDirectoryListener () {
+ return function redirect (res) {
+ if (this.hasTrailingSlash()) {
+ this.error(404);
+ return
+ }
+
+ // get original URL
+ var originalUrl = parseUrl.original(this.req);
+
+ // append trailing slash
+ originalUrl.path = null;
+ originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/');
+
+ // reformat the URL
+ var loc = encodeUrl(url.format(originalUrl));
+ var doc = createHtmlDocument('Redirecting', 'Redirecting to ' +
+ escapeHtml(loc) + '');
+
+ // send redirect response
+ res.statusCode = 301;
+ res.setHeader('Content-Type', 'text/html; charset=UTF-8');
+ res.setHeader('Content-Length', Buffer.byteLength(doc));
+ res.setHeader('Content-Security-Policy', "default-src 'none'");
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.setHeader('Location', loc);
+ res.end(doc);
+ }
+ }
+ return serveStaticExports;
+}
+
+/*!
+ * express
+ * Copyright(c) 2009-2013 TJ Holowaychuk
+ * Copyright(c) 2013 Roman Shtylman
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+(function (module, exports) {
+
+ /**
+ * Module dependencies.
+ */
+
+ var bodyParser = bodyParserExports;
+ var EventEmitter = require$$0$f.EventEmitter;
+ var mixin = mergeDescriptors;
+ var proto = applicationExports;
+ var Route = route;
+ var Router = routerExports;
+ var req = request;
+ var res = response$1;
+
+ /**
+ * Expose `createApplication()`.
+ */
+
+ exports = module.exports = createApplication;
+
+ /**
+ * Create an express application.
+ *
+ * @return {Function}
+ * @api public
+ */
+
+ function createApplication() {
+ var app = function(req, res, next) {
+ app.handle(req, res, next);
+ };
+
+ mixin(app, EventEmitter.prototype, false);
+ mixin(app, proto, false);
+
+ // expose the prototype that will get set on requests
+ app.request = Object.create(req, {
+ app: { configurable: true, enumerable: true, writable: true, value: app }
+ });
+
+ // expose the prototype that will get set on responses
+ app.response = Object.create(res, {
+ app: { configurable: true, enumerable: true, writable: true, value: app }
+ });
+
+ app.init();
+ return app;
+ }
+
+ /**
+ * Expose the prototypes.
+ */
+
+ exports.application = proto;
+ exports.request = req;
+ exports.response = res;
+
+ /**
+ * Expose constructors.
+ */
+
+ exports.Route = Route;
+ exports.Router = Router;
+
+ /**
+ * Expose middleware
+ */
+
+ exports.json = bodyParser.json;
+ exports.query = query;
+ exports.raw = bodyParser.raw;
+ exports.static = requireServeStatic();
+ exports.text = bodyParser.text;
+ exports.urlencoded = bodyParser.urlencoded;
+
+ /**
+ * Replace removed middleware with an appropriate error message.
+ */
+
+ var removedMiddlewares = [
+ 'bodyParser',
+ 'compress',
+ 'cookieSession',
+ 'session',
+ 'logger',
+ 'cookieParser',
+ 'favicon',
+ 'responseTime',
+ 'errorHandler',
+ 'timeout',
+ 'methodOverride',
+ 'vhost',
+ 'csrf',
+ 'directory',
+ 'limit',
+ 'multipart',
+ 'staticCache'
+ ];
+
+ removedMiddlewares.forEach(function (name) {
+ Object.defineProperty(exports, name, {
+ get: function () {
+ throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.');
+ },
+ configurable: true
+ });
+ });
+} (express, expressExports));
+
+/*!
+ * express
+ * Copyright(c) 2009-2013 TJ Holowaychuk
+ * Copyright(c) 2013 Roman Shtylman
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+(function (module) {
+
+ module.exports = expressExports;
+} (express$1));
+
+var loggingMiddleware = {};
+
+var loggerExports$1 = {};
+var logger$2 = {
+ get exports(){ return loggerExports$1; },
+ set exports(v){ loggerExports$1 = v; },
+};
+
+var err$1 = errSerializer$3;
+
+const { toString: toString$4 } = Object.prototype;
+const seen$1 = Symbol('circular-ref-tag');
+const rawSymbol$5 = Symbol('pino-raw-err-ref');
+const pinoErrProto$1 = Object.create({}, {
+ type: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ message: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ stack: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ raw: {
+ enumerable: false,
+ get: function () {
+ return this[rawSymbol$5]
+ },
+ set: function (val) {
+ this[rawSymbol$5] = val;
+ }
+ }
+});
+Object.defineProperty(pinoErrProto$1, rawSymbol$5, {
+ writable: true,
+ value: {}
+});
+
+function errSerializer$3 (err) {
+ if (!(err instanceof Error)) {
+ return err
+ }
+
+ err[seen$1] = undefined; // tag to prevent re-looking at this
+ const _err = Object.create(pinoErrProto$1);
+ _err.type = toString$4.call(err.constructor) === '[object Function]'
+ ? err.constructor.name
+ : err.name;
+ _err.message = err.message;
+ _err.stack = err.stack;
+ for (const key in err) {
+ if (_err[key] === undefined) {
+ const val = err[key];
+ if (val instanceof Error) {
+ /* eslint-disable no-prototype-builtins */
+ if (!val.hasOwnProperty(seen$1)) {
+ _err[key] = errSerializer$3(val);
+ }
+ } else {
+ _err[key] = val;
+ }
+ }
+ }
+
+ delete err[seen$1]; // clean up tag in case err is serialized again later
+ _err.raw = err;
+ return _err
+}
+
+var req$1 = {
+ mapHttpRequest: mapHttpRequest$2,
+ reqSerializer: reqSerializer$1
+};
+
+const rawSymbol$4 = Symbol('pino-raw-req-ref');
+const pinoReqProto$1 = Object.create({}, {
+ id: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ method: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ url: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ query: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ params: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ headers: {
+ enumerable: true,
+ writable: true,
+ value: {}
+ },
+ remoteAddress: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ remotePort: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ raw: {
+ enumerable: false,
+ get: function () {
+ return this[rawSymbol$4]
+ },
+ set: function (val) {
+ this[rawSymbol$4] = val;
+ }
+ }
+});
+Object.defineProperty(pinoReqProto$1, rawSymbol$4, {
+ writable: true,
+ value: {}
+});
+
+function reqSerializer$1 (req) {
+ // req.info is for hapi compat.
+ const connection = req.info || req.socket;
+ const _req = Object.create(pinoReqProto$1);
+ _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)));
+ _req.method = req.method;
+ // req.originalUrl is for expressjs compat.
+ if (req.originalUrl) {
+ _req.url = req.originalUrl;
+ _req.query = req.query;
+ _req.params = req.params;
+ } else {
+ // req.url.path is for hapi compat.
+ _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined);
+ }
+ _req.headers = req.headers;
+ _req.remoteAddress = connection && connection.remoteAddress;
+ _req.remotePort = connection && connection.remotePort;
+ // req.raw is for hapi compat/equivalence
+ _req.raw = req.raw || req;
+ return _req
+}
+
+function mapHttpRequest$2 (req) {
+ return {
+ req: reqSerializer$1(req)
+ }
+}
+
+var res$1 = {
+ mapHttpResponse: mapHttpResponse$2,
+ resSerializer: resSerializer$1
+};
+
+const rawSymbol$3 = Symbol('pino-raw-res-ref');
+const pinoResProto$1 = Object.create({}, {
+ statusCode: {
+ enumerable: true,
+ writable: true,
+ value: 0
+ },
+ headers: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ raw: {
+ enumerable: false,
+ get: function () {
+ return this[rawSymbol$3]
+ },
+ set: function (val) {
+ this[rawSymbol$3] = val;
+ }
+ }
+});
+Object.defineProperty(pinoResProto$1, rawSymbol$3, {
+ writable: true,
+ value: {}
+});
+
+function resSerializer$1 (res) {
+ const _res = Object.create(pinoResProto$1);
+ _res.statusCode = res.statusCode;
+ _res.headers = res.getHeaders ? res.getHeaders() : res._headers;
+ _res.raw = res;
+ return _res
+}
+
+function mapHttpResponse$2 (res) {
+ return {
+ res: resSerializer$1(res)
+ }
+}
+
+const errSerializer$2 = err$1;
+const reqSerializers$1 = req$1;
+const resSerializers$1 = res$1;
+
+var pinoStdSerializers$1 = {
+ err: errSerializer$2,
+ mapHttpRequest: reqSerializers$1.mapHttpRequest,
+ mapHttpResponse: resSerializers$1.mapHttpResponse,
+ req: reqSerializers$1.reqSerializer,
+ res: resSerializers$1.resSerializer,
+
+ wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {
+ if (customSerializer === errSerializer$2) return customSerializer
+ return function wrapErrSerializer (err) {
+ return customSerializer(errSerializer$2(err))
+ }
+ },
+
+ wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {
+ if (customSerializer === reqSerializers$1.reqSerializer) return customSerializer
+ return function wrappedReqSerializer (req) {
+ return customSerializer(reqSerializers$1.reqSerializer(req))
+ }
+ },
+
+ wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {
+ if (customSerializer === resSerializers$1.resSerializer) return customSerializer
+ return function wrappedResSerializer (res) {
+ return customSerializer(resSerializers$1.resSerializer(res))
+ }
+ }
+};
+
+/*
+Copyright (c) 2014 Petka Antonov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+function Url() {
+ //For more efficient internal representation and laziness.
+ //The non-underscore versions of these properties are accessor functions
+ //defined on the prototype.
+ this._protocol = null;
+ this._href = "";
+ this._port = -1;
+ this._query = null;
+
+ this.auth = null;
+ this.slashes = null;
+ this.host = null;
+ this.hostname = null;
+ this.hash = null;
+ this.search = null;
+ this.pathname = null;
+
+ this._prependSlash = false;
+}
+
+var querystring$3 = require$$8$1;
+
+Url.queryString = querystring$3;
+
+Url.prototype.parse =
+function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) {
+ if (typeof str !== "string") {
+ throw new TypeError("Parameter 'url' must be a string, not " +
+ typeof str);
+ }
+ var start = 0;
+ var end = str.length - 1;
+
+ //Trim leading and trailing ws
+ while (str.charCodeAt(start) <= 0x20 /*' '*/) start++;
+ while (str.charCodeAt(end) <= 0x20 /*' '*/) end--;
+
+ start = this._parseProtocol(str, start, end);
+
+ //Javascript doesn't have host
+ if (this._protocol !== "javascript") {
+ start = this._parseHost(str, start, end, hostDenotesSlash);
+ var proto = this._protocol;
+ if (!this.hostname &&
+ (this.slashes || (proto && !slashProtocols[proto]))) {
+ this.hostname = this.host = "";
+ }
+ }
+
+ if (start <= end) {
+ var ch = str.charCodeAt(start);
+
+ if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) {
+ this._parsePath(str, start, end, disableAutoEscapeChars);
+ }
+ else if (ch === 0x3F /*'?'*/) {
+ this._parseQuery(str, start, end, disableAutoEscapeChars);
+ }
+ else if (ch === 0x23 /*'#'*/) {
+ this._parseHash(str, start, end, disableAutoEscapeChars);
+ }
+ else if (this._protocol !== "javascript") {
+ this._parsePath(str, start, end, disableAutoEscapeChars);
+ }
+ else { //For javascript the pathname is just the rest of it
+ this.pathname = str.slice(start, end + 1 );
+ }
+
+ }
+
+ if (!this.pathname && this.hostname &&
+ this._slashProtocols[this._protocol]) {
+ this.pathname = "/";
+ }
+
+ if (parseQueryString) {
+ var search = this.search;
+ if (search == null) {
+ search = this.search = "";
+ }
+ if (search.charCodeAt(0) === 0x3F /*'?'*/) {
+ search = search.slice(1);
+ }
+ //This calls a setter function, there is no .query data property
+ this.query = Url.queryString.parse(search);
+ }
+};
+
+Url.prototype.resolve = function Url$resolve(relative) {
+ return this.resolveObject(Url.parse(relative, false, true)).format();
+};
+
+Url.prototype.format = function Url$format() {
+ var auth = this.auth || "";
+
+ if (auth) {
+ auth = encodeURIComponent(auth);
+ auth = auth.replace(/%3A/i, ":");
+ auth += "@";
+ }
+
+ var protocol = this.protocol || "";
+ var pathname = this.pathname || "";
+ var hash = this.hash || "";
+ var search = this.search || "";
+ var query = "";
+ var hostname = this.hostname || "";
+ var port = this.port || "";
+ var host = false;
+ var scheme = "";
+
+ //Cache the result of the getter function
+ var q = this.query;
+ if (q && typeof q === "object") {
+ query = Url.queryString.stringify(q);
+ }
+
+ if (!search) {
+ search = query ? "?" + query : "";
+ }
+
+ if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/)
+ protocol += ":";
+
+ if (this.host) {
+ host = auth + this.host;
+ }
+ else if (hostname) {
+ var ip6 = hostname.indexOf(":") > -1;
+ if (ip6) hostname = "[" + hostname + "]";
+ host = auth + hostname + (port ? ":" + port : "");
+ }
+
+ var slashes = this.slashes ||
+ ((!protocol ||
+ slashProtocols[protocol]) && host !== false);
+
+
+ if (protocol) scheme = protocol + (slashes ? "//" : "");
+ else if (slashes) scheme = "//";
+
+ if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) {
+ pathname = "/" + pathname;
+ }
+ if (search && search.charCodeAt(0) !== 0x3F /*'?'*/)
+ search = "?" + search;
+ if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/)
+ hash = "#" + hash;
+
+ pathname = escapePathName(pathname);
+ search = escapeSearch(search);
+
+ return scheme + (host === false ? "" : host) + pathname + search + hash;
+};
+
+Url.prototype.resolveObject = function Url$resolveObject(relative) {
+ if (typeof relative === "string")
+ relative = Url.parse(relative, false, true);
+
+ var result = this._clone();
+
+ // hash is always overridden, no matter what.
+ // even href="" will remove it.
+ result.hash = relative.hash;
+
+ // if the relative url is empty, then there"s nothing left to do here.
+ if (!relative.href) {
+ result._href = "";
+ return result;
+ }
+
+ // hrefs like //foo/bar always cut to the protocol.
+ if (relative.slashes && !relative._protocol) {
+ relative._copyPropsTo(result, true);
+
+ if (slashProtocols[result._protocol] &&
+ result.hostname && !result.pathname) {
+ result.pathname = "/";
+ }
+ result._href = "";
+ return result;
+ }
+
+ if (relative._protocol && relative._protocol !== result._protocol) {
+ // if it"s a known url protocol, then changing
+ // the protocol does weird things
+ // first, if it"s not file:, then we MUST have a host,
+ // and if there was a path
+ // to begin with, then we MUST have a path.
+ // if it is file:, then the host is dropped,
+ // because that"s known to be hostless.
+ // anything else is assumed to be absolute.
+ if (!slashProtocols[relative._protocol]) {
+ relative._copyPropsTo(result, false);
+ result._href = "";
+ return result;
+ }
+
+ result._protocol = relative._protocol;
+ if (!relative.host && relative._protocol !== "javascript") {
+ var relPath = (relative.pathname || "").split("/");
+ while (relPath.length && !(relative.host = relPath.shift()));
+ if (!relative.host) relative.host = "";
+ if (!relative.hostname) relative.hostname = "";
+ if (relPath[0] !== "") relPath.unshift("");
+ if (relPath.length < 2) relPath.unshift("");
+ result.pathname = relPath.join("/");
+ } else {
+ result.pathname = relative.pathname;
+ }
+
+ result.search = relative.search;
+ result.host = relative.host || "";
+ result.auth = relative.auth;
+ result.hostname = relative.hostname || relative.host;
+ result._port = relative._port;
+ result.slashes = result.slashes || relative.slashes;
+ result._href = "";
+ return result;
+ }
+
+ var isSourceAbs =
+ (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/);
+ var isRelAbs = (
+ relative.host ||
+ (relative.pathname &&
+ relative.pathname.charCodeAt(0) === 0x2F /*'/'*/)
+ );
+ var mustEndAbs = (isRelAbs || isSourceAbs ||
+ (result.host && relative.pathname));
+
+ var removeAllDots = mustEndAbs;
+
+ var srcPath = result.pathname && result.pathname.split("/") || [];
+ var relPath = relative.pathname && relative.pathname.split("/") || [];
+ var psychotic = result._protocol && !slashProtocols[result._protocol];
+
+ // if the url is a non-slashed url, then relative
+ // links like ../.. should be able
+ // to crawl up to the hostname, as well. This is strange.
+ // result.protocol has already been set by now.
+ // Later on, put the first path part into the host field.
+ if (psychotic) {
+ result.hostname = "";
+ result._port = -1;
+ if (result.host) {
+ if (srcPath[0] === "") srcPath[0] = result.host;
+ else srcPath.unshift(result.host);
+ }
+ result.host = "";
+ if (relative._protocol) {
+ relative.hostname = "";
+ relative._port = -1;
+ if (relative.host) {
+ if (relPath[0] === "") relPath[0] = relative.host;
+ else relPath.unshift(relative.host);
+ }
+ relative.host = "";
+ }
+ mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === "");
+ }
+
+ if (isRelAbs) {
+ // it"s absolute.
+ result.host = relative.host ?
+ relative.host : result.host;
+ result.hostname = relative.hostname ?
+ relative.hostname : result.hostname;
+ result.search = relative.search;
+ srcPath = relPath;
+ // fall through to the dot-handling below.
+ } else if (relPath.length) {
+ // it"s relative
+ // throw away the existing file, and take the new path instead.
+ if (!srcPath) srcPath = [];
+ srcPath.pop();
+ srcPath = srcPath.concat(relPath);
+ result.search = relative.search;
+ } else if (relative.search) {
+ // just pull out the search.
+ // like href="?foo".
+ // Put this after the other two cases because it simplifies the booleans
+ if (psychotic) {
+ result.hostname = result.host = srcPath.shift();
+ //occationaly the auth can get stuck only in host
+ //this especialy happens in cases like
+ //url.resolveObject("mailto:local1@domain1", "local2@domain2")
+ var authInHost = result.host && result.host.indexOf("@") > 0 ?
+ result.host.split("@") : false;
+ if (authInHost) {
+ result.auth = authInHost.shift();
+ result.host = result.hostname = authInHost.shift();
+ }
+ }
+ result.search = relative.search;
+ result._href = "";
+ return result;
+ }
+
+ if (!srcPath.length) {
+ // no path at all. easy.
+ // we"ve already handled the other stuff above.
+ result.pathname = null;
+ result._href = "";
+ return result;
+ }
+
+ // if a url ENDs in . or .., then it must get a trailing slash.
+ // however, if it ends in anything else non-slashy,
+ // then it must NOT get a trailing slash.
+ var last = srcPath.slice(-1)[0];
+ var hasTrailingSlash = (
+ (result.host || relative.host) && (last === "." || last === "..") ||
+ last === "");
+
+ // strip single dots, resolve double dots to parent dir
+ // if the path tries to go above the root, `up` ends up > 0
+ var up = 0;
+ for (var i = srcPath.length; i >= 0; i--) {
+ last = srcPath[i];
+ if (last === ".") {
+ srcPath.splice(i, 1);
+ } else if (last === "..") {
+ srcPath.splice(i, 1);
+ up++;
+ } else if (up) {
+ srcPath.splice(i, 1);
+ up--;
+ }
+ }
+
+ // if the path is allowed to go above the root, restore leading ..s
+ if (!mustEndAbs && !removeAllDots) {
+ for (; up--; up) {
+ srcPath.unshift("..");
+ }
+ }
+
+ if (mustEndAbs && srcPath[0] !== "" &&
+ (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) {
+ srcPath.unshift("");
+ }
+
+ if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) {
+ srcPath.push("");
+ }
+
+ var isAbsolute = srcPath[0] === "" ||
+ (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/);
+
+ // put the host back
+ if (psychotic) {
+ result.hostname = result.host = isAbsolute ? "" :
+ srcPath.length ? srcPath.shift() : "";
+ //occationaly the auth can get stuck only in host
+ //this especialy happens in cases like
+ //url.resolveObject("mailto:local1@domain1", "local2@domain2")
+ var authInHost = result.host && result.host.indexOf("@") > 0 ?
+ result.host.split("@") : false;
+ if (authInHost) {
+ result.auth = authInHost.shift();
+ result.host = result.hostname = authInHost.shift();
+ }
+ }
+
+ mustEndAbs = mustEndAbs || (result.host && srcPath.length);
+
+ if (mustEndAbs && !isAbsolute) {
+ srcPath.unshift("");
+ }
+
+ result.pathname = srcPath.length === 0 ? null : srcPath.join("/");
+ result.auth = relative.auth || result.auth;
+ result.slashes = result.slashes || relative.slashes;
+ result._href = "";
+ return result;
+};
+
+var punycode$2 = require$$0$l;
+Url.prototype._hostIdna = function Url$_hostIdna(hostname) {
+ // IDNA Support: Returns a punycoded representation of "domain".
+ // It only converts parts of the domain name that
+ // have non-ASCII characters, i.e. it doesn't matter if
+ // you call it with a domain that already is ASCII-only.
+ return punycode$2.toASCII(hostname);
+};
+
+var escapePathName = Url.prototype._escapePathName =
+function Url$_escapePathName(pathname) {
+ if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) {
+ return pathname;
+ }
+ //Avoid closure creation to keep this inlinable
+ return _escapePath(pathname);
+};
+
+var escapeSearch = Url.prototype._escapeSearch =
+function Url$_escapeSearch(search) {
+ if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search;
+ //Avoid closure creation to keep this inlinable
+ return _escapeSearch(search);
+};
+
+Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) {
+ var doLowerCase = false;
+ var protocolCharacters = this._protocolCharacters;
+
+ for (var i = start; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+
+ if (ch === 0x3A /*':'*/) {
+ var protocol = str.slice(start, i);
+ if (doLowerCase) protocol = protocol.toLowerCase();
+ this._protocol = protocol;
+ return i + 1;
+ }
+ else if (protocolCharacters[ch] === 1) {
+ if (ch < 0x61 /*'a'*/)
+ doLowerCase = true;
+ }
+ else {
+ return start;
+ }
+
+ }
+ return start;
+};
+
+Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) {
+ var auth = str.slice(start, end + 1);
+ if (decode) {
+ auth = decodeURIComponent(auth);
+ }
+ this.auth = auth;
+};
+
+Url.prototype._parsePort = function Url$_parsePort(str, start, end) {
+ //Internal format is integer for more efficient parsing
+ //and for efficient trimming of leading zeros
+ var port = 0;
+ //Distinguish between :0 and : (no port number at all)
+ var hadChars = false;
+ var validPort = true;
+
+ for (var i = start; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+
+ if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) {
+ port = (10 * port) + (ch - 0x30 /*'0'*/);
+ hadChars = true;
+ }
+ else {
+ validPort = false;
+ if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) {
+ validPort = true;
+ }
+ break;
+ }
+
+ }
+ if ((port === 0 && !hadChars) || !validPort) {
+ if (!validPort) {
+ this._port = -2;
+ }
+ return 0;
+ }
+
+ this._port = port;
+ return i - start;
+};
+
+Url.prototype._parseHost =
+function Url$_parseHost(str, start, end, slashesDenoteHost) {
+ var hostEndingCharacters = this._hostEndingCharacters;
+ var first = str.charCodeAt(start);
+ var second = str.charCodeAt(start + 1);
+ if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) &&
+ (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) {
+ this.slashes = true;
+
+ //The string starts with //
+ if (start === 0) {
+ //The string is just "//"
+ if (end < 2) return start;
+ //If slashes do not denote host and there is no auth,
+ //there is no host when the string starts with //
+ var hasAuth =
+ containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters);
+ if (!hasAuth && !slashesDenoteHost) {
+ this.slashes = null;
+ return start;
+ }
+ }
+ //There is a host that starts after the //
+ start += 2;
+ }
+ //If there is no slashes, there is no hostname if
+ //1. there was no protocol at all
+ else if (!this._protocol ||
+ //2. there was a protocol that requires slashes
+ //e.g. in 'http:asd' 'asd' is not a hostname
+ slashProtocols[this._protocol]
+ ) {
+ return start;
+ }
+
+ var doLowerCase = false;
+ var idna = false;
+ var hostNameStart = start;
+ var hostNameEnd = end;
+ var portLength = 0;
+ var charsAfterDot = 0;
+ var authNeedsDecoding = false;
+
+ var j = -1;
+
+ //Find the last occurrence of an @-sign until hostending character is met
+ //also mark if decoding is needed for the auth portion
+ for (var i = start; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+
+ if (ch === 0x40 /*'@'*/) {
+ j = i;
+ }
+ //This check is very, very cheap. Unneeded decodeURIComponent is very
+ //very expensive
+ else if (ch === 0x25 /*'%'*/) {
+ authNeedsDecoding = true;
+ }
+ else if (hostEndingCharacters[ch] === 1) {
+ break;
+ }
+ }
+
+ //@-sign was found at index j, everything to the left from it
+ //is auth part
+ if (j > -1) {
+ this._parseAuth(str, start, j - 1, authNeedsDecoding);
+ //hostname starts after the last @-sign
+ start = hostNameStart = j + 1;
+ }
+
+ //Host name is starting with a [
+ if (str.charCodeAt(start) === 0x5B /*'['*/) {
+ for (var i = start + 1; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+
+ //Assume valid IP6 is between the brackets
+ if (ch === 0x5D /*']'*/) {
+ if (str.charCodeAt(i + 1) === 0x3A /*':'*/) {
+ portLength = this._parsePort(str, i + 2, end) + 1;
+ }
+ var hostname = str.slice(start + 1, i).toLowerCase();
+ this.hostname = hostname;
+ this.host = this._port > 0 ?
+ "[" + hostname + "]:" + this._port :
+ "[" + hostname + "]";
+ this.pathname = "/";
+ return i + portLength + 1;
+ }
+ }
+ //Empty hostname, [ starts a path
+ return start;
+ }
+
+ for (var i = start; i <= end; ++i) {
+ if (charsAfterDot > 62) {
+ this.hostname = this.host = str.slice(start, i);
+ return i;
+ }
+ var ch = str.charCodeAt(i);
+
+ if (ch === 0x3A /*':'*/) {
+ portLength = this._parsePort(str, i + 1, end) + 1;
+ hostNameEnd = i - 1;
+ break;
+ }
+ else if (ch < 0x61 /*'a'*/) {
+ if (ch === 0x2E /*'.'*/) {
+ //Node.js ignores this error
+ /*
+ if (lastCh === DOT || lastCh === -1) {
+ this.hostname = this.host = "";
+ return start;
+ }
+ */
+ charsAfterDot = -1;
+ }
+ else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) {
+ doLowerCase = true;
+ }
+ //Valid characters other than ASCII letters -, _, +, 0-9
+ else if (!(ch === 0x2D /*'-'*/ ||
+ ch === 0x5F /*'_'*/ ||
+ ch === 0x2B /*'+'*/ ||
+ (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/))
+ ) {
+ if (hostEndingCharacters[ch] === 0 &&
+ this._noPrependSlashHostEnders[ch] === 0) {
+ this._prependSlash = true;
+ }
+ hostNameEnd = i - 1;
+ break;
+ }
+ }
+ else if (ch >= 0x7B /*'{'*/) {
+ if (ch <= 0x7E /*'~'*/) {
+ if (this._noPrependSlashHostEnders[ch] === 0) {
+ this._prependSlash = true;
+ }
+ hostNameEnd = i - 1;
+ break;
+ }
+ idna = true;
+ }
+ charsAfterDot++;
+ }
+
+ //Node.js ignores this error
+ /*
+ if (lastCh === DOT) {
+ hostNameEnd--;
+ }
+ */
+
+ if (hostNameEnd + 1 !== start &&
+ hostNameEnd - hostNameStart <= 256) {
+ var hostname = str.slice(hostNameStart, hostNameEnd + 1);
+ if (doLowerCase) hostname = hostname.toLowerCase();
+ if (idna) hostname = this._hostIdna(hostname);
+ this.hostname = hostname;
+ this.host = this._port > 0 ? hostname + ":" + this._port : hostname;
+ }
+
+ return hostNameEnd + 1 + portLength;
+
+};
+
+Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) {
+ if (!noProtocol) {
+ input._protocol = this._protocol;
+ }
+ input._href = this._href;
+ input._port = this._port;
+ input._prependSlash = this._prependSlash;
+ input.auth = this.auth;
+ input.slashes = this.slashes;
+ input.host = this.host;
+ input.hostname = this.hostname;
+ input.hash = this.hash;
+ input.search = this.search;
+ input.pathname = this.pathname;
+};
+
+Url.prototype._clone = function Url$_clone() {
+ var ret = new Url();
+ ret._protocol = this._protocol;
+ ret._href = this._href;
+ ret._port = this._port;
+ ret._prependSlash = this._prependSlash;
+ ret.auth = this.auth;
+ ret.slashes = this.slashes;
+ ret.host = this.host;
+ ret.hostname = this.hostname;
+ ret.hash = this.hash;
+ ret.search = this.search;
+ ret.pathname = this.pathname;
+ return ret;
+};
+
+Url.prototype._getComponentEscaped =
+function Url$_getComponentEscaped(str, start, end, isAfterQuery) {
+ var cur = start;
+ var i = start;
+ var ret = "";
+ var autoEscapeMap = isAfterQuery ?
+ this._afterQueryAutoEscapeMap : this._autoEscapeMap;
+ for (; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+ var escaped = autoEscapeMap[ch];
+
+ if (escaped !== "" && escaped !== undefined) {
+ if (cur < i) ret += str.slice(cur, i);
+ ret += escaped;
+ cur = i + 1;
+ }
+ }
+ if (cur < i + 1) ret += str.slice(cur, i);
+ return ret;
+};
+
+Url.prototype._parsePath =
+function Url$_parsePath(str, start, end, disableAutoEscapeChars) {
+ var pathStart = start;
+ var pathEnd = end;
+ var escape = false;
+ var autoEscapeCharacters = this._autoEscapeCharacters;
+ var prePath = this._port === -2 ? "/:" : "";
+
+ for (var i = start; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+ if (ch === 0x23 /*'#'*/) {
+ this._parseHash(str, i, end, disableAutoEscapeChars);
+ pathEnd = i - 1;
+ break;
+ }
+ else if (ch === 0x3F /*'?'*/) {
+ this._parseQuery(str, i, end, disableAutoEscapeChars);
+ pathEnd = i - 1;
+ break;
+ }
+ else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) {
+ escape = true;
+ }
+ }
+
+ if (pathStart > pathEnd) {
+ this.pathname = prePath === "" ? "/" : prePath;
+ return;
+ }
+
+ var path;
+ if (escape) {
+ path = this._getComponentEscaped(str, pathStart, pathEnd, false);
+ }
+ else {
+ path = str.slice(pathStart, pathEnd + 1);
+ }
+ this.pathname = prePath === ""
+ ? (this._prependSlash ? "/" + path : path)
+ : prePath + path;
+};
+
+Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) {
+ var queryStart = start;
+ var queryEnd = end;
+ var escape = false;
+ var autoEscapeCharacters = this._autoEscapeCharacters;
+
+ for (var i = start; i <= end; ++i) {
+ var ch = str.charCodeAt(i);
+
+ if (ch === 0x23 /*'#'*/) {
+ this._parseHash(str, i, end, disableAutoEscapeChars);
+ queryEnd = i - 1;
+ break;
+ }
+ else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) {
+ escape = true;
+ }
+ }
+
+ if (queryStart > queryEnd) {
+ this.search = "";
+ return;
+ }
+
+ var query;
+ if (escape) {
+ query = this._getComponentEscaped(str, queryStart, queryEnd, true);
+ }
+ else {
+ query = str.slice(queryStart, queryEnd + 1);
+ }
+ this.search = query;
+};
+
+Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) {
+ if (start > end) {
+ this.hash = "";
+ return;
+ }
+
+ this.hash = disableAutoEscapeChars ?
+ str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true);
+};
+
+Object.defineProperty(Url.prototype, "port", {
+ get: function() {
+ if (this._port >= 0) {
+ return ("" + this._port);
+ }
+ return null;
+ },
+ set: function(v) {
+ if (v == null) {
+ this._port = -1;
+ }
+ else {
+ this._port = parseInt(v, 10);
+ }
+ }
+});
+
+Object.defineProperty(Url.prototype, "query", {
+ get: function() {
+ var query = this._query;
+ if (query != null) {
+ return query;
+ }
+ var search = this.search;
+
+ if (search) {
+ if (search.charCodeAt(0) === 0x3F /*'?'*/) {
+ search = search.slice(1);
+ }
+ if (search !== "") {
+ this._query = search;
+ return search;
+ }
+ }
+ return search;
+ },
+ set: function(v) {
+ this._query = v;
+ }
+});
+
+Object.defineProperty(Url.prototype, "path", {
+ get: function() {
+ var p = this.pathname || "";
+ var s = this.search || "";
+ if (p || s) {
+ return p + s;
+ }
+ return (p == null && s) ? ("/" + s) : null;
+ },
+ set: function() {}
+});
+
+Object.defineProperty(Url.prototype, "protocol", {
+ get: function() {
+ var proto = this._protocol;
+ return proto ? proto + ":" : proto;
+ },
+ set: function(v) {
+ if (typeof v === "string") {
+ var end = v.length - 1;
+ if (v.charCodeAt(end) === 0x3A /*':'*/) {
+ this._protocol = v.slice(0, end);
+ }
+ else {
+ this._protocol = v;
+ }
+ }
+ else if (v == null) {
+ this._protocol = null;
+ }
+ }
+});
+
+Object.defineProperty(Url.prototype, "href", {
+ get: function() {
+ var href = this._href;
+ if (!href) {
+ href = this._href = this.format();
+ }
+ return href;
+ },
+ set: function(v) {
+ this._href = v;
+ }
+});
+
+Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) {
+ if (str instanceof Url) return str;
+ var ret = new Url();
+ ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars);
+ return ret;
+};
+
+Url.format = function Url$Format(obj) {
+ if (typeof obj === "string") {
+ obj = Url.parse(obj);
+ }
+ if (!(obj instanceof Url)) {
+ return Url.prototype.format.call(obj);
+ }
+ return obj.format();
+};
+
+Url.resolve = function Url$Resolve(source, relative) {
+ return Url.parse(source, false, true).resolve(relative);
+};
+
+Url.resolveObject = function Url$ResolveObject(source, relative) {
+ if (!source) return relative;
+ return Url.parse(source, false, true).resolveObject(relative);
+};
+
+function _escapePath(pathname) {
+ return pathname.replace(/[?#]/g, function(match) {
+ return encodeURIComponent(match);
+ });
+}
+
+function _escapeSearch(search) {
+ return search.replace(/#/g, function(match) {
+ return encodeURIComponent(match);
+ });
+}
+
+//Search `char1` (integer code for a character) in `string`
+//starting from `fromIndex` and ending at `string.length - 1`
+//or when a stop character is found
+function containsCharacter(string, char1, fromIndex, stopCharacterTable) {
+ var len = string.length;
+ for (var i = fromIndex; i < len; ++i) {
+ var ch = string.charCodeAt(i);
+
+ if (ch === char1) {
+ return true;
+ }
+ else if (stopCharacterTable[ch] === 1) {
+ return false;
+ }
+ }
+ return false;
+}
+
+//See if `char1` or `char2` (integer codes for characters)
+//is contained in `string`
+function containsCharacter2(string, char1, char2) {
+ for (var i = 0, len = string.length; i < len; ++i) {
+ var ch = string.charCodeAt(i);
+ if (ch === char1 || ch === char2) return true;
+ }
+ return false;
+}
+
+//Makes an array of 128 uint8's which represent boolean values.
+//Spec is an array of ascii code points or ascii code point ranges
+//ranges are expressed as [start, end]
+
+//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and
+//0x7A (lowercaseletter 'z') as `true`:
+//
+//var a = makeAsciiTable([[0x30, 0x39], 0x7A]);
+//a[0x30]; //1
+//a[0x15]; //0
+//a[0x35]; //1
+function makeAsciiTable(spec) {
+ var ret = new Uint8Array(128);
+ spec.forEach(function(item){
+ if (typeof item === "number") {
+ ret[item] = 1;
+ }
+ else {
+ var start = item[0];
+ var end = item[1];
+ for (var j = start; j <= end; ++j) {
+ ret[j] = 1;
+ }
+ }
+ });
+
+ return ret;
+}
+
+
+var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n",
+ "\t", "{", "}", "|", "\\", "^", "`", "'"];
+
+var autoEscapeMap = new Array(128);
+
+
+
+for (var i$4 = 0, len = autoEscapeMap.length; i$4 < len; ++i$4) {
+ autoEscapeMap[i$4] = "";
+}
+
+for (var i$4 = 0, len = autoEscape.length; i$4 < len; ++i$4) {
+ var c = autoEscape[i$4];
+ var esc = encodeURIComponent(c);
+ if (esc === c) {
+ esc = escape(c);
+ }
+ autoEscapeMap[c.charCodeAt(0)] = esc;
+}
+var afterQueryAutoEscapeMap = autoEscapeMap.slice();
+autoEscapeMap[0x5C /*'\'*/] = "/";
+
+var slashProtocols = Url.prototype._slashProtocols = {
+ http: true,
+ https: true,
+ gopher: true,
+ file: true,
+ ftp: true,
+
+ "http:": true,
+ "https:": true,
+ "gopher:": true,
+ "file:": true,
+ "ftp:": true
+};
+
+Url.prototype._protocolCharacters = makeAsciiTable([
+ [0x61 /*'a'*/, 0x7A /*'z'*/],
+ [0x41 /*'A'*/, 0x5A /*'Z'*/],
+ 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/
+]);
+
+Url.prototype._hostEndingCharacters = makeAsciiTable([
+ 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/
+]);
+
+Url.prototype._autoEscapeCharacters = makeAsciiTable(
+ autoEscape.map(function(v) {
+ return v.charCodeAt(0);
+ })
+);
+
+//If these characters end a host name, the path will not be prepended a /
+Url.prototype._noPrependSlashHostEnders = makeAsciiTable(
+ [
+ "<", ">", "'", "`", " ", "\r",
+ "\n", "\t", "{", "}", "|",
+ "^", "`", "\"", "%", ";"
+ ].map(function(v) {
+ return v.charCodeAt(0);
+ })
+);
+
+Url.prototype._autoEscapeMap = autoEscapeMap;
+Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap;
+
+var urlparser = Url;
+
+Url.replace = function Url$Replace() {
+ require.cache.url = {
+ exports: Url
+ };
+};
+
+var pino$4 = pinoExports$1;
+var serializers$1 = pinoStdSerializers$1;
+var URL$3 = urlparser;
+var startTime = Symbol('startTime');
+
+function pinoLogger (opts, stream) {
+ if (opts && opts._writableState) {
+ stream = opts;
+ opts = null;
+ }
+
+ opts = Object.assign({}, opts);
+
+ opts.customAttributeKeys = opts.customAttributeKeys || {};
+ var reqKey = opts.customAttributeKeys.req || 'req';
+ var resKey = opts.customAttributeKeys.res || 'res';
+ var errKey = opts.customAttributeKeys.err || 'err';
+ var requestIdKey = opts.customAttributeKeys.reqId || 'reqId';
+ var responseTimeKey = opts.customAttributeKeys.responseTime || 'responseTime';
+ delete opts.customAttributeKeys;
+
+ var customProps = opts.customProps || opts.reqCustomProps || {};
+
+ opts.wrapSerializers = 'wrapSerializers' in opts ? opts.wrapSerializers : true;
+ if (opts.wrapSerializers) {
+ opts.serializers = Object.assign({}, opts.serializers);
+ var requestSerializer = opts.serializers[reqKey] || opts.serializers.req || serializers$1.req;
+ var responseSerializer = opts.serializers[resKey] || opts.serializers.res || serializers$1.res;
+ var errorSerializer = opts.serializers[errKey] || opts.serializers.err || serializers$1.err;
+ opts.serializers[reqKey] = serializers$1.wrapRequestSerializer(requestSerializer);
+ opts.serializers[resKey] = serializers$1.wrapResponseSerializer(responseSerializer);
+ opts.serializers[errKey] = serializers$1.wrapErrorSerializer(errorSerializer);
+ }
+ delete opts.wrapSerializers;
+
+ if (opts.useLevel && opts.customLogLevel) {
+ throw new Error("You can't pass 'useLevel' and 'customLogLevel' together")
+ }
+
+ var useLevel = opts.useLevel || 'info';
+ var customLogLevel = opts.customLogLevel;
+ delete opts.useLevel;
+ delete opts.customLogLevel;
+
+ var theStream = opts.stream || stream;
+ delete opts.stream;
+
+ var autoLogging = (opts.autoLogging !== false);
+ var autoLoggingIgnore = opts.autoLogging && opts.autoLogging.ignore ? opts.autoLogging.ignore : null;
+ var autoLoggingIgnorePaths = (opts.autoLogging && opts.autoLogging.ignorePaths) ? opts.autoLogging.ignorePaths : [];
+ var autoLoggingGetPath = opts.autoLogging && opts.autoLogging.getPath ? opts.autoLogging.getPath : null;
+ delete opts.autoLogging;
+
+ var successMessage = opts.customSuccessMessage || function () { return 'request completed' };
+ var errorMessage = opts.customErrorMessage || function () { return 'request errored' };
+ delete opts.customSuccessfulMessage;
+ delete opts.customErroredMessage;
+
+ var quietReqLogger = !!opts.quietReqLogger;
+
+ var logger = wrapChild(opts, theStream);
+ var genReqId = reqIdGenFactory(opts.genReqId);
+ loggingMiddleware.logger = logger;
+ return loggingMiddleware
+
+ function onResFinished (err) {
+ this.removeListener('error', onResFinished);
+ this.removeListener('finish', onResFinished);
+
+ var log = this.log;
+ var responseTime = Date.now() - this[startTime];
+ var level = customLogLevel ? customLogLevel(this, err) : useLevel;
+
+ if (err || this.err || this.statusCode >= 500) {
+ var error = err || this.err || new Error('failed with status code ' + this.statusCode);
+
+ log[level]({
+ [resKey]: this,
+ [errKey]: error,
+ [responseTimeKey]: responseTime
+ }, errorMessage(error, this));
+ return
+ }
+
+ log[level]({
+ [resKey]: this,
+ [responseTimeKey]: responseTime
+ }, successMessage(this));
+ }
+
+ function loggingMiddleware (req, res, next) {
+ var shouldLogSuccess = true;
+
+ req.id = genReqId(req);
+
+ var log = quietReqLogger ? logger.child({ [requestIdKey]: req.id }) : logger;
+
+ var fullReqLogger = log.child({ [reqKey]: req });
+ var customPropBindings = (typeof customProps === 'function') ? customProps(req, res) : customProps;
+ fullReqLogger = fullReqLogger.child(customPropBindings);
+
+ res.log = fullReqLogger;
+ req.log = quietReqLogger ? log : fullReqLogger;
+
+ res[startTime] = res[startTime] || Date.now();
+
+ if (autoLogging) {
+ if (autoLoggingIgnorePaths.length) {
+ var url;
+ if (autoLoggingGetPath) {
+ url = URL$3.parse(autoLoggingGetPath(req));
+ } else {
+ url = URL$3.parse(req.url);
+ }
+
+ const isPathIgnored = autoLoggingIgnorePaths.find(ignorePath => {
+ if (ignorePath instanceof RegExp) {
+ return ignorePath.test(url.pathname)
+ }
+
+ return ignorePath === url.pathname
+ });
+
+ shouldLogSuccess = !isPathIgnored;
+ }
+
+ if (autoLoggingIgnore !== null && shouldLogSuccess === true) {
+ const isIgnored = autoLoggingIgnore !== null && autoLoggingIgnore(req);
+ shouldLogSuccess = !isIgnored;
+ }
+
+ if (shouldLogSuccess) {
+ res.on('finish', onResFinished);
+ }
+
+ res.on('error', onResFinished);
+ }
+
+ if (next) {
+ next();
+ }
+ }
+}
+
+function wrapChild (opts, stream) {
+ var prevLogger = opts.logger;
+ var prevGenReqId = opts.genReqId;
+ var logger = null;
+
+ if (prevLogger) {
+ opts.logger = undefined;
+ opts.genReqId = undefined;
+ logger = prevLogger.child({}, opts);
+ opts.logger = prevLogger;
+ opts.genReqId = prevGenReqId;
+ } else {
+ logger = pino$4(opts, stream);
+ }
+
+ return logger
+}
+
+function reqIdGenFactory (func) {
+ if (typeof func === 'function') return func
+ var maxInt = 2147483647;
+ var nextReqId = 0;
+ return function genReqId (req) {
+ return req.id || (nextReqId = (nextReqId + 1) & maxInt)
+ }
+}
+
+logger$2.exports = pinoLogger;
+loggerExports$1.stdSerializers = {
+ err: serializers$1.err,
+ req: serializers$1.req,
+ res: serializers$1.res
+};
+loggerExports$1.startTime = startTime;
+
+// Unique ID creation requires a high quality random # generator. In the browser we therefore
+// require the crypto API and do not support built-in fallback to lower quality random number
+// generators (like Math.random()).
+var getRandomValues$2;
+var rnds8$2 = new Uint8Array(16);
+function rng$2() {
+ // lazy load so that environments that need to polyfill have a chance to do so
+ if (!getRandomValues$2) {
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
+ // find the complete implementation of crypto (msCrypto) on IE11.
+ getRandomValues$2 = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
+
+ if (!getRandomValues$2) {
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
+ }
+ }
+
+ return getRandomValues$2(rnds8$2);
+}
+
+var REGEX$1 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
+
+function validate$2(uuid) {
+ return typeof uuid === 'string' && REGEX$1.test(uuid);
+}
+
+/**
+ * Convert array of 16 byte values to UUID string format of the form:
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+ */
+
+var byteToHex$2 = [];
+
+for (var i$3 = 0; i$3 < 256; ++i$3) {
+ byteToHex$2.push((i$3 + 0x100).toString(16).substr(1));
+}
+
+function stringify$4(arr) {
+ var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ // Note: Be careful editing this code! It's been tuned for performance
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
+ var uuid = (byteToHex$2[arr[offset + 0]] + byteToHex$2[arr[offset + 1]] + byteToHex$2[arr[offset + 2]] + byteToHex$2[arr[offset + 3]] + '-' + byteToHex$2[arr[offset + 4]] + byteToHex$2[arr[offset + 5]] + '-' + byteToHex$2[arr[offset + 6]] + byteToHex$2[arr[offset + 7]] + '-' + byteToHex$2[arr[offset + 8]] + byteToHex$2[arr[offset + 9]] + '-' + byteToHex$2[arr[offset + 10]] + byteToHex$2[arr[offset + 11]] + byteToHex$2[arr[offset + 12]] + byteToHex$2[arr[offset + 13]] + byteToHex$2[arr[offset + 14]] + byteToHex$2[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
+ // of the following:
+ // - One or more input array values don't map to a hex octet (leading to
+ // "undefined" in the uuid)
+ // - Invalid input values for the RFC `version` or `variant` fields
+
+ if (!validate$2(uuid)) {
+ throw TypeError('Stringified UUID is invalid');
+ }
+
+ return uuid;
+}
+
+//
+// Inspired by https://github.com/LiosK/UUID.js
+// and http://docs.python.org/library/uuid.html
+
+var _nodeId$1;
+
+var _clockseq$1; // Previous uuid creation time
+
+
+var _lastMSecs$1 = 0;
+var _lastNSecs$1 = 0; // See https://github.com/uuidjs/uuid for API details
+
+function v1$1(options, buf, offset) {
+ var i = buf && offset || 0;
+ var b = buf || new Array(16);
+ options = options || {};
+ var node = options.node || _nodeId$1;
+ var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq$1; // node and clockseq need to be initialized to random values if they're not
+ // specified. We do this lazily to minimize issues related to insufficient
+ // system entropy. See #189
+
+ if (node == null || clockseq == null) {
+ var seedBytes = options.random || (options.rng || rng$2)();
+
+ if (node == null) {
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
+ node = _nodeId$1 = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
+ }
+
+ if (clockseq == null) {
+ // Per 4.2.2, randomize (14 bit) clockseq
+ clockseq = _clockseq$1 = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
+ }
+ } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+
+
+ var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
+ // cycle to simulate higher resolution clock
+
+ var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs$1 + 1; // Time since last uuid creation (in msecs)
+
+ var dt = msecs - _lastMSecs$1 + (nsecs - _lastNSecs$1) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
+
+ if (dt < 0 && options.clockseq === undefined) {
+ clockseq = clockseq + 1 & 0x3fff;
+ } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
+ // time interval
+
+
+ if ((dt < 0 || msecs > _lastMSecs$1) && options.nsecs === undefined) {
+ nsecs = 0;
+ } // Per 4.2.1.2 Throw error if too many uuids are requested
+
+
+ if (nsecs >= 10000) {
+ throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
+ }
+
+ _lastMSecs$1 = msecs;
+ _lastNSecs$1 = nsecs;
+ _clockseq$1 = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+
+ msecs += 12219292800000; // `time_low`
+
+ var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
+ b[i++] = tl >>> 24 & 0xff;
+ b[i++] = tl >>> 16 & 0xff;
+ b[i++] = tl >>> 8 & 0xff;
+ b[i++] = tl & 0xff; // `time_mid`
+
+ var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
+ b[i++] = tmh >>> 8 & 0xff;
+ b[i++] = tmh & 0xff; // `time_high_and_version`
+
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+
+ b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+
+ b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
+
+ b[i++] = clockseq & 0xff; // `node`
+
+ for (var n = 0; n < 6; ++n) {
+ b[i + n] = node[n];
+ }
+
+ return buf || stringify$4(b);
+}
+
+function parse$5(uuid) {
+ if (!validate$2(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ var v;
+ var arr = new Uint8Array(16); // Parse ########-....-....-....-............
+
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
+ arr[1] = v >>> 16 & 0xff;
+ arr[2] = v >>> 8 & 0xff;
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
+
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
+
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
+
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
+
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
+ arr[11] = v / 0x100000000 & 0xff;
+ arr[12] = v >>> 24 & 0xff;
+ arr[13] = v >>> 16 & 0xff;
+ arr[14] = v >>> 8 & 0xff;
+ arr[15] = v & 0xff;
+ return arr;
+}
+
+function stringToBytes$1(str) {
+ str = unescape(encodeURIComponent(str)); // UTF8 escape
+
+ var bytes = [];
+
+ for (var i = 0; i < str.length; ++i) {
+ bytes.push(str.charCodeAt(i));
+ }
+
+ return bytes;
+}
+
+var DNS$1 = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+var URL$2 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
+function v35$1 (name, version, hashfunc) {
+ function generateUUID(value, namespace, buf, offset) {
+ if (typeof value === 'string') {
+ value = stringToBytes$1(value);
+ }
+
+ if (typeof namespace === 'string') {
+ namespace = parse$5(namespace);
+ }
+
+ if (namespace.length !== 16) {
+ throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
+ } // Compute hash of namespace and value, Per 4.3
+ // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
+ // hashfunc([...namespace, ... value])`
+
+
+ var bytes = new Uint8Array(16 + value.length);
+ bytes.set(namespace);
+ bytes.set(value, namespace.length);
+ bytes = hashfunc(bytes);
+ bytes[6] = bytes[6] & 0x0f | version;
+ bytes[8] = bytes[8] & 0x3f | 0x80;
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (var i = 0; i < 16; ++i) {
+ buf[offset + i] = bytes[i];
+ }
+
+ return buf;
+ }
+
+ return stringify$4(bytes);
+ } // Function#name is not settable on some platforms (#270)
+
+
+ try {
+ generateUUID.name = name; // eslint-disable-next-line no-empty
+ } catch (err) {} // For CommonJS default export support
+
+
+ generateUUID.DNS = DNS$1;
+ generateUUID.URL = URL$2;
+ return generateUUID;
+}
+
+/*
+ * Browser-compatible JavaScript MD5
+ *
+ * Modification of JavaScript MD5
+ * https://github.com/blueimp/JavaScript-MD5
+ *
+ * Copyright 2011, Sebastian Tschan
+ * https://blueimp.net
+ *
+ * Licensed under the MIT license:
+ * https://opensource.org/licenses/MIT
+ *
+ * Based on
+ * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
+ * Digest Algorithm, as defined in RFC 1321.
+ * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
+ * Distributed under the BSD License
+ * See http://pajhome.org.uk/crypt/md5 for more info.
+ */
+function md5$1(bytes) {
+ if (typeof bytes === 'string') {
+ var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
+
+ bytes = new Uint8Array(msg.length);
+
+ for (var i = 0; i < msg.length; ++i) {
+ bytes[i] = msg.charCodeAt(i);
+ }
+ }
+
+ return md5ToHexEncodedArray$1(wordsToMd5$1(bytesToWords$1(bytes), bytes.length * 8));
+}
+/*
+ * Convert an array of little-endian words to an array of bytes
+ */
+
+
+function md5ToHexEncodedArray$1(input) {
+ var output = [];
+ var length32 = input.length * 32;
+ var hexTab = '0123456789abcdef';
+
+ for (var i = 0; i < length32; i += 8) {
+ var x = input[i >> 5] >>> i % 32 & 0xff;
+ var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
+ output.push(hex);
+ }
+
+ return output;
+}
+/**
+ * Calculate output length with padding and bit length
+ */
+
+
+function getOutputLength$1(inputLength8) {
+ return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
+}
+/*
+ * Calculate the MD5 of an array of little-endian words, and a bit length.
+ */
+
+
+function wordsToMd5$1(x, len) {
+ /* append padding */
+ x[len >> 5] |= 0x80 << len % 32;
+ x[getOutputLength$1(len) - 1] = len;
+ var a = 1732584193;
+ var b = -271733879;
+ var c = -1732584194;
+ var d = 271733878;
+
+ for (var i = 0; i < x.length; i += 16) {
+ var olda = a;
+ var oldb = b;
+ var oldc = c;
+ var oldd = d;
+ a = md5ff$1(a, b, c, d, x[i], 7, -680876936);
+ d = md5ff$1(d, a, b, c, x[i + 1], 12, -389564586);
+ c = md5ff$1(c, d, a, b, x[i + 2], 17, 606105819);
+ b = md5ff$1(b, c, d, a, x[i + 3], 22, -1044525330);
+ a = md5ff$1(a, b, c, d, x[i + 4], 7, -176418897);
+ d = md5ff$1(d, a, b, c, x[i + 5], 12, 1200080426);
+ c = md5ff$1(c, d, a, b, x[i + 6], 17, -1473231341);
+ b = md5ff$1(b, c, d, a, x[i + 7], 22, -45705983);
+ a = md5ff$1(a, b, c, d, x[i + 8], 7, 1770035416);
+ d = md5ff$1(d, a, b, c, x[i + 9], 12, -1958414417);
+ c = md5ff$1(c, d, a, b, x[i + 10], 17, -42063);
+ b = md5ff$1(b, c, d, a, x[i + 11], 22, -1990404162);
+ a = md5ff$1(a, b, c, d, x[i + 12], 7, 1804603682);
+ d = md5ff$1(d, a, b, c, x[i + 13], 12, -40341101);
+ c = md5ff$1(c, d, a, b, x[i + 14], 17, -1502002290);
+ b = md5ff$1(b, c, d, a, x[i + 15], 22, 1236535329);
+ a = md5gg$1(a, b, c, d, x[i + 1], 5, -165796510);
+ d = md5gg$1(d, a, b, c, x[i + 6], 9, -1069501632);
+ c = md5gg$1(c, d, a, b, x[i + 11], 14, 643717713);
+ b = md5gg$1(b, c, d, a, x[i], 20, -373897302);
+ a = md5gg$1(a, b, c, d, x[i + 5], 5, -701558691);
+ d = md5gg$1(d, a, b, c, x[i + 10], 9, 38016083);
+ c = md5gg$1(c, d, a, b, x[i + 15], 14, -660478335);
+ b = md5gg$1(b, c, d, a, x[i + 4], 20, -405537848);
+ a = md5gg$1(a, b, c, d, x[i + 9], 5, 568446438);
+ d = md5gg$1(d, a, b, c, x[i + 14], 9, -1019803690);
+ c = md5gg$1(c, d, a, b, x[i + 3], 14, -187363961);
+ b = md5gg$1(b, c, d, a, x[i + 8], 20, 1163531501);
+ a = md5gg$1(a, b, c, d, x[i + 13], 5, -1444681467);
+ d = md5gg$1(d, a, b, c, x[i + 2], 9, -51403784);
+ c = md5gg$1(c, d, a, b, x[i + 7], 14, 1735328473);
+ b = md5gg$1(b, c, d, a, x[i + 12], 20, -1926607734);
+ a = md5hh$1(a, b, c, d, x[i + 5], 4, -378558);
+ d = md5hh$1(d, a, b, c, x[i + 8], 11, -2022574463);
+ c = md5hh$1(c, d, a, b, x[i + 11], 16, 1839030562);
+ b = md5hh$1(b, c, d, a, x[i + 14], 23, -35309556);
+ a = md5hh$1(a, b, c, d, x[i + 1], 4, -1530992060);
+ d = md5hh$1(d, a, b, c, x[i + 4], 11, 1272893353);
+ c = md5hh$1(c, d, a, b, x[i + 7], 16, -155497632);
+ b = md5hh$1(b, c, d, a, x[i + 10], 23, -1094730640);
+ a = md5hh$1(a, b, c, d, x[i + 13], 4, 681279174);
+ d = md5hh$1(d, a, b, c, x[i], 11, -358537222);
+ c = md5hh$1(c, d, a, b, x[i + 3], 16, -722521979);
+ b = md5hh$1(b, c, d, a, x[i + 6], 23, 76029189);
+ a = md5hh$1(a, b, c, d, x[i + 9], 4, -640364487);
+ d = md5hh$1(d, a, b, c, x[i + 12], 11, -421815835);
+ c = md5hh$1(c, d, a, b, x[i + 15], 16, 530742520);
+ b = md5hh$1(b, c, d, a, x[i + 2], 23, -995338651);
+ a = md5ii$1(a, b, c, d, x[i], 6, -198630844);
+ d = md5ii$1(d, a, b, c, x[i + 7], 10, 1126891415);
+ c = md5ii$1(c, d, a, b, x[i + 14], 15, -1416354905);
+ b = md5ii$1(b, c, d, a, x[i + 5], 21, -57434055);
+ a = md5ii$1(a, b, c, d, x[i + 12], 6, 1700485571);
+ d = md5ii$1(d, a, b, c, x[i + 3], 10, -1894986606);
+ c = md5ii$1(c, d, a, b, x[i + 10], 15, -1051523);
+ b = md5ii$1(b, c, d, a, x[i + 1], 21, -2054922799);
+ a = md5ii$1(a, b, c, d, x[i + 8], 6, 1873313359);
+ d = md5ii$1(d, a, b, c, x[i + 15], 10, -30611744);
+ c = md5ii$1(c, d, a, b, x[i + 6], 15, -1560198380);
+ b = md5ii$1(b, c, d, a, x[i + 13], 21, 1309151649);
+ a = md5ii$1(a, b, c, d, x[i + 4], 6, -145523070);
+ d = md5ii$1(d, a, b, c, x[i + 11], 10, -1120210379);
+ c = md5ii$1(c, d, a, b, x[i + 2], 15, 718787259);
+ b = md5ii$1(b, c, d, a, x[i + 9], 21, -343485551);
+ a = safeAdd$1(a, olda);
+ b = safeAdd$1(b, oldb);
+ c = safeAdd$1(c, oldc);
+ d = safeAdd$1(d, oldd);
+ }
+
+ return [a, b, c, d];
+}
+/*
+ * Convert an array bytes to an array of little-endian words
+ * Characters >255 have their high-byte silently ignored.
+ */
+
+
+function bytesToWords$1(input) {
+ if (input.length === 0) {
+ return [];
+ }
+
+ var length8 = input.length * 8;
+ var output = new Uint32Array(getOutputLength$1(length8));
+
+ for (var i = 0; i < length8; i += 8) {
+ output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
+ }
+
+ return output;
+}
+/*
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
+ * to work around bugs in some JS interpreters.
+ */
+
+
+function safeAdd$1(x, y) {
+ var lsw = (x & 0xffff) + (y & 0xffff);
+ var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+ return msw << 16 | lsw & 0xffff;
+}
+/*
+ * Bitwise rotate a 32-bit number to the left.
+ */
+
+
+function bitRotateLeft$1(num, cnt) {
+ return num << cnt | num >>> 32 - cnt;
+}
+/*
+ * These functions implement the four basic operations the algorithm uses.
+ */
+
+
+function md5cmn$1(q, a, b, x, s, t) {
+ return safeAdd$1(bitRotateLeft$1(safeAdd$1(safeAdd$1(a, q), safeAdd$1(x, t)), s), b);
+}
+
+function md5ff$1(a, b, c, d, x, s, t) {
+ return md5cmn$1(b & c | ~b & d, a, b, x, s, t);
+}
+
+function md5gg$1(a, b, c, d, x, s, t) {
+ return md5cmn$1(b & d | c & ~d, a, b, x, s, t);
+}
+
+function md5hh$1(a, b, c, d, x, s, t) {
+ return md5cmn$1(b ^ c ^ d, a, b, x, s, t);
+}
+
+function md5ii$1(a, b, c, d, x, s, t) {
+ return md5cmn$1(c ^ (b | ~d), a, b, x, s, t);
+}
+
+var v3$2 = v35$1('v3', 0x30, md5$1);
+var v3$3 = v3$2;
+
+function v4$2(options, buf, offset) {
+ options = options || {};
+ var rnds = options.random || (options.rng || rng$2)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
+ rnds[6] = rnds[6] & 0x0f | 0x40;
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (var i = 0; i < 16; ++i) {
+ buf[offset + i] = rnds[i];
+ }
+
+ return buf;
+ }
+
+ return stringify$4(rnds);
+}
+
+// Adapted from Chris Veness' SHA1 code at
+// http://www.movable-type.co.uk/scripts/sha1.html
+function f$2(s, x, y, z) {
+ switch (s) {
+ case 0:
+ return x & y ^ ~x & z;
+
+ case 1:
+ return x ^ y ^ z;
+
+ case 2:
+ return x & y ^ x & z ^ y & z;
+
+ case 3:
+ return x ^ y ^ z;
+ }
+}
+
+function ROTL$1(x, n) {
+ return x << n | x >>> 32 - n;
+}
+
+function sha1$1(bytes) {
+ var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
+ var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
+
+ if (typeof bytes === 'string') {
+ var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
+
+ bytes = [];
+
+ for (var i = 0; i < msg.length; ++i) {
+ bytes.push(msg.charCodeAt(i));
+ }
+ } else if (!Array.isArray(bytes)) {
+ // Convert Array-like to Array
+ bytes = Array.prototype.slice.call(bytes);
+ }
+
+ bytes.push(0x80);
+ var l = bytes.length / 4 + 2;
+ var N = Math.ceil(l / 16);
+ var M = new Array(N);
+
+ for (var _i = 0; _i < N; ++_i) {
+ var arr = new Uint32Array(16);
+
+ for (var j = 0; j < 16; ++j) {
+ arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
+ }
+
+ M[_i] = arr;
+ }
+
+ M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
+ M[N - 1][14] = Math.floor(M[N - 1][14]);
+ M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
+
+ for (var _i2 = 0; _i2 < N; ++_i2) {
+ var W = new Uint32Array(80);
+
+ for (var t = 0; t < 16; ++t) {
+ W[t] = M[_i2][t];
+ }
+
+ for (var _t = 16; _t < 80; ++_t) {
+ W[_t] = ROTL$1(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
+ }
+
+ var a = H[0];
+ var b = H[1];
+ var c = H[2];
+ var d = H[3];
+ var e = H[4];
+
+ for (var _t2 = 0; _t2 < 80; ++_t2) {
+ var s = Math.floor(_t2 / 20);
+ var T = ROTL$1(a, 5) + f$2(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
+ e = d;
+ d = c;
+ c = ROTL$1(b, 30) >>> 0;
+ b = a;
+ a = T;
+ }
+
+ H[0] = H[0] + a >>> 0;
+ H[1] = H[1] + b >>> 0;
+ H[2] = H[2] + c >>> 0;
+ H[3] = H[3] + d >>> 0;
+ H[4] = H[4] + e >>> 0;
+ }
+
+ return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
+}
+
+var v5$2 = v35$1('v5', 0x50, sha1$1);
+var v5$3 = v5$2;
+
+var nil$1 = '00000000-0000-0000-0000-000000000000';
+
+function version$8(uuid) {
+ if (!validate$2(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ return parseInt(uuid.substr(14, 1), 16);
+}
+
+var esmBrowser$1 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ NIL: nil$1,
+ parse: parse$5,
+ stringify: stringify$4,
+ v1: v1$1,
+ v3: v3$3,
+ v4: v4$2,
+ v5: v5$3,
+ validate: validate$2,
+ version: version$8
+});
+
+var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(esmBrowser$1);
+
+var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(loggingMiddleware, "__esModule", { value: true });
+loggingMiddleware.getLoggingMiddleware = void 0;
+const pino_http_1 = __importDefault$4(loggerExports$1);
+const uuid_1$1 = require$$1$1;
+function getLoggingMiddleware(logger, options) {
+ return (0, pino_http_1.default)({
+ ...options,
+ logger: logger.child({ name: "http" }),
+ customSuccessMessage(res) {
+ const responseTime = Date.now() - res[pino_http_1.default.startTime];
+ // @ts-ignore
+ return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`;
+ },
+ customErrorMessage(err, res) {
+ const responseTime = Date.now() - res[pino_http_1.default.startTime];
+ // @ts-ignore
+ return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`;
+ },
+ genReqId: (req) => req.headers["x-request-id"] ||
+ req.headers["x-github-delivery"] ||
+ (0, uuid_1$1.v4)(),
+ });
+}
+loggingMiddleware.getLoggingMiddleware = getLoggingMiddleware;
+
+var webhookProxy = {};
+
+var validatorExports = {};
+var validator$1 = {
+ get exports(){ return validatorExports; },
+ set exports(v){ validatorExports = v; },
+};
+
+var toDateExports = {};
+var toDate = {
+ get exports(){ return toDateExports; },
+ set exports(v){ toDateExports = v; },
+};
+
+var assertStringExports = {};
+var assertString = {
+ get exports(){ return assertStringExports; },
+ set exports(v){ assertStringExports = v; },
+};
+
+var hasRequiredAssertString;
+
+function requireAssertString () {
+ if (hasRequiredAssertString) return assertStringExports;
+ hasRequiredAssertString = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = assertString;
+
+ 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 assertString(input) {
+ var isString = typeof input === 'string' || input instanceof String;
+
+ if (!isString) {
+ var invalidType = _typeof(input);
+
+ if (input === null) invalidType = 'null';else if (invalidType === 'object') invalidType = input.constructor.name;
+ throw new TypeError("Expected a string but received a ".concat(invalidType));
+ }
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (assertString, assertStringExports));
+ return assertStringExports;
+}
+
+var hasRequiredToDate;
+
+function requireToDate () {
+ if (hasRequiredToDate) return toDateExports;
+ hasRequiredToDate = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = toDate;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function toDate(date) {
+ (0, _assertString.default)(date);
+ date = Date.parse(date);
+ return !isNaN(date) ? new Date(date) : null;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (toDate, toDateExports));
+ return toDateExports;
+}
+
+var toFloatExports = {};
+var toFloat = {
+ get exports(){ return toFloatExports; },
+ set exports(v){ toFloatExports = v; },
+};
+
+var isFloat$1 = {};
+
+var alpha = {};
+
+var hasRequiredAlpha;
+
+function requireAlpha () {
+ if (hasRequiredAlpha) return alpha;
+ hasRequiredAlpha = 1;
+
+ Object.defineProperty(alpha, "__esModule", {
+ value: true
+ });
+ alpha.commaDecimal = alpha.dotDecimal = alpha.bengaliLocales = alpha.farsiLocales = alpha.arabicLocales = alpha.englishLocales = alpha.decimal = alpha.alphanumeric = alpha.alpha = void 0;
+ var alpha$1 = {
+ 'en-US': /^[A-Z]+$/i,
+ 'az-AZ': /^[A-VXYZÇƏĞİıÖŞÜ]+$/i,
+ 'bg-BG': /^[А-Я]+$/i,
+ 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
+ 'da-DK': /^[A-ZÆØÅ]+$/i,
+ 'de-DE': /^[A-ZÄÖÜß]+$/i,
+ 'el-GR': /^[Α-ώ]+$/i,
+ 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i,
+ 'fa-IR': /^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$/i,
+ 'fi-FI': /^[A-ZÅÄÖ]+$/i,
+ 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
+ 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i,
+ 'ja-JP': /^[ぁ-んァ-ヶヲ-゚一-龠ー・。、]+$/i,
+ 'nb-NO': /^[A-ZÆØÅ]+$/i,
+ 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i,
+ 'nn-NO': /^[A-ZÆØÅ]+$/i,
+ 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
+ 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
+ 'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,
+ 'ru-RU': /^[А-ЯЁ]+$/i,
+ 'sl-SI': /^[A-ZČĆĐŠŽ]+$/i,
+ 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
+ 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i,
+ 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i,
+ 'sv-SE': /^[A-ZÅÄÖ]+$/i,
+ 'th-TH': /^[ก-๐\s]+$/i,
+ 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i,
+ 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i,
+ 'vi-VN': /^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i,
+ 'ko-KR': /^[ㄱ-ㅎㅏ-ㅣ가-힣]*$/,
+ 'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,
+ ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,
+ he: /^[א-ת]+$/,
+ fa: /^['آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی']+$/i,
+ bn: /^['ঀঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣৰৱ৲৳৴৵৶৷৸৹৺৻']+$/,
+ 'hi-IN': /^[\u0900-\u0961]+[\u0972-\u097F]*$/i,
+ 'si-LK': /^[\u0D80-\u0DFF]+$/
+ };
+ alpha.alpha = alpha$1;
+ var alphanumeric = {
+ 'en-US': /^[0-9A-Z]+$/i,
+ 'az-AZ': /^[0-9A-VXYZÇƏĞİıÖŞÜ]+$/i,
+ 'bg-BG': /^[0-9А-Я]+$/i,
+ 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
+ 'da-DK': /^[0-9A-ZÆØÅ]+$/i,
+ 'de-DE': /^[0-9A-ZÄÖÜß]+$/i,
+ 'el-GR': /^[0-9Α-ω]+$/i,
+ 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,
+ 'fi-FI': /^[0-9A-ZÅÄÖ]+$/i,
+ 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
+ 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,
+ 'ja-JP': /^[0-90-9ぁ-んァ-ヶヲ-゚一-龠ー・。、]+$/i,
+ 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
+ 'nb-NO': /^[0-9A-ZÆØÅ]+$/i,
+ 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,
+ 'nn-NO': /^[0-9A-ZÆØÅ]+$/i,
+ 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
+ 'pt-PT': /^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,
+ 'ru-RU': /^[0-9А-ЯЁ]+$/i,
+ 'sl-SI': /^[0-9A-ZČĆĐŠŽ]+$/i,
+ 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
+ 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i,
+ 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i,
+ 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i,
+ 'th-TH': /^[ก-๙\s]+$/i,
+ 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i,
+ 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,
+ 'ko-KR': /^[0-9ㄱ-ㅎㅏ-ㅣ가-힣]*$/,
+ 'ku-IQ': /^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,
+ 'vi-VN': /^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i,
+ ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,
+ he: /^[0-9א-ת]+$/,
+ fa: /^['0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰']+$/i,
+ bn: /^['ঀঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣ০১২৩৪৫৬৭৮৯ৰৱ৲৳৴৵৶৷৸৹৺৻']+$/,
+ 'hi-IN': /^[\u0900-\u0963]+[\u0966-\u097F]*$/i,
+ 'si-LK': /^[0-9\u0D80-\u0DFF]+$/
+ };
+ alpha.alphanumeric = alphanumeric;
+ var decimal = {
+ 'en-US': '.',
+ ar: '٫'
+ };
+ alpha.decimal = decimal;
+ var englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];
+ alpha.englishLocales = englishLocales;
+
+ for (var locale, i = 0; i < englishLocales.length; i++) {
+ locale = "en-".concat(englishLocales[i]);
+ alpha$1[locale] = alpha$1['en-US'];
+ alphanumeric[locale] = alphanumeric['en-US'];
+ decimal[locale] = decimal['en-US'];
+ } // Source: http://www.localeplanet.com/java/
+
+
+ var arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];
+ alpha.arabicLocales = arabicLocales;
+
+ for (var _locale, _i = 0; _i < arabicLocales.length; _i++) {
+ _locale = "ar-".concat(arabicLocales[_i]);
+ alpha$1[_locale] = alpha$1.ar;
+ alphanumeric[_locale] = alphanumeric.ar;
+ decimal[_locale] = decimal.ar;
+ }
+
+ var farsiLocales = ['IR', 'AF'];
+ alpha.farsiLocales = farsiLocales;
+
+ for (var _locale2, _i2 = 0; _i2 < farsiLocales.length; _i2++) {
+ _locale2 = "fa-".concat(farsiLocales[_i2]);
+ alphanumeric[_locale2] = alphanumeric.fa;
+ decimal[_locale2] = decimal.ar;
+ }
+
+ var bengaliLocales = ['BD', 'IN'];
+ alpha.bengaliLocales = bengaliLocales;
+
+ for (var _locale3, _i3 = 0; _i3 < bengaliLocales.length; _i3++) {
+ _locale3 = "bn-".concat(bengaliLocales[_i3]);
+ alpha$1[_locale3] = alpha$1.bn;
+ alphanumeric[_locale3] = alphanumeric.bn;
+ decimal[_locale3] = decimal['en-US'];
+ } // Source: https://en.wikipedia.org/wiki/Decimal_mark
+
+
+ var dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY'];
+ alpha.dotDecimal = dotDecimal;
+ var commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-CA', 'fr-FR', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'si-LK', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN'];
+ alpha.commaDecimal = commaDecimal;
+
+ for (var _i4 = 0; _i4 < dotDecimal.length; _i4++) {
+ decimal[dotDecimal[_i4]] = decimal['en-US'];
+ }
+
+ for (var _i5 = 0; _i5 < commaDecimal.length; _i5++) {
+ decimal[commaDecimal[_i5]] = ',';
+ }
+
+ alpha$1['fr-CA'] = alpha$1['fr-FR'];
+ alphanumeric['fr-CA'] = alphanumeric['fr-FR'];
+ alpha$1['pt-BR'] = alpha$1['pt-PT'];
+ alphanumeric['pt-BR'] = alphanumeric['pt-PT'];
+ decimal['pt-BR'] = decimal['pt-PT']; // see #862
+
+ alpha$1['pl-Pl'] = alpha$1['pl-PL'];
+ alphanumeric['pl-Pl'] = alphanumeric['pl-PL'];
+ decimal['pl-Pl'] = decimal['pl-PL']; // see #1455
+
+ alpha$1['fa-AF'] = alpha$1.fa;
+ return alpha;
+}
+
+var hasRequiredIsFloat;
+
+function requireIsFloat () {
+ if (hasRequiredIsFloat) return isFloat$1;
+ hasRequiredIsFloat = 1;
+
+ Object.defineProperty(isFloat$1, "__esModule", {
+ value: true
+ });
+ isFloat$1.default = isFloat;
+ isFloat$1.locales = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _alpha = requireAlpha();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isFloat(str, options) {
+ (0, _assertString.default)(str);
+ options = options || {};
+ var float = new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\".concat(options.locale ? _alpha.decimal[options.locale] : '.', "[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"));
+
+ if (str === '' || str === '.' || str === ',' || str === '-' || str === '+') {
+ return false;
+ }
+
+ var value = parseFloat(str.replace(',', '.'));
+ return float.test(str) && (!options.hasOwnProperty('min') || value >= options.min) && (!options.hasOwnProperty('max') || value <= options.max) && (!options.hasOwnProperty('lt') || value < options.lt) && (!options.hasOwnProperty('gt') || value > options.gt);
+ }
+
+ var locales = Object.keys(_alpha.decimal);
+ isFloat$1.locales = locales;
+ return isFloat$1;
+}
+
+var hasRequiredToFloat;
+
+function requireToFloat () {
+ if (hasRequiredToFloat) return toFloatExports;
+ hasRequiredToFloat = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = toFloat;
+
+ var _isFloat = _interopRequireDefault(requireIsFloat());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function toFloat(str) {
+ if (!(0, _isFloat.default)(str)) return NaN;
+ return parseFloat(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (toFloat, toFloatExports));
+ return toFloatExports;
+}
+
+var toIntExports = {};
+var toInt = {
+ get exports(){ return toIntExports; },
+ set exports(v){ toIntExports = v; },
+};
+
+var hasRequiredToInt;
+
+function requireToInt () {
+ if (hasRequiredToInt) return toIntExports;
+ hasRequiredToInt = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = toInt;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function toInt(str, radix) {
+ (0, _assertString.default)(str);
+ return parseInt(str, radix || 10);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (toInt, toIntExports));
+ return toIntExports;
+}
+
+var toBooleanExports = {};
+var toBoolean = {
+ get exports(){ return toBooleanExports; },
+ set exports(v){ toBooleanExports = v; },
+};
+
+var hasRequiredToBoolean;
+
+function requireToBoolean () {
+ if (hasRequiredToBoolean) return toBooleanExports;
+ hasRequiredToBoolean = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = toBoolean;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function toBoolean(str, strict) {
+ (0, _assertString.default)(str);
+
+ if (strict) {
+ return str === '1' || /^true$/i.test(str);
+ }
+
+ return str !== '0' && !/^false$/i.test(str) && str !== '';
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (toBoolean, toBooleanExports));
+ return toBooleanExports;
+}
+
+var equalsExports = {};
+var equals = {
+ get exports(){ return equalsExports; },
+ set exports(v){ equalsExports = v; },
+};
+
+var hasRequiredEquals;
+
+function requireEquals () {
+ if (hasRequiredEquals) return equalsExports;
+ hasRequiredEquals = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = equals;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function equals(str, comparison) {
+ (0, _assertString.default)(str);
+ return str === comparison;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (equals, equalsExports));
+ return equalsExports;
+}
+
+var containsExports = {};
+var contains = {
+ get exports(){ return containsExports; },
+ set exports(v){ containsExports = v; },
+};
+
+var toStringExports = {};
+var toString$3 = {
+ get exports(){ return toStringExports; },
+ set exports(v){ toStringExports = v; },
+};
+
+var hasRequiredToString;
+
+function requireToString () {
+ if (hasRequiredToString) return toStringExports;
+ hasRequiredToString = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = toString;
+
+ 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 toString(input) {
+ if (_typeof(input) === 'object' && input !== null) {
+ if (typeof input.toString === 'function') {
+ input = input.toString();
+ } else {
+ input = '[object Object]';
+ }
+ } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {
+ input = '';
+ }
+
+ return String(input);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (toString$3, toStringExports));
+ return toStringExports;
+}
+
+var mergeExports = {};
+var merge$1 = {
+ get exports(){ return mergeExports; },
+ set exports(v){ mergeExports = v; },
+};
+
+var hasRequiredMerge;
+
+function requireMerge () {
+ if (hasRequiredMerge) return mergeExports;
+ hasRequiredMerge = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = merge;
+
+ function merge() {
+ var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var defaults = arguments.length > 1 ? arguments[1] : undefined;
+
+ for (var key in defaults) {
+ if (typeof obj[key] === 'undefined') {
+ obj[key] = defaults[key];
+ }
+ }
+
+ return obj;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (merge$1, mergeExports));
+ return mergeExports;
+}
+
+var hasRequiredContains;
+
+function requireContains () {
+ if (hasRequiredContains) return containsExports;
+ hasRequiredContains = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = contains;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _toString = _interopRequireDefault(requireToString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var defaulContainsOptions = {
+ ignoreCase: false,
+ minOccurrences: 1
+ };
+
+ function contains(str, elem, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, defaulContainsOptions);
+
+ if (options.ignoreCase) {
+ return str.toLowerCase().split((0, _toString.default)(elem).toLowerCase()).length > options.minOccurrences;
+ }
+
+ return str.split((0, _toString.default)(elem)).length > options.minOccurrences;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (contains, containsExports));
+ return containsExports;
+}
+
+var matchesExports = {};
+var matches = {
+ get exports(){ return matchesExports; },
+ set exports(v){ matchesExports = v; },
+};
+
+var hasRequiredMatches;
+
+function requireMatches () {
+ if (hasRequiredMatches) return matchesExports;
+ hasRequiredMatches = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = matches;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function matches(str, pattern, modifiers) {
+ (0, _assertString.default)(str);
+
+ if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {
+ pattern = new RegExp(pattern, modifiers);
+ }
+
+ return !!str.match(pattern);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (matches, matchesExports));
+ return matchesExports;
+}
+
+var isEmailExports = {};
+var isEmail = {
+ get exports(){ return isEmailExports; },
+ set exports(v){ isEmailExports = v; },
+};
+
+var isByteLengthExports = {};
+var isByteLength = {
+ get exports(){ return isByteLengthExports; },
+ set exports(v){ isByteLengthExports = v; },
+};
+
+var hasRequiredIsByteLength;
+
+function requireIsByteLength () {
+ if (hasRequiredIsByteLength) return isByteLengthExports;
+ hasRequiredIsByteLength = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isByteLength;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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); }
+
+ /* eslint-disable prefer-rest-params */
+ function isByteLength(str, options) {
+ (0, _assertString.default)(str);
+ var min;
+ var max;
+
+ if (_typeof(options) === 'object') {
+ min = options.min || 0;
+ max = options.max;
+ } else {
+ // backwards compatibility: isByteLength(str, min [, max])
+ min = arguments[1];
+ max = arguments[2];
+ }
+
+ var len = encodeURI(str).split(/%..|./).length - 1;
+ return len >= min && (typeof max === 'undefined' || len <= max);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isByteLength, isByteLengthExports));
+ return isByteLengthExports;
+}
+
+var isFQDNExports = {};
+var isFQDN = {
+ get exports(){ return isFQDNExports; },
+ set exports(v){ isFQDNExports = v; },
+};
+
+var hasRequiredIsFQDN;
+
+function requireIsFQDN () {
+ if (hasRequiredIsFQDN) return isFQDNExports;
+ hasRequiredIsFQDN = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isFQDN;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var default_fqdn_options = {
+ require_tld: true,
+ allow_underscores: false,
+ allow_trailing_dot: false,
+ allow_numeric_tld: false,
+ allow_wildcard: false,
+ ignore_max_length: false
+ };
+
+ function isFQDN(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, default_fqdn_options);
+ /* Remove the optional trailing dot before checking validity */
+
+ if (options.allow_trailing_dot && str[str.length - 1] === '.') {
+ str = str.substring(0, str.length - 1);
+ }
+ /* Remove the optional wildcard before checking validity */
+
+
+ if (options.allow_wildcard === true && str.indexOf('*.') === 0) {
+ str = str.substring(2);
+ }
+
+ var parts = str.split('.');
+ var tld = parts[parts.length - 1];
+
+ if (options.require_tld) {
+ // disallow fqdns without tld
+ if (parts.length < 2) {
+ return false;
+ }
+
+ if (!options.allow_numeric_tld && !/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
+ return false;
+ } // disallow spaces
+
+
+ if (/\s/.test(tld)) {
+ return false;
+ }
+ } // reject numeric TLDs
+
+
+ if (!options.allow_numeric_tld && /^\d+$/.test(tld)) {
+ return false;
+ }
+
+ return parts.every(function (part) {
+ if (part.length > 63 && !options.ignore_max_length) {
+ return false;
+ }
+
+ if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) {
+ return false;
+ } // disallow full-width chars
+
+
+ if (/[\uff01-\uff5e]/.test(part)) {
+ return false;
+ } // disallow parts starting or ending with hyphen
+
+
+ if (/^-|-$/.test(part)) {
+ return false;
+ }
+
+ if (!options.allow_underscores && /_/.test(part)) {
+ return false;
+ }
+
+ return true;
+ });
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isFQDN, isFQDNExports));
+ return isFQDNExports;
+}
+
+var isIPExports = {};
+var isIP = {
+ get exports(){ return isIPExports; },
+ set exports(v){ isIPExports = v; },
+};
+
+var hasRequiredIsIP;
+
+function requireIsIP () {
+ if (hasRequiredIsIP) return isIPExports;
+ hasRequiredIsIP = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isIP;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /**
+ 11.3. Examples
+
+ The following addresses
+
+ fe80::1234 (on the 1st link of the node)
+ ff02::5678 (on the 5th link of the node)
+ ff08::9abc (on the 10th organization of the node)
+
+ would be represented as follows:
+
+ fe80::1234%1
+ ff02::5678%5
+ ff08::9abc%10
+
+ (Here we assume a natural translation from a zone index to the
+ part, where the Nth zone of any scope is translated into
+ "N".)
+
+ If we use interface names as , those addresses could also be
+ represented as follows:
+
+ fe80::1234%ne0
+ ff02::5678%pvc1.3
+ ff08::9abc%interface10
+
+ where the interface "ne0" belongs to the 1st link, "pvc1.3" belongs
+ to the 5th link, and "interface10" belongs to the 10th organization.
+ * * */
+ var IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
+ var IPv4AddressFormat = "(".concat(IPv4SegmentFormat, "[.]){3}").concat(IPv4SegmentFormat);
+ var IPv4AddressRegExp = new RegExp("^".concat(IPv4AddressFormat, "$"));
+ var IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})';
+ var IPv6AddressRegExp = new RegExp('^(' + "(?:".concat(IPv6SegmentFormat, ":){7}(?:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){6}(?:").concat(IPv4AddressFormat, "|:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){5}(?::").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,2}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){4}(?:(:").concat(IPv6SegmentFormat, "){0,1}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,3}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){3}(?:(:").concat(IPv6SegmentFormat, "){0,2}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,4}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){2}(?:(:").concat(IPv6SegmentFormat, "){0,3}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,5}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){1}(?:(:").concat(IPv6SegmentFormat, "){0,4}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,6}|:)|") + "(?::((?::".concat(IPv6SegmentFormat, "){0,5}:").concat(IPv4AddressFormat, "|(?::").concat(IPv6SegmentFormat, "){1,7}|:))") + ')(%[0-9a-zA-Z-.:]{1,})?$');
+
+ function isIP(str) {
+ var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
+ (0, _assertString.default)(str);
+ version = String(version);
+
+ if (!version) {
+ return isIP(str, 4) || isIP(str, 6);
+ }
+
+ if (version === '4') {
+ return IPv4AddressRegExp.test(str);
+ }
+
+ if (version === '6') {
+ return IPv6AddressRegExp.test(str);
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isIP, isIPExports));
+ return isIPExports;
+}
+
+var hasRequiredIsEmail;
+
+function requireIsEmail () {
+ if (hasRequiredIsEmail) return isEmailExports;
+ hasRequiredIsEmail = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isEmail;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ var _isByteLength = _interopRequireDefault(requireIsByteLength());
+
+ var _isFQDN = _interopRequireDefault(requireIsFQDN());
+
+ var _isIP = _interopRequireDefault(requireIsIP());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var default_email_options = {
+ allow_display_name: false,
+ require_display_name: false,
+ allow_utf8_local_part: true,
+ require_tld: true,
+ blacklisted_chars: '',
+ ignore_max_length: false,
+ host_blacklist: [],
+ host_whitelist: []
+ };
+ /* eslint-disable max-len */
+
+ /* eslint-disable no-control-regex */
+
+ var splitNameAddress = /^([^\x00-\x1F\x7F-\x9F\cX]+)]/.test(display_name_without_quotes);
+
+ if (contains_illegal) {
+ // if contains illegal characters,
+ // must to be enclosed in double-quotes, otherwise it's not a valid display name
+ if (display_name_without_quotes === display_name) {
+ return false;
+ } // the quotes in display name must start with character symbol \
+
+
+ var all_start_with_back_slash = display_name_without_quotes.split('"').length === display_name_without_quotes.split('\\"').length;
+
+ if (!all_start_with_back_slash) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ function isEmail(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, default_email_options);
+
+ if (options.require_display_name || options.allow_display_name) {
+ var display_email = str.match(splitNameAddress);
+
+ if (display_email) {
+ var display_name = display_email[1]; // Remove display name and angle brackets to get email address
+ // Can be done in the regex but will introduce a ReDOS (See #1597 for more info)
+
+ str = str.replace(display_name, '').replace(/(^<|>$)/g, ''); // sometimes need to trim the last space to get the display name
+ // because there may be a space between display name and email address
+ // eg. myname
+ // the display name is `myname` instead of `myname `, so need to trim the last space
+
+ if (display_name.endsWith(' ')) {
+ display_name = display_name.slice(0, -1);
+ }
+
+ if (!validateDisplayName(display_name)) {
+ return false;
+ }
+ } else if (options.require_display_name) {
+ return false;
+ }
+ }
+
+ if (!options.ignore_max_length && str.length > defaultMaxEmailLength) {
+ return false;
+ }
+
+ var parts = str.split('@');
+ var domain = parts.pop();
+ var lower_domain = domain.toLowerCase();
+
+ if (options.host_blacklist.includes(lower_domain)) {
+ return false;
+ }
+
+ if (options.host_whitelist.length > 0 && !options.host_whitelist.includes(lower_domain)) {
+ return false;
+ }
+
+ var user = parts.join('@');
+
+ if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) {
+ /*
+ Previously we removed dots for gmail addresses before validating.
+ This was removed because it allows `multiple..dots@gmail.com`
+ to be reported as valid, but it is not.
+ Gmail only normalizes single dots, removing them from here is pointless,
+ should be done in normalizeEmail
+ */
+ user = user.toLowerCase(); // Removing sub-address from username before gmail validation
+
+ var username = user.split('+')[0]; // Dots are not included in gmail length restriction
+
+ if (!(0, _isByteLength.default)(username.replace(/\./g, ''), {
+ min: 6,
+ max: 30
+ })) {
+ return false;
+ }
+
+ var _user_parts = username.split('.');
+
+ for (var i = 0; i < _user_parts.length; i++) {
+ if (!gmailUserPart.test(_user_parts[i])) {
+ return false;
+ }
+ }
+ }
+
+ if (options.ignore_max_length === false && (!(0, _isByteLength.default)(user, {
+ max: 64
+ }) || !(0, _isByteLength.default)(domain, {
+ max: 254
+ }))) {
+ return false;
+ }
+
+ if (!(0, _isFQDN.default)(domain, {
+ require_tld: options.require_tld,
+ ignore_max_length: options.ignore_max_length
+ })) {
+ if (!options.allow_ip_domain) {
+ return false;
+ }
+
+ if (!(0, _isIP.default)(domain)) {
+ if (!domain.startsWith('[') || !domain.endsWith(']')) {
+ return false;
+ }
+
+ var noBracketdomain = domain.slice(1, -1);
+
+ if (noBracketdomain.length === 0 || !(0, _isIP.default)(noBracketdomain)) {
+ return false;
+ }
+ }
+ }
+
+ if (user[0] === '"') {
+ user = user.slice(1, user.length - 1);
+ return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
+ }
+
+ var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
+ var user_parts = user.split('.');
+
+ for (var _i = 0; _i < user_parts.length; _i++) {
+ if (!pattern.test(user_parts[_i])) {
+ return false;
+ }
+ }
+
+ if (options.blacklisted_chars) {
+ if (user.search(new RegExp("[".concat(options.blacklisted_chars, "]+"), 'g')) !== -1) return false;
+ }
+
+ return true;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isEmail, isEmailExports));
+ return isEmailExports;
+}
+
+var isURLExports = {};
+var isURL = {
+ get exports(){ return isURLExports; },
+ set exports(v){ isURLExports = v; },
+};
+
+var hasRequiredIsURL;
+
+function requireIsURL () {
+ if (hasRequiredIsURL) return isURLExports;
+ hasRequiredIsURL = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isURL;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isFQDN = _interopRequireDefault(requireIsFQDN());
+
+ var _isIP = _interopRequireDefault(requireIsIP());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
+
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+ /*
+ options for isURL method
+
+ require_protocol - if set as true isURL will return false if protocol is not present in the URL
+ require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option
+ protocols - valid protocols can be modified with this option
+ require_host - if set as false isURL will not check if host is present in the URL
+ require_port - if set as true isURL will check if port is present in the URL
+ allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed
+ validate_length - if set as false isURL will skip string length validation (IE maximum is 2083)
+
+ */
+ var default_url_options = {
+ protocols: ['http', 'https', 'ftp'],
+ require_tld: true,
+ require_protocol: false,
+ require_host: true,
+ require_port: false,
+ require_valid_protocol: true,
+ allow_underscores: false,
+ allow_trailing_dot: false,
+ allow_protocol_relative_urls: false,
+ allow_fragments: true,
+ allow_query_components: true,
+ validate_length: true
+ };
+ var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/;
+
+ function isRegExp(obj) {
+ return Object.prototype.toString.call(obj) === '[object RegExp]';
+ }
+
+ function checkHost(host, matches) {
+ for (var i = 0; i < matches.length; i++) {
+ var match = matches[i];
+
+ if (host === match || isRegExp(match) && match.test(host)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ function isURL(url, options) {
+ (0, _assertString.default)(url);
+
+ if (!url || /[\s<>]/.test(url)) {
+ return false;
+ }
+
+ if (url.indexOf('mailto:') === 0) {
+ return false;
+ }
+
+ options = (0, _merge.default)(options, default_url_options);
+
+ if (options.validate_length && url.length >= 2083) {
+ return false;
+ }
+
+ if (!options.allow_fragments && url.includes('#')) {
+ return false;
+ }
+
+ if (!options.allow_query_components && (url.includes('?') || url.includes('&'))) {
+ return false;
+ }
+
+ var protocol, auth, host, hostname, port, port_str, split, ipv6;
+ split = url.split('#');
+ url = split.shift();
+ split = url.split('?');
+ url = split.shift();
+ split = url.split('://');
+
+ if (split.length > 1) {
+ protocol = split.shift().toLowerCase();
+
+ if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
+ return false;
+ }
+ } else if (options.require_protocol) {
+ return false;
+ } else if (url.slice(0, 2) === '//') {
+ if (!options.allow_protocol_relative_urls) {
+ return false;
+ }
+
+ split[0] = url.slice(2);
+ }
+
+ url = split.join('://');
+
+ if (url === '') {
+ return false;
+ }
+
+ split = url.split('/');
+ url = split.shift();
+
+ if (url === '' && !options.require_host) {
+ return true;
+ }
+
+ split = url.split('@');
+
+ if (split.length > 1) {
+ if (options.disallow_auth) {
+ return false;
+ }
+
+ if (split[0] === '') {
+ return false;
+ }
+
+ auth = split.shift();
+
+ if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
+ return false;
+ }
+
+ var _auth$split = auth.split(':'),
+ _auth$split2 = _slicedToArray(_auth$split, 2),
+ user = _auth$split2[0],
+ password = _auth$split2[1];
+
+ if (user === '' && password === '') {
+ return false;
+ }
+ }
+
+ hostname = split.join('@');
+ port_str = null;
+ ipv6 = null;
+ var ipv6_match = hostname.match(wrapped_ipv6);
+
+ if (ipv6_match) {
+ host = '';
+ ipv6 = ipv6_match[1];
+ port_str = ipv6_match[2] || null;
+ } else {
+ split = hostname.split(':');
+ host = split.shift();
+
+ if (split.length) {
+ port_str = split.join(':');
+ }
+ }
+
+ if (port_str !== null && port_str.length > 0) {
+ port = parseInt(port_str, 10);
+
+ if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
+ return false;
+ }
+ } else if (options.require_port) {
+ return false;
+ }
+
+ if (options.host_whitelist) {
+ return checkHost(host, options.host_whitelist);
+ }
+
+ if (host === '' && !options.require_host) {
+ return true;
+ }
+
+ if (!(0, _isIP.default)(host) && !(0, _isFQDN.default)(host, options) && (!ipv6 || !(0, _isIP.default)(ipv6, 6))) {
+ return false;
+ }
+
+ host = host || ipv6;
+
+ if (options.host_blacklist && checkHost(host, options.host_blacklist)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isURL, isURLExports));
+ return isURLExports;
+}
+
+var isMACAddressExports = {};
+var isMACAddress = {
+ get exports(){ return isMACAddressExports; },
+ set exports(v){ isMACAddressExports = v; },
+};
+
+var hasRequiredIsMACAddress;
+
+function requireIsMACAddress () {
+ if (hasRequiredIsMACAddress) return isMACAddressExports;
+ hasRequiredIsMACAddress = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isMACAddress;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var macAddress48 = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){4}([0-9a-fA-F]{2})$/;
+ var macAddress48NoSeparators = /^([0-9a-fA-F]){12}$/;
+ var macAddress48WithDots = /^([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})$/;
+ var macAddress64 = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){6}([0-9a-fA-F]{2})$/;
+ var macAddress64NoSeparators = /^([0-9a-fA-F]){16}$/;
+ var macAddress64WithDots = /^([0-9a-fA-F]{4}\.){3}([0-9a-fA-F]{4})$/;
+
+ function isMACAddress(str, options) {
+ (0, _assertString.default)(str);
+
+ if (options !== null && options !== void 0 && options.eui) {
+ options.eui = String(options.eui);
+ }
+ /**
+ * @deprecated `no_colons` TODO: remove it in the next major
+ */
+
+
+ if (options !== null && options !== void 0 && options.no_colons || options !== null && options !== void 0 && options.no_separators) {
+ if (options.eui === '48') {
+ return macAddress48NoSeparators.test(str);
+ }
+
+ if (options.eui === '64') {
+ return macAddress64NoSeparators.test(str);
+ }
+
+ return macAddress48NoSeparators.test(str) || macAddress64NoSeparators.test(str);
+ }
+
+ if ((options === null || options === void 0 ? void 0 : options.eui) === '48') {
+ return macAddress48.test(str) || macAddress48WithDots.test(str);
+ }
+
+ if ((options === null || options === void 0 ? void 0 : options.eui) === '64') {
+ return macAddress64.test(str) || macAddress64WithDots.test(str);
+ }
+
+ return isMACAddress(str, {
+ eui: '48'
+ }) || isMACAddress(str, {
+ eui: '64'
+ });
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isMACAddress, isMACAddressExports));
+ return isMACAddressExports;
+}
+
+var isIPRangeExports = {};
+var isIPRange = {
+ get exports(){ return isIPRangeExports; },
+ set exports(v){ isIPRangeExports = v; },
+};
+
+var hasRequiredIsIPRange;
+
+function requireIsIPRange () {
+ if (hasRequiredIsIPRange) return isIPRangeExports;
+ hasRequiredIsIPRange = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isIPRange;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isIP = _interopRequireDefault(requireIsIP());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var subnetMaybe = /^\d{1,3}$/;
+ var v4Subnet = 32;
+ var v6Subnet = 128;
+
+ function isIPRange(str) {
+ var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
+ (0, _assertString.default)(str);
+ var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet
+
+ if (parts.length !== 2) {
+ return false;
+ }
+
+ if (!subnetMaybe.test(parts[1])) {
+ return false;
+ } // Disallow preceding 0 i.e. 01, 02, ...
+
+
+ if (parts[1].length > 1 && parts[1].startsWith('0')) {
+ return false;
+ }
+
+ var isValidIP = (0, _isIP.default)(parts[0], version);
+
+ if (!isValidIP) {
+ return false;
+ } // Define valid subnet according to IP's version
+
+
+ var expectedSubnet = null;
+
+ switch (String(version)) {
+ case '4':
+ expectedSubnet = v4Subnet;
+ break;
+
+ case '6':
+ expectedSubnet = v6Subnet;
+ break;
+
+ default:
+ expectedSubnet = (0, _isIP.default)(parts[0], '6') ? v6Subnet : v4Subnet;
+ }
+
+ return parts[1] <= expectedSubnet && parts[1] >= 0;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isIPRange, isIPRangeExports));
+ return isIPRangeExports;
+}
+
+var isDateExports = {};
+var isDate = {
+ get exports(){ return isDateExports; },
+ set exports(v){ isDateExports = v; },
+};
+
+var hasRequiredIsDate;
+
+function requireIsDate () {
+ if (hasRequiredIsDate) return isDateExports;
+ hasRequiredIsDate = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isDate;
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
+
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
+
+ function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
+
+ 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 _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; }
+
+ var default_date_options = {
+ format: 'YYYY/MM/DD',
+ delimiters: ['/', '-'],
+ strictMode: false
+ };
+
+ function isValidFormat(format) {
+ return /(^(y{4}|y{2})[.\/-](m{1,2})[.\/-](d{1,2})$)|(^(m{1,2})[.\/-](d{1,2})[.\/-]((y{4}|y{2})$))|(^(d{1,2})[.\/-](m{1,2})[.\/-]((y{4}|y{2})$))/gi.test(format);
+ }
+
+ function zip(date, format) {
+ var zippedArr = [],
+ len = Math.min(date.length, format.length);
+
+ for (var i = 0; i < len; i++) {
+ zippedArr.push([date[i], format[i]]);
+ }
+
+ return zippedArr;
+ }
+
+ function isDate(input, options) {
+ if (typeof options === 'string') {
+ // Allow backward compatbility for old format isDate(input [, format])
+ options = (0, _merge.default)({
+ format: options
+ }, default_date_options);
+ } else {
+ options = (0, _merge.default)(options, default_date_options);
+ }
+
+ if (typeof input === 'string' && isValidFormat(options.format)) {
+ var formatDelimiter = options.delimiters.find(function (delimiter) {
+ return options.format.indexOf(delimiter) !== -1;
+ });
+ var dateDelimiter = options.strictMode ? formatDelimiter : options.delimiters.find(function (delimiter) {
+ return input.indexOf(delimiter) !== -1;
+ });
+ var dateAndFormat = zip(input.split(dateDelimiter), options.format.toLowerCase().split(formatDelimiter));
+ var dateObj = {};
+
+ var _iterator = _createForOfIteratorHelper(dateAndFormat),
+ _step;
+
+ try {
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ var _step$value = _slicedToArray(_step.value, 2),
+ dateWord = _step$value[0],
+ formatWord = _step$value[1];
+
+ if (dateWord.length !== formatWord.length) {
+ return false;
+ }
+
+ dateObj[formatWord.charAt(0)] = dateWord;
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+
+ return new Date("".concat(dateObj.m, "/").concat(dateObj.d, "/").concat(dateObj.y)).getDate() === +dateObj.d;
+ }
+
+ if (!options.strictMode) {
+ return Object.prototype.toString.call(input) === '[object Date]' && isFinite(input);
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isDate, isDateExports));
+ return isDateExports;
+}
+
+var isTimeExports = {};
+var isTime = {
+ get exports(){ return isTimeExports; },
+ set exports(v){ isTimeExports = v; },
+};
+
+var hasRequiredIsTime;
+
+function requireIsTime () {
+ if (hasRequiredIsTime) return isTimeExports;
+ hasRequiredIsTime = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isTime;
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var default_time_options = {
+ hourFormat: 'hour24',
+ mode: 'default'
+ };
+ var formats = {
+ hour24: {
+ default: /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/,
+ withSeconds: /^([01]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/
+ },
+ hour12: {
+ default: /^(0?[1-9]|1[0-2]):([0-5][0-9]) (A|P)M$/,
+ withSeconds: /^(0?[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9]) (A|P)M$/
+ }
+ };
+
+ function isTime(input, options) {
+ options = (0, _merge.default)(options, default_time_options);
+ if (typeof input !== 'string') return false;
+ return formats[options.hourFormat][options.mode].test(input);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isTime, isTimeExports));
+ return isTimeExports;
+}
+
+var isBooleanExports = {};
+var isBoolean$1 = {
+ get exports(){ return isBooleanExports; },
+ set exports(v){ isBooleanExports = v; },
+};
+
+var hasRequiredIsBoolean;
+
+function requireIsBoolean () {
+ if (hasRequiredIsBoolean) return isBooleanExports;
+ hasRequiredIsBoolean = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBoolean;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var defaultOptions = {
+ loose: false
+ };
+ var strictBooleans = ['true', 'false', '1', '0'];
+ var looseBooleans = [].concat(strictBooleans, ['yes', 'no']);
+
+ function isBoolean(str) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOptions;
+ (0, _assertString.default)(str);
+
+ if (options.loose) {
+ return looseBooleans.includes(str.toLowerCase());
+ }
+
+ return strictBooleans.includes(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBoolean$1, isBooleanExports));
+ return isBooleanExports;
+}
+
+var isLocaleExports = {};
+var isLocale = {
+ get exports(){ return isLocaleExports; },
+ set exports(v){ isLocaleExports = v; },
+};
+
+var hasRequiredIsLocale;
+
+function requireIsLocale () {
+ if (hasRequiredIsLocale) return isLocaleExports;
+ hasRequiredIsLocale = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isLocale;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var localeReg = /^[A-Za-z]{2,4}([_-]([A-Za-z]{4}|[\d]{3}))?([_-]([A-Za-z]{2}|[\d]{3}))?$/;
+
+ function isLocale(str) {
+ (0, _assertString.default)(str);
+
+ if (str === 'en_US_POSIX' || str === 'ca_ES_VALENCIA') {
+ return true;
+ }
+
+ return localeReg.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isLocale, isLocaleExports));
+ return isLocaleExports;
+}
+
+var isAlpha = {};
+
+var hasRequiredIsAlpha;
+
+function requireIsAlpha () {
+ if (hasRequiredIsAlpha) return isAlpha;
+ hasRequiredIsAlpha = 1;
+
+ Object.defineProperty(isAlpha, "__esModule", {
+ value: true
+ });
+ isAlpha.default = isAlpha$1;
+ isAlpha.locales = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _alpha = requireAlpha();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isAlpha$1(_str) {
+ var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ (0, _assertString.default)(_str);
+ var str = _str;
+ var ignore = options.ignore;
+
+ if (ignore) {
+ if (ignore instanceof RegExp) {
+ str = str.replace(ignore, '');
+ } else if (typeof ignore === 'string') {
+ str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore
+ } else {
+ throw new Error('ignore should be instance of a String or RegExp');
+ }
+ }
+
+ if (locale in _alpha.alpha) {
+ return _alpha.alpha[locale].test(str);
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+
+ var locales = Object.keys(_alpha.alpha);
+ isAlpha.locales = locales;
+ return isAlpha;
+}
+
+var isAlphanumeric = {};
+
+var hasRequiredIsAlphanumeric;
+
+function requireIsAlphanumeric () {
+ if (hasRequiredIsAlphanumeric) return isAlphanumeric;
+ hasRequiredIsAlphanumeric = 1;
+
+ Object.defineProperty(isAlphanumeric, "__esModule", {
+ value: true
+ });
+ isAlphanumeric.default = isAlphanumeric$1;
+ isAlphanumeric.locales = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _alpha = requireAlpha();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isAlphanumeric$1(_str) {
+ var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ (0, _assertString.default)(_str);
+ var str = _str;
+ var ignore = options.ignore;
+
+ if (ignore) {
+ if (ignore instanceof RegExp) {
+ str = str.replace(ignore, '');
+ } else if (typeof ignore === 'string') {
+ str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore
+ } else {
+ throw new Error('ignore should be instance of a String or RegExp');
+ }
+ }
+
+ if (locale in _alpha.alphanumeric) {
+ return _alpha.alphanumeric[locale].test(str);
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+
+ var locales = Object.keys(_alpha.alphanumeric);
+ isAlphanumeric.locales = locales;
+ return isAlphanumeric;
+}
+
+var isNumericExports = {};
+var isNumeric = {
+ get exports(){ return isNumericExports; },
+ set exports(v){ isNumericExports = v; },
+};
+
+var hasRequiredIsNumeric;
+
+function requireIsNumeric () {
+ if (hasRequiredIsNumeric) return isNumericExports;
+ hasRequiredIsNumeric = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isNumeric;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _alpha = requireAlpha();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var numericNoSymbols = /^[0-9]+$/;
+
+ function isNumeric(str, options) {
+ (0, _assertString.default)(str);
+
+ if (options && options.no_symbols) {
+ return numericNoSymbols.test(str);
+ }
+
+ return new RegExp("^[+-]?([0-9]*[".concat((options || {}).locale ? _alpha.decimal[options.locale] : '.', "])?[0-9]+$")).test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isNumeric, isNumericExports));
+ return isNumericExports;
+}
+
+var isPassportNumberExports = {};
+var isPassportNumber = {
+ get exports(){ return isPassportNumberExports; },
+ set exports(v){ isPassportNumberExports = v; },
+};
+
+var hasRequiredIsPassportNumber;
+
+function requireIsPassportNumber () {
+ if (hasRequiredIsPassportNumber) return isPassportNumberExports;
+ hasRequiredIsPassportNumber = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isPassportNumber;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /**
+ * Reference:
+ * https://en.wikipedia.org/ -- Wikipedia
+ * https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number
+ * https://countrycode.org/ -- Country Codes
+ */
+ var passportRegexByCountryCode = {
+ AM: /^[A-Z]{2}\d{7}$/,
+ // ARMENIA
+ AR: /^[A-Z]{3}\d{6}$/,
+ // ARGENTINA
+ AT: /^[A-Z]\d{7}$/,
+ // AUSTRIA
+ AU: /^[A-Z]\d{7}$/,
+ // AUSTRALIA
+ AZ: /^[A-Z]{2,3}\d{7,8}$/,
+ // AZERBAIJAN
+ BE: /^[A-Z]{2}\d{6}$/,
+ // BELGIUM
+ BG: /^\d{9}$/,
+ // BULGARIA
+ BR: /^[A-Z]{2}\d{6}$/,
+ // BRAZIL
+ BY: /^[A-Z]{2}\d{7}$/,
+ // BELARUS
+ CA: /^[A-Z]{2}\d{6}$/,
+ // CANADA
+ CH: /^[A-Z]\d{7}$/,
+ // SWITZERLAND
+ CN: /^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$/,
+ // CHINA [G=Ordinary, E=Electronic] followed by 8-digits, or E followed by any UPPERCASE letter (except I and O) followed by 7 digits
+ CY: /^[A-Z](\d{6}|\d{8})$/,
+ // CYPRUS
+ CZ: /^\d{8}$/,
+ // CZECH REPUBLIC
+ DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/,
+ // GERMANY
+ DK: /^\d{9}$/,
+ // DENMARK
+ DZ: /^\d{9}$/,
+ // ALGERIA
+ EE: /^([A-Z]\d{7}|[A-Z]{2}\d{7})$/,
+ // ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits
+ ES: /^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$/,
+ // SPAIN
+ FI: /^[A-Z]{2}\d{7}$/,
+ // FINLAND
+ FR: /^\d{2}[A-Z]{2}\d{5}$/,
+ // FRANCE
+ GB: /^\d{9}$/,
+ // UNITED KINGDOM
+ GR: /^[A-Z]{2}\d{7}$/,
+ // GREECE
+ HR: /^\d{9}$/,
+ // CROATIA
+ HU: /^[A-Z]{2}(\d{6}|\d{7})$/,
+ // HUNGARY
+ IE: /^[A-Z0-9]{2}\d{7}$/,
+ // IRELAND
+ IN: /^[A-Z]{1}-?\d{7}$/,
+ // INDIA
+ ID: /^[A-C]\d{7}$/,
+ // INDONESIA
+ IR: /^[A-Z]\d{8}$/,
+ // IRAN
+ IS: /^(A)\d{7}$/,
+ // ICELAND
+ IT: /^[A-Z0-9]{2}\d{7}$/,
+ // ITALY
+ JM: /^[Aa]\d{7}$/,
+ // JAMAICA
+ JP: /^[A-Z]{2}\d{7}$/,
+ // JAPAN
+ KR: /^[MS]\d{8}$/,
+ // SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports]
+ KZ: /^[a-zA-Z]\d{7}$/,
+ // KAZAKHSTAN
+ LI: /^[a-zA-Z]\d{5}$/,
+ // LIECHTENSTEIN
+ LT: /^[A-Z0-9]{8}$/,
+ // LITHUANIA
+ LU: /^[A-Z0-9]{8}$/,
+ // LUXEMBURG
+ LV: /^[A-Z0-9]{2}\d{7}$/,
+ // LATVIA
+ LY: /^[A-Z0-9]{8}$/,
+ // LIBYA
+ MT: /^\d{7}$/,
+ // MALTA
+ MZ: /^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$/,
+ // MOZAMBIQUE
+ MY: /^[AHK]\d{8}$/,
+ // MALAYSIA
+ MX: /^\d{10,11}$/,
+ // MEXICO
+ NL: /^[A-Z]{2}[A-Z0-9]{6}\d$/,
+ // NETHERLANDS
+ NZ: /^([Ll]([Aa]|[Dd]|[Ff]|[Hh])|[Ee]([Aa]|[Pp])|[Nn])\d{6}$/,
+ // NEW ZEALAND
+ PH: /^([A-Z](\d{6}|\d{7}[A-Z]))|([A-Z]{2}(\d{6}|\d{7}))$/,
+ // PHILIPPINES
+ PK: /^[A-Z]{2}\d{7}$/,
+ // PAKISTAN
+ PL: /^[A-Z]{2}\d{7}$/,
+ // POLAND
+ PT: /^[A-Z]\d{6}$/,
+ // PORTUGAL
+ RO: /^\d{8,9}$/,
+ // ROMANIA
+ RU: /^\d{9}$/,
+ // RUSSIAN FEDERATION
+ SE: /^\d{8}$/,
+ // SWEDEN
+ SL: /^(P)[A-Z]\d{7}$/,
+ // SLOVENIA
+ SK: /^[0-9A-Z]\d{7}$/,
+ // SLOVAKIA
+ TH: /^[A-Z]{1,2}\d{6,7}$/,
+ // THAILAND
+ TR: /^[A-Z]\d{8}$/,
+ // TURKEY
+ UA: /^[A-Z]{2}\d{6}$/,
+ // UKRAINE
+ US: /^\d{9}$/ // UNITED STATES
+
+ };
+ /**
+ * Check if str is a valid passport number
+ * relative to provided ISO Country Code.
+ *
+ * @param {string} str
+ * @param {string} countryCode
+ * @return {boolean}
+ */
+
+ function isPassportNumber(str, countryCode) {
+ (0, _assertString.default)(str);
+ /** Remove All Whitespaces, Convert to UPPERCASE */
+
+ var normalizedStr = str.replace(/\s/g, '').toUpperCase();
+ return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isPassportNumber, isPassportNumberExports));
+ return isPassportNumberExports;
+}
+
+var isPortExports = {};
+var isPort = {
+ get exports(){ return isPortExports; },
+ set exports(v){ isPortExports = v; },
+};
+
+var isIntExports = {};
+var isInt = {
+ get exports(){ return isIntExports; },
+ set exports(v){ isIntExports = v; },
+};
+
+var hasRequiredIsInt;
+
+function requireIsInt () {
+ if (hasRequiredIsInt) return isIntExports;
+ hasRequiredIsInt = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isInt;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;
+ var intLeadingZeroes = /^[-+]?[0-9]+$/;
+
+ function isInt(str, options) {
+ (0, _assertString.default)(str);
+ options = options || {}; // Get the regex to use for testing, based on whether
+ // leading zeroes are allowed or not.
+
+ var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes; // Check min/max/lt/gt
+
+ var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;
+ var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;
+ var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt;
+ var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt;
+ return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isInt, isIntExports));
+ return isIntExports;
+}
+
+var hasRequiredIsPort;
+
+function requireIsPort () {
+ if (hasRequiredIsPort) return isPortExports;
+ hasRequiredIsPort = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isPort;
+
+ var _isInt = _interopRequireDefault(requireIsInt());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isPort(str) {
+ return (0, _isInt.default)(str, {
+ min: 0,
+ max: 65535
+ });
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isPort, isPortExports));
+ return isPortExports;
+}
+
+var isLowercaseExports = {};
+var isLowercase = {
+ get exports(){ return isLowercaseExports; },
+ set exports(v){ isLowercaseExports = v; },
+};
+
+var hasRequiredIsLowercase;
+
+function requireIsLowercase () {
+ if (hasRequiredIsLowercase) return isLowercaseExports;
+ hasRequiredIsLowercase = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isLowercase;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isLowercase(str) {
+ (0, _assertString.default)(str);
+ return str === str.toLowerCase();
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isLowercase, isLowercaseExports));
+ return isLowercaseExports;
+}
+
+var isUppercaseExports = {};
+var isUppercase = {
+ get exports(){ return isUppercaseExports; },
+ set exports(v){ isUppercaseExports = v; },
+};
+
+var hasRequiredIsUppercase;
+
+function requireIsUppercase () {
+ if (hasRequiredIsUppercase) return isUppercaseExports;
+ hasRequiredIsUppercase = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isUppercase;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isUppercase(str) {
+ (0, _assertString.default)(str);
+ return str === str.toUpperCase();
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isUppercase, isUppercaseExports));
+ return isUppercaseExports;
+}
+
+var isIMEIExports = {};
+var isIMEI = {
+ get exports(){ return isIMEIExports; },
+ set exports(v){ isIMEIExports = v; },
+};
+
+var hasRequiredIsIMEI;
+
+function requireIsIMEI () {
+ if (hasRequiredIsIMEI) return isIMEIExports;
+ hasRequiredIsIMEI = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isIMEI;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var imeiRegexWithoutHypens = /^[0-9]{15}$/;
+ var imeiRegexWithHypens = /^\d{2}-\d{6}-\d{6}-\d{1}$/;
+
+ function isIMEI(str, options) {
+ (0, _assertString.default)(str);
+ options = options || {}; // default regex for checking imei is the one without hyphens
+
+ var imeiRegex = imeiRegexWithoutHypens;
+
+ if (options.allow_hyphens) {
+ imeiRegex = imeiRegexWithHypens;
+ }
+
+ if (!imeiRegex.test(str)) {
+ return false;
+ }
+
+ str = str.replace(/-/g, '');
+ var sum = 0,
+ mul = 2,
+ l = 14;
+
+ for (var i = 0; i < l; i++) {
+ var digit = str.substring(l - i - 1, l - i);
+ var tp = parseInt(digit, 10) * mul;
+
+ if (tp >= 10) {
+ sum += tp % 10 + 1;
+ } else {
+ sum += tp;
+ }
+
+ if (mul === 1) {
+ mul += 1;
+ } else {
+ mul -= 1;
+ }
+ }
+
+ var chk = (10 - sum % 10) % 10;
+
+ if (chk !== parseInt(str.substring(14, 15), 10)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isIMEI, isIMEIExports));
+ return isIMEIExports;
+}
+
+var isAsciiExports = {};
+var isAscii = {
+ get exports(){ return isAsciiExports; },
+ set exports(v){ isAsciiExports = v; },
+};
+
+var hasRequiredIsAscii;
+
+function requireIsAscii () {
+ if (hasRequiredIsAscii) return isAsciiExports;
+ hasRequiredIsAscii = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isAscii;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /* eslint-disable no-control-regex */
+ var ascii = /^[\x00-\x7F]+$/;
+ /* eslint-enable no-control-regex */
+
+ function isAscii(str) {
+ (0, _assertString.default)(str);
+ return ascii.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isAscii, isAsciiExports));
+ return isAsciiExports;
+}
+
+var isFullWidth = {};
+
+var hasRequiredIsFullWidth;
+
+function requireIsFullWidth () {
+ if (hasRequiredIsFullWidth) return isFullWidth;
+ hasRequiredIsFullWidth = 1;
+
+ Object.defineProperty(isFullWidth, "__esModule", {
+ value: true
+ });
+ isFullWidth.default = isFullWidth$1;
+ isFullWidth.fullWidth = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
+ isFullWidth.fullWidth = fullWidth;
+
+ function isFullWidth$1(str) {
+ (0, _assertString.default)(str);
+ return fullWidth.test(str);
+ }
+ return isFullWidth;
+}
+
+var isHalfWidth = {};
+
+var hasRequiredIsHalfWidth;
+
+function requireIsHalfWidth () {
+ if (hasRequiredIsHalfWidth) return isHalfWidth;
+ hasRequiredIsHalfWidth = 1;
+
+ Object.defineProperty(isHalfWidth, "__esModule", {
+ value: true
+ });
+ isHalfWidth.default = isHalfWidth$1;
+ isHalfWidth.halfWidth = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
+ isHalfWidth.halfWidth = halfWidth;
+
+ function isHalfWidth$1(str) {
+ (0, _assertString.default)(str);
+ return halfWidth.test(str);
+ }
+ return isHalfWidth;
+}
+
+var isVariableWidthExports = {};
+var isVariableWidth = {
+ get exports(){ return isVariableWidthExports; },
+ set exports(v){ isVariableWidthExports = v; },
+};
+
+var hasRequiredIsVariableWidth;
+
+function requireIsVariableWidth () {
+ if (hasRequiredIsVariableWidth) return isVariableWidthExports;
+ hasRequiredIsVariableWidth = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isVariableWidth;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isFullWidth = requireIsFullWidth();
+
+ var _isHalfWidth = requireIsHalfWidth();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isVariableWidth(str) {
+ (0, _assertString.default)(str);
+ return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isVariableWidth, isVariableWidthExports));
+ return isVariableWidthExports;
+}
+
+var isMultibyteExports = {};
+var isMultibyte = {
+ get exports(){ return isMultibyteExports; },
+ set exports(v){ isMultibyteExports = v; },
+};
+
+var hasRequiredIsMultibyte;
+
+function requireIsMultibyte () {
+ if (hasRequiredIsMultibyte) return isMultibyteExports;
+ hasRequiredIsMultibyte = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isMultibyte;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /* eslint-disable no-control-regex */
+ var multibyte = /[^\x00-\x7F]/;
+ /* eslint-enable no-control-regex */
+
+ function isMultibyte(str) {
+ (0, _assertString.default)(str);
+ return multibyte.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isMultibyte, isMultibyteExports));
+ return isMultibyteExports;
+}
+
+var isSemVerExports = {};
+var isSemVer = {
+ get exports(){ return isSemVerExports; },
+ set exports(v){ isSemVerExports = v; },
+};
+
+var multilineRegexExports = {};
+var multilineRegex = {
+ get exports(){ return multilineRegexExports; },
+ set exports(v){ multilineRegexExports = v; },
+};
+
+var hasRequiredMultilineRegex;
+
+function requireMultilineRegex () {
+ if (hasRequiredMultilineRegex) return multilineRegexExports;
+ hasRequiredMultilineRegex = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = multilineRegexp;
+
+ /**
+ * Build RegExp object from an array
+ * of multiple/multi-line regexp parts
+ *
+ * @param {string[]} parts
+ * @param {string} flags
+ * @return {object} - RegExp object
+ */
+ function multilineRegexp(parts, flags) {
+ var regexpAsStringLiteral = parts.join('');
+ return new RegExp(regexpAsStringLiteral, flags);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (multilineRegex, multilineRegexExports));
+ return multilineRegexExports;
+}
+
+var hasRequiredIsSemVer;
+
+function requireIsSemVer () {
+ if (hasRequiredIsSemVer) return isSemVerExports;
+ hasRequiredIsSemVer = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isSemVer;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _multilineRegex = _interopRequireDefault(requireMultilineRegex());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /**
+ * Regular Expression to match
+ * semantic versioning (SemVer)
+ * built from multi-line, multi-parts regexp
+ * Reference: https://semver.org/
+ */
+ var semanticVersioningRegex = (0, _multilineRegex.default)(['^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)', '(?:-((?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-z-][0-9a-z-]*))*))', '?(?:\\+([0-9a-z-]+(?:\\.[0-9a-z-]+)*))?$'], 'i');
+
+ function isSemVer(str) {
+ (0, _assertString.default)(str);
+ return semanticVersioningRegex.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isSemVer, isSemVerExports));
+ return isSemVerExports;
+}
+
+var isSurrogatePairExports = {};
+var isSurrogatePair = {
+ get exports(){ return isSurrogatePairExports; },
+ set exports(v){ isSurrogatePairExports = v; },
+};
+
+var hasRequiredIsSurrogatePair;
+
+function requireIsSurrogatePair () {
+ if (hasRequiredIsSurrogatePair) return isSurrogatePairExports;
+ hasRequiredIsSurrogatePair = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isSurrogatePair;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;
+
+ function isSurrogatePair(str) {
+ (0, _assertString.default)(str);
+ return surrogatePair.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isSurrogatePair, isSurrogatePairExports));
+ return isSurrogatePairExports;
+}
+
+var isDecimalExports = {};
+var isDecimal = {
+ get exports(){ return isDecimalExports; },
+ set exports(v){ isDecimalExports = v; },
+};
+
+var includesExports = {};
+var includes = {
+ get exports(){ return includesExports; },
+ set exports(v){ includesExports = v; },
+};
+
+var hasRequiredIncludes;
+
+function requireIncludes () {
+ if (hasRequiredIncludes) return includesExports;
+ hasRequiredIncludes = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = void 0;
+
+ var includes = function includes(arr, val) {
+ return arr.some(function (arrVal) {
+ return val === arrVal;
+ });
+ };
+
+ var _default = includes;
+ exports.default = _default;
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (includes, includesExports));
+ return includesExports;
+}
+
+var hasRequiredIsDecimal;
+
+function requireIsDecimal () {
+ if (hasRequiredIsDecimal) return isDecimalExports;
+ hasRequiredIsDecimal = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isDecimal;
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _includes = _interopRequireDefault(requireIncludes());
+
+ var _alpha = requireAlpha();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function decimalRegExp(options) {
+ var regExp = new RegExp("^[-+]?([0-9]+)?(\\".concat(_alpha.decimal[options.locale], "[0-9]{").concat(options.decimal_digits, "})").concat(options.force_decimal ? '' : '?', "$"));
+ return regExp;
+ }
+
+ var default_decimal_options = {
+ force_decimal: false,
+ decimal_digits: '1,',
+ locale: 'en-US'
+ };
+ var blacklist = ['', '-', '+'];
+
+ function isDecimal(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, default_decimal_options);
+
+ if (options.locale in _alpha.decimal) {
+ return !(0, _includes.default)(blacklist, str.replace(/ /g, '')) && decimalRegExp(options).test(str);
+ }
+
+ throw new Error("Invalid locale '".concat(options.locale, "'"));
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isDecimal, isDecimalExports));
+ return isDecimalExports;
+}
+
+var isHexadecimalExports = {};
+var isHexadecimal = {
+ get exports(){ return isHexadecimalExports; },
+ set exports(v){ isHexadecimalExports = v; },
+};
+
+var hasRequiredIsHexadecimal;
+
+function requireIsHexadecimal () {
+ if (hasRequiredIsHexadecimal) return isHexadecimalExports;
+ hasRequiredIsHexadecimal = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isHexadecimal;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var hexadecimal = /^(0x|0h)?[0-9A-F]+$/i;
+
+ function isHexadecimal(str) {
+ (0, _assertString.default)(str);
+ return hexadecimal.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isHexadecimal, isHexadecimalExports));
+ return isHexadecimalExports;
+}
+
+var isOctalExports = {};
+var isOctal = {
+ get exports(){ return isOctalExports; },
+ set exports(v){ isOctalExports = v; },
+};
+
+var hasRequiredIsOctal;
+
+function requireIsOctal () {
+ if (hasRequiredIsOctal) return isOctalExports;
+ hasRequiredIsOctal = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isOctal;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var octal = /^(0o)?[0-7]+$/i;
+
+ function isOctal(str) {
+ (0, _assertString.default)(str);
+ return octal.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isOctal, isOctalExports));
+ return isOctalExports;
+}
+
+var isDivisibleByExports = {};
+var isDivisibleBy = {
+ get exports(){ return isDivisibleByExports; },
+ set exports(v){ isDivisibleByExports = v; },
+};
+
+var hasRequiredIsDivisibleBy;
+
+function requireIsDivisibleBy () {
+ if (hasRequiredIsDivisibleBy) return isDivisibleByExports;
+ hasRequiredIsDivisibleBy = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isDivisibleBy;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _toFloat = _interopRequireDefault(requireToFloat());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isDivisibleBy(str, num) {
+ (0, _assertString.default)(str);
+ return (0, _toFloat.default)(str) % parseInt(num, 10) === 0;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isDivisibleBy, isDivisibleByExports));
+ return isDivisibleByExports;
+}
+
+var isHexColorExports = {};
+var isHexColor = {
+ get exports(){ return isHexColorExports; },
+ set exports(v){ isHexColorExports = v; },
+};
+
+var hasRequiredIsHexColor;
+
+function requireIsHexColor () {
+ if (hasRequiredIsHexColor) return isHexColorExports;
+ hasRequiredIsHexColor = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isHexColor;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i;
+
+ function isHexColor(str) {
+ (0, _assertString.default)(str);
+ return hexcolor.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isHexColor, isHexColorExports));
+ return isHexColorExports;
+}
+
+var isRgbColorExports = {};
+var isRgbColor = {
+ get exports(){ return isRgbColorExports; },
+ set exports(v){ isRgbColorExports = v; },
+};
+
+var hasRequiredIsRgbColor;
+
+function requireIsRgbColor () {
+ if (hasRequiredIsRgbColor) return isRgbColorExports;
+ hasRequiredIsRgbColor = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isRgbColor;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var rgbColor = /^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$/;
+ var rgbaColor = /^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/;
+ var rgbColorPercent = /^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)$/;
+ var rgbaColorPercent = /^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$/;
+
+ function isRgbColor(str) {
+ var includePercentValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
+ (0, _assertString.default)(str);
+
+ if (!includePercentValues) {
+ return rgbColor.test(str) || rgbaColor.test(str);
+ }
+
+ return rgbColor.test(str) || rgbaColor.test(str) || rgbColorPercent.test(str) || rgbaColorPercent.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isRgbColor, isRgbColorExports));
+ return isRgbColorExports;
+}
+
+var isHSLExports = {};
+var isHSL = {
+ get exports(){ return isHSLExports; },
+ set exports(v){ isHSLExports = v; },
+};
+
+var hasRequiredIsHSL;
+
+function requireIsHSL () {
+ if (hasRequiredIsHSL) return isHSLExports;
+ hasRequiredIsHSL = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isHSL;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var hslComma = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(,(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}(,((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?))?\)$/i;
+ var hslSpace = /^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(\s(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}\s?(\/\s((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?)\s?)?\)$/i;
+
+ function isHSL(str) {
+ (0, _assertString.default)(str); // Strip duplicate spaces before calling the validation regex (See #1598 for more info)
+
+ var strippedStr = str.replace(/\s+/g, ' ').replace(/\s?(hsla?\(|\)|,)\s?/ig, '$1');
+
+ if (strippedStr.indexOf(',') !== -1) {
+ return hslComma.test(strippedStr);
+ }
+
+ return hslSpace.test(strippedStr);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isHSL, isHSLExports));
+ return isHSLExports;
+}
+
+var isISRCExports = {};
+var isISRC = {
+ get exports(){ return isISRCExports; },
+ set exports(v){ isISRCExports = v; },
+};
+
+var hasRequiredIsISRC;
+
+function requireIsISRC () {
+ if (hasRequiredIsISRC) return isISRCExports;
+ hasRequiredIsISRC = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISRC;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // see http://isrc.ifpi.org/en/isrc-standard/code-syntax
+ var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/;
+
+ function isISRC(str) {
+ (0, _assertString.default)(str);
+ return isrc.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISRC, isISRCExports));
+ return isISRCExports;
+}
+
+var isIBAN = {};
+
+var hasRequiredIsIBAN;
+
+function requireIsIBAN () {
+ if (hasRequiredIsIBAN) return isIBAN;
+ hasRequiredIsIBAN = 1;
+
+ Object.defineProperty(isIBAN, "__esModule", {
+ value: true
+ });
+ isIBAN.default = isIBAN$1;
+ isIBAN.locales = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /**
+ * List of country codes with
+ * corresponding IBAN regular expression
+ * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number
+ */
+ var ibanRegexThroughCountryCode = {
+ AD: /^(AD[0-9]{2})\d{8}[A-Z0-9]{12}$/,
+ AE: /^(AE[0-9]{2})\d{3}\d{16}$/,
+ AL: /^(AL[0-9]{2})\d{8}[A-Z0-9]{16}$/,
+ AT: /^(AT[0-9]{2})\d{16}$/,
+ AZ: /^(AZ[0-9]{2})[A-Z0-9]{4}\d{20}$/,
+ BA: /^(BA[0-9]{2})\d{16}$/,
+ BE: /^(BE[0-9]{2})\d{12}$/,
+ BG: /^(BG[0-9]{2})[A-Z]{4}\d{6}[A-Z0-9]{8}$/,
+ BH: /^(BH[0-9]{2})[A-Z]{4}[A-Z0-9]{14}$/,
+ BR: /^(BR[0-9]{2})\d{23}[A-Z]{1}[A-Z0-9]{1}$/,
+ BY: /^(BY[0-9]{2})[A-Z0-9]{4}\d{20}$/,
+ CH: /^(CH[0-9]{2})\d{5}[A-Z0-9]{12}$/,
+ CR: /^(CR[0-9]{2})\d{18}$/,
+ CY: /^(CY[0-9]{2})\d{8}[A-Z0-9]{16}$/,
+ CZ: /^(CZ[0-9]{2})\d{20}$/,
+ DE: /^(DE[0-9]{2})\d{18}$/,
+ DK: /^(DK[0-9]{2})\d{14}$/,
+ DO: /^(DO[0-9]{2})[A-Z]{4}\d{20}$/,
+ EE: /^(EE[0-9]{2})\d{16}$/,
+ EG: /^(EG[0-9]{2})\d{25}$/,
+ ES: /^(ES[0-9]{2})\d{20}$/,
+ FI: /^(FI[0-9]{2})\d{14}$/,
+ FO: /^(FO[0-9]{2})\d{14}$/,
+ FR: /^(FR[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/,
+ GB: /^(GB[0-9]{2})[A-Z]{4}\d{14}$/,
+ GE: /^(GE[0-9]{2})[A-Z0-9]{2}\d{16}$/,
+ GI: /^(GI[0-9]{2})[A-Z]{4}[A-Z0-9]{15}$/,
+ GL: /^(GL[0-9]{2})\d{14}$/,
+ GR: /^(GR[0-9]{2})\d{7}[A-Z0-9]{16}$/,
+ GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/,
+ HR: /^(HR[0-9]{2})\d{17}$/,
+ HU: /^(HU[0-9]{2})\d{24}$/,
+ IE: /^(IE[0-9]{2})[A-Z0-9]{4}\d{14}$/,
+ IL: /^(IL[0-9]{2})\d{19}$/,
+ IQ: /^(IQ[0-9]{2})[A-Z]{4}\d{15}$/,
+ IR: /^(IR[0-9]{2})0\d{2}0\d{18}$/,
+ IS: /^(IS[0-9]{2})\d{22}$/,
+ IT: /^(IT[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/,
+ JO: /^(JO[0-9]{2})[A-Z]{4}\d{22}$/,
+ KW: /^(KW[0-9]{2})[A-Z]{4}[A-Z0-9]{22}$/,
+ KZ: /^(KZ[0-9]{2})\d{3}[A-Z0-9]{13}$/,
+ LB: /^(LB[0-9]{2})\d{4}[A-Z0-9]{20}$/,
+ LC: /^(LC[0-9]{2})[A-Z]{4}[A-Z0-9]{24}$/,
+ LI: /^(LI[0-9]{2})\d{5}[A-Z0-9]{12}$/,
+ LT: /^(LT[0-9]{2})\d{16}$/,
+ LU: /^(LU[0-9]{2})\d{3}[A-Z0-9]{13}$/,
+ LV: /^(LV[0-9]{2})[A-Z]{4}[A-Z0-9]{13}$/,
+ MC: /^(MC[0-9]{2})\d{10}[A-Z0-9]{11}\d{2}$/,
+ MD: /^(MD[0-9]{2})[A-Z0-9]{20}$/,
+ ME: /^(ME[0-9]{2})\d{18}$/,
+ MK: /^(MK[0-9]{2})\d{3}[A-Z0-9]{10}\d{2}$/,
+ MR: /^(MR[0-9]{2})\d{23}$/,
+ MT: /^(MT[0-9]{2})[A-Z]{4}\d{5}[A-Z0-9]{18}$/,
+ MU: /^(MU[0-9]{2})[A-Z]{4}\d{19}[A-Z]{3}$/,
+ MZ: /^(MZ[0-9]{2})\d{21}$/,
+ NL: /^(NL[0-9]{2})[A-Z]{4}\d{10}$/,
+ NO: /^(NO[0-9]{2})\d{11}$/,
+ PK: /^(PK[0-9]{2})[A-Z0-9]{4}\d{16}$/,
+ PL: /^(PL[0-9]{2})\d{24}$/,
+ PS: /^(PS[0-9]{2})[A-Z0-9]{4}\d{21}$/,
+ PT: /^(PT[0-9]{2})\d{21}$/,
+ QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/,
+ RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/,
+ RS: /^(RS[0-9]{2})\d{18}$/,
+ SA: /^(SA[0-9]{2})\d{2}[A-Z0-9]{18}$/,
+ SC: /^(SC[0-9]{2})[A-Z]{4}\d{20}[A-Z]{3}$/,
+ SE: /^(SE[0-9]{2})\d{20}$/,
+ SI: /^(SI[0-9]{2})\d{15}$/,
+ SK: /^(SK[0-9]{2})\d{20}$/,
+ SM: /^(SM[0-9]{2})[A-Z]{1}\d{10}[A-Z0-9]{12}$/,
+ SV: /^(SV[0-9]{2})[A-Z0-9]{4}\d{20}$/,
+ TL: /^(TL[0-9]{2})\d{19}$/,
+ TN: /^(TN[0-9]{2})\d{20}$/,
+ TR: /^(TR[0-9]{2})\d{5}[A-Z0-9]{17}$/,
+ UA: /^(UA[0-9]{2})\d{6}[A-Z0-9]{19}$/,
+ VA: /^(VA[0-9]{2})\d{18}$/,
+ VG: /^(VG[0-9]{2})[A-Z0-9]{4}\d{16}$/,
+ XK: /^(XK[0-9]{2})\d{16}$/
+ };
+ /**
+ * Check whether string has correct universal IBAN format
+ * The IBAN consists of up to 34 alphanumeric characters, as follows:
+ * Country Code using ISO 3166-1 alpha-2, two letters
+ * check digits, two digits and
+ * Basic Bank Account Number (BBAN), up to 30 alphanumeric characters.
+ * NOTE: Permitted IBAN characters are: digits [0-9] and the 26 latin alphabetic [A-Z]
+ *
+ * @param {string} str - string under validation
+ * @return {boolean}
+ */
+
+ function hasValidIbanFormat(str) {
+ // Strip white spaces and hyphens
+ var strippedStr = str.replace(/[\s\-]+/gi, '').toUpperCase();
+ var isoCountryCode = strippedStr.slice(0, 2).toUpperCase();
+ return isoCountryCode in ibanRegexThroughCountryCode && ibanRegexThroughCountryCode[isoCountryCode].test(strippedStr);
+ }
+ /**
+ * Check whether string has valid IBAN Checksum
+ * by performing basic mod-97 operation and
+ * the remainder should equal 1
+ * -- Start by rearranging the IBAN by moving the four initial characters to the end of the string
+ * -- Replace each letter in the string with two digits, A -> 10, B = 11, Z = 35
+ * -- Interpret the string as a decimal integer and
+ * -- compute the remainder on division by 97 (mod 97)
+ * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number
+ *
+ * @param {string} str
+ * @return {boolean}
+ */
+
+
+ function hasValidIbanChecksum(str) {
+ var strippedStr = str.replace(/[^A-Z0-9]+/gi, '').toUpperCase(); // Keep only digits and A-Z latin alphabetic
+
+ var rearranged = strippedStr.slice(4) + strippedStr.slice(0, 4);
+ var alphaCapsReplacedWithDigits = rearranged.replace(/[A-Z]/g, function (char) {
+ return char.charCodeAt(0) - 55;
+ });
+ var remainder = alphaCapsReplacedWithDigits.match(/\d{1,7}/g).reduce(function (acc, value) {
+ return Number(acc + value) % 97;
+ }, '');
+ return remainder === 1;
+ }
+
+ function isIBAN$1(str) {
+ (0, _assertString.default)(str);
+ return hasValidIbanFormat(str) && hasValidIbanChecksum(str);
+ }
+
+ var locales = Object.keys(ibanRegexThroughCountryCode);
+ isIBAN.locales = locales;
+ return isIBAN;
+}
+
+var isBICExports = {};
+var isBIC = {
+ get exports(){ return isBICExports; },
+ set exports(v){ isBICExports = v; },
+};
+
+var isISO31661Alpha2 = {};
+
+var hasRequiredIsISO31661Alpha2;
+
+function requireIsISO31661Alpha2 () {
+ if (hasRequiredIsISO31661Alpha2) return isISO31661Alpha2;
+ hasRequiredIsISO31661Alpha2 = 1;
+
+ Object.defineProperty(isISO31661Alpha2, "__esModule", {
+ value: true
+ });
+ isISO31661Alpha2.default = isISO31661Alpha2$1;
+ isISO31661Alpha2.CountryCodes = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
+ var validISO31661Alpha2CountriesCodes = new Set(['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW']);
+
+ function isISO31661Alpha2$1(str) {
+ (0, _assertString.default)(str);
+ return validISO31661Alpha2CountriesCodes.has(str.toUpperCase());
+ }
+
+ var CountryCodes = validISO31661Alpha2CountriesCodes;
+ isISO31661Alpha2.CountryCodes = CountryCodes;
+ return isISO31661Alpha2;
+}
+
+var hasRequiredIsBIC;
+
+function requireIsBIC () {
+ if (hasRequiredIsBIC) return isBICExports;
+ hasRequiredIsBIC = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBIC;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isISO31661Alpha = requireIsISO31661Alpha2();
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // https://en.wikipedia.org/wiki/ISO_9362
+ var isBICReg = /^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$/;
+
+ function isBIC(str) {
+ (0, _assertString.default)(str); // toUpperCase() should be removed when a new major version goes out that changes
+ // the regex to [A-Z] (per the spec).
+
+ var countryCode = str.slice(4, 6).toUpperCase();
+
+ if (!_isISO31661Alpha.CountryCodes.has(countryCode) && countryCode !== 'XK') {
+ return false;
+ }
+
+ return isBICReg.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBIC, isBICExports));
+ return isBICExports;
+}
+
+var isMD5Exports = {};
+var isMD5 = {
+ get exports(){ return isMD5Exports; },
+ set exports(v){ isMD5Exports = v; },
+};
+
+var hasRequiredIsMD5;
+
+function requireIsMD5 () {
+ if (hasRequiredIsMD5) return isMD5Exports;
+ hasRequiredIsMD5 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isMD5;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var md5 = /^[a-f0-9]{32}$/;
+
+ function isMD5(str) {
+ (0, _assertString.default)(str);
+ return md5.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isMD5, isMD5Exports));
+ return isMD5Exports;
+}
+
+var isHashExports = {};
+var isHash = {
+ get exports(){ return isHashExports; },
+ set exports(v){ isHashExports = v; },
+};
+
+var hasRequiredIsHash;
+
+function requireIsHash () {
+ if (hasRequiredIsHash) return isHashExports;
+ hasRequiredIsHash = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isHash;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var lengths = {
+ md5: 32,
+ md4: 32,
+ sha1: 40,
+ sha256: 64,
+ sha384: 96,
+ sha512: 128,
+ ripemd128: 32,
+ ripemd160: 40,
+ tiger128: 32,
+ tiger160: 40,
+ tiger192: 48,
+ crc32: 8,
+ crc32b: 8
+ };
+
+ function isHash(str, algorithm) {
+ (0, _assertString.default)(str);
+ var hash = new RegExp("^[a-fA-F0-9]{".concat(lengths[algorithm], "}$"));
+ return hash.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isHash, isHashExports));
+ return isHashExports;
+}
+
+var isJWTExports = {};
+var isJWT = {
+ get exports(){ return isJWTExports; },
+ set exports(v){ isJWTExports = v; },
+};
+
+var isBase64Exports$1 = {};
+var isBase64$2 = {
+ get exports(){ return isBase64Exports$1; },
+ set exports(v){ isBase64Exports$1 = v; },
+};
+
+var hasRequiredIsBase64;
+
+function requireIsBase64 () {
+ if (hasRequiredIsBase64) return isBase64Exports$1;
+ hasRequiredIsBase64 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBase64;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var notBase64 = /[^A-Z0-9+\/=]/i;
+ var urlSafeBase64 = /^[A-Z0-9_\-]*$/i;
+ var defaultBase64Options = {
+ urlSafe: false
+ };
+
+ function isBase64(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, defaultBase64Options);
+ var len = str.length;
+
+ if (options.urlSafe) {
+ return urlSafeBase64.test(str);
+ }
+
+ if (len % 4 !== 0 || notBase64.test(str)) {
+ return false;
+ }
+
+ var firstPaddingChar = str.indexOf('=');
+ return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBase64$2, isBase64Exports$1));
+ return isBase64Exports$1;
+}
+
+var hasRequiredIsJWT;
+
+function requireIsJWT () {
+ if (hasRequiredIsJWT) return isJWTExports;
+ hasRequiredIsJWT = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isJWT;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isBase = _interopRequireDefault(requireIsBase64());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isJWT(str) {
+ (0, _assertString.default)(str);
+ var dotSplit = str.split('.');
+ var len = dotSplit.length;
+
+ if (len > 3 || len < 2) {
+ return false;
+ }
+
+ return dotSplit.reduce(function (acc, currElem) {
+ return acc && (0, _isBase.default)(currElem, {
+ urlSafe: true
+ });
+ }, true);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isJWT, isJWTExports));
+ return isJWTExports;
+}
+
+var isJSONExports = {};
+var isJSON = {
+ get exports(){ return isJSONExports; },
+ set exports(v){ isJSONExports = v; },
+};
+
+var hasRequiredIsJSON;
+
+function requireIsJSON () {
+ if (hasRequiredIsJSON) return isJSONExports;
+ hasRequiredIsJSON = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isJSON;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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); }
+
+ var default_json_options = {
+ allow_primitives: false
+ };
+
+ function isJSON(str, options) {
+ (0, _assertString.default)(str);
+
+ try {
+ options = (0, _merge.default)(options, default_json_options);
+ var primitives = [];
+
+ if (options.allow_primitives) {
+ primitives = [null, false, true];
+ }
+
+ var obj = JSON.parse(str);
+ return primitives.includes(obj) || !!obj && _typeof(obj) === 'object';
+ } catch (e) {
+ /* ignore */
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isJSON, isJSONExports));
+ return isJSONExports;
+}
+
+var isEmptyExports = {};
+var isEmpty$1 = {
+ get exports(){ return isEmptyExports; },
+ set exports(v){ isEmptyExports = v; },
+};
+
+var hasRequiredIsEmpty;
+
+function requireIsEmpty () {
+ if (hasRequiredIsEmpty) return isEmptyExports;
+ hasRequiredIsEmpty = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isEmpty;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var default_is_empty_options = {
+ ignore_whitespace: false
+ };
+
+ function isEmpty(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, default_is_empty_options);
+ return (options.ignore_whitespace ? str.trim().length : str.length) === 0;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isEmpty$1, isEmptyExports));
+ return isEmptyExports;
+}
+
+var isLengthExports = {};
+var isLength = {
+ get exports(){ return isLengthExports; },
+ set exports(v){ isLengthExports = v; },
+};
+
+var hasRequiredIsLength;
+
+function requireIsLength () {
+ if (hasRequiredIsLength) return isLengthExports;
+ hasRequiredIsLength = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isLength;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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); }
+
+ /* eslint-disable prefer-rest-params */
+ function isLength(str, options) {
+ (0, _assertString.default)(str);
+ var min;
+ var max;
+
+ if (_typeof(options) === 'object') {
+ min = options.min || 0;
+ max = options.max;
+ } else {
+ // backwards compatibility: isLength(str, min [, max])
+ min = arguments[1] || 0;
+ max = arguments[2];
+ }
+
+ var presentationSequences = str.match(/(\uFE0F|\uFE0E)/g) || [];
+ var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || [];
+ var len = str.length - presentationSequences.length - surrogatePairs.length;
+ return len >= min && (typeof max === 'undefined' || len <= max);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isLength, isLengthExports));
+ return isLengthExports;
+}
+
+var isUUIDExports = {};
+var isUUID = {
+ get exports(){ return isUUIDExports; },
+ set exports(v){ isUUIDExports = v; },
+};
+
+var hasRequiredIsUUID;
+
+function requireIsUUID () {
+ if (hasRequiredIsUUID) return isUUIDExports;
+ hasRequiredIsUUID = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isUUID;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var uuid = {
+ 1: /^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
+ 2: /^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
+ 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
+ 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
+ 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
+ all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i
+ };
+
+ function isUUID(str, version) {
+ (0, _assertString.default)(str);
+ var pattern = uuid[![undefined, null].includes(version) ? version : 'all'];
+ return !!pattern && pattern.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isUUID, isUUIDExports));
+ return isUUIDExports;
+}
+
+var isMongoIdExports = {};
+var isMongoId = {
+ get exports(){ return isMongoIdExports; },
+ set exports(v){ isMongoIdExports = v; },
+};
+
+var hasRequiredIsMongoId;
+
+function requireIsMongoId () {
+ if (hasRequiredIsMongoId) return isMongoIdExports;
+ hasRequiredIsMongoId = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isMongoId;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isHexadecimal = _interopRequireDefault(requireIsHexadecimal());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isMongoId(str) {
+ (0, _assertString.default)(str);
+ return (0, _isHexadecimal.default)(str) && str.length === 24;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isMongoId, isMongoIdExports));
+ return isMongoIdExports;
+}
+
+var isAfterExports = {};
+var isAfter = {
+ get exports(){ return isAfterExports; },
+ set exports(v){ isAfterExports = v; },
+};
+
+var hasRequiredIsAfter;
+
+function requireIsAfter () {
+ if (hasRequiredIsAfter) return isAfterExports;
+ hasRequiredIsAfter = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isAfter;
+
+ var _toDate = _interopRequireDefault(requireToDate());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isAfter(date, options) {
+ // For backwards compatibility:
+ // isAfter(str [, date]), i.e. `options` could be used as argument for the legacy `date`
+ var comparisonDate = (options === null || options === void 0 ? void 0 : options.comparisonDate) || options || Date().toString();
+ var comparison = (0, _toDate.default)(comparisonDate);
+ var original = (0, _toDate.default)(date);
+ return !!(original && comparison && original > comparison);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isAfter, isAfterExports));
+ return isAfterExports;
+}
+
+var isBeforeExports = {};
+var isBefore = {
+ get exports(){ return isBeforeExports; },
+ set exports(v){ isBeforeExports = v; },
+};
+
+var hasRequiredIsBefore;
+
+function requireIsBefore () {
+ if (hasRequiredIsBefore) return isBeforeExports;
+ hasRequiredIsBefore = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBefore;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _toDate = _interopRequireDefault(requireToDate());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isBefore(str) {
+ var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());
+ (0, _assertString.default)(str);
+ var comparison = (0, _toDate.default)(date);
+ var original = (0, _toDate.default)(str);
+ return !!(original && comparison && original < comparison);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBefore, isBeforeExports));
+ return isBeforeExports;
+}
+
+var isInExports = {};
+var isIn = {
+ get exports(){ return isInExports; },
+ set exports(v){ isInExports = v; },
+};
+
+var hasRequiredIsIn;
+
+function requireIsIn () {
+ if (hasRequiredIsIn) return isInExports;
+ hasRequiredIsIn = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isIn;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _toString = _interopRequireDefault(requireToString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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 isIn(str, options) {
+ (0, _assertString.default)(str);
+ var i;
+
+ if (Object.prototype.toString.call(options) === '[object Array]') {
+ var array = [];
+
+ for (i in options) {
+ // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
+ // istanbul ignore else
+ if ({}.hasOwnProperty.call(options, i)) {
+ array[i] = (0, _toString.default)(options[i]);
+ }
+ }
+
+ return array.indexOf(str) >= 0;
+ } else if (_typeof(options) === 'object') {
+ return options.hasOwnProperty(str);
+ } else if (options && typeof options.indexOf === 'function') {
+ return options.indexOf(str) >= 0;
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isIn, isInExports));
+ return isInExports;
+}
+
+var isLuhnNumberExports = {};
+var isLuhnNumber = {
+ get exports(){ return isLuhnNumberExports; },
+ set exports(v){ isLuhnNumberExports = v; },
+};
+
+var hasRequiredIsLuhnNumber;
+
+function requireIsLuhnNumber () {
+ if (hasRequiredIsLuhnNumber) return isLuhnNumberExports;
+ hasRequiredIsLuhnNumber = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isLuhnNumber;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isLuhnNumber(str) {
+ (0, _assertString.default)(str);
+ var sanitized = str.replace(/[- ]+/g, '');
+ var sum = 0;
+ var digit;
+ var tmpNum;
+ var shouldDouble;
+
+ for (var i = sanitized.length - 1; i >= 0; i--) {
+ digit = sanitized.substring(i, i + 1);
+ tmpNum = parseInt(digit, 10);
+
+ if (shouldDouble) {
+ tmpNum *= 2;
+
+ if (tmpNum >= 10) {
+ sum += tmpNum % 10 + 1;
+ } else {
+ sum += tmpNum;
+ }
+ } else {
+ sum += tmpNum;
+ }
+
+ shouldDouble = !shouldDouble;
+ }
+
+ return !!(sum % 10 === 0 ? sanitized : false);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isLuhnNumber, isLuhnNumberExports));
+ return isLuhnNumberExports;
+}
+
+var isCreditCardExports = {};
+var isCreditCard = {
+ get exports(){ return isCreditCardExports; },
+ set exports(v){ isCreditCardExports = v; },
+};
+
+var hasRequiredIsCreditCard;
+
+function requireIsCreditCard () {
+ if (hasRequiredIsCreditCard) return isCreditCardExports;
+ hasRequiredIsCreditCard = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isCreditCard;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isLuhnNumber = _interopRequireDefault(requireIsLuhnNumber());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var cards = {
+ amex: /^3[47][0-9]{13}$/,
+ dinersclub: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
+ discover: /^6(?:011|5[0-9][0-9])[0-9]{12,15}$/,
+ jcb: /^(?:2131|1800|35\d{3})\d{11}$/,
+ mastercard: /^5[1-5][0-9]{2}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/,
+ // /^[25][1-7][0-9]{14}$/;
+ unionpay: /^(6[27][0-9]{14}|^(81[0-9]{14,17}))$/,
+ visa: /^(?:4[0-9]{12})(?:[0-9]{3,6})?$/
+ };
+ /* eslint-disable max-len */
+
+ var allCards = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/;
+ /* eslint-enable max-len */
+
+ function isCreditCard(card) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ (0, _assertString.default)(card);
+ var provider = options.provider;
+ var sanitized = card.replace(/[- ]+/g, '');
+
+ if (provider && provider.toLowerCase() in cards) {
+ // specific provider in the list
+ if (!cards[provider.toLowerCase()].test(sanitized)) {
+ return false;
+ }
+ } else if (provider && !(provider.toLowerCase() in cards)) {
+ /* specific provider not in the list */
+ throw new Error("".concat(provider, " is not a valid credit card provider."));
+ } else if (!allCards.test(sanitized)) {
+ // no specific provider
+ return false;
+ }
+
+ return (0, _isLuhnNumber.default)(card);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isCreditCard, isCreditCardExports));
+ return isCreditCardExports;
+}
+
+var isIdentityCardExports = {};
+var isIdentityCard = {
+ get exports(){ return isIdentityCardExports; },
+ set exports(v){ isIdentityCardExports = v; },
+};
+
+var hasRequiredIsIdentityCard;
+
+function requireIsIdentityCard () {
+ if (hasRequiredIsIdentityCard) return isIdentityCardExports;
+ hasRequiredIsIdentityCard = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isIdentityCard;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _isInt = _interopRequireDefault(requireIsInt());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var validators = {
+ PL: function PL(str) {
+ (0, _assertString.default)(str);
+ var weightOfDigits = {
+ 1: 1,
+ 2: 3,
+ 3: 7,
+ 4: 9,
+ 5: 1,
+ 6: 3,
+ 7: 7,
+ 8: 9,
+ 9: 1,
+ 10: 3,
+ 11: 0
+ };
+
+ if (str != null && str.length === 11 && (0, _isInt.default)(str, {
+ allow_leading_zeroes: true
+ })) {
+ var digits = str.split('').slice(0, -1);
+ var sum = digits.reduce(function (acc, digit, index) {
+ return acc + Number(digit) * weightOfDigits[index + 1];
+ }, 0);
+ var modulo = sum % 10;
+ var lastDigit = Number(str.charAt(str.length - 1));
+
+ if (modulo === 0 && lastDigit === 0 || lastDigit === 10 - modulo) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+ ES: function ES(str) {
+ (0, _assertString.default)(str);
+ var DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/;
+ var charsValue = {
+ X: 0,
+ Y: 1,
+ Z: 2
+ };
+ var controlDigits = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; // sanitize user input
+
+ var sanitized = str.trim().toUpperCase(); // validate the data structure
+
+ if (!DNI.test(sanitized)) {
+ return false;
+ } // validate the control digit
+
+
+ var number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, function (char) {
+ return charsValue[char];
+ });
+ return sanitized.endsWith(controlDigits[number % 23]);
+ },
+ FI: function FI(str) {
+ // https://dvv.fi/en/personal-identity-code#:~:text=control%20character%20for%20a-,personal,-identity%20code%20calculated
+ (0, _assertString.default)(str);
+
+ if (str.length !== 11) {
+ return false;
+ }
+
+ if (!str.match(/^\d{6}[\-A\+]\d{3}[0-9ABCDEFHJKLMNPRSTUVWXY]{1}$/)) {
+ return false;
+ }
+
+ var checkDigits = '0123456789ABCDEFHJKLMNPRSTUVWXY';
+ var idAsNumber = parseInt(str.slice(0, 6), 10) * 1000 + parseInt(str.slice(7, 10), 10);
+ var remainder = idAsNumber % 31;
+ var checkDigit = checkDigits[remainder];
+ return checkDigit === str.slice(10, 11);
+ },
+ IN: function IN(str) {
+ var DNI = /^[1-9]\d{3}\s?\d{4}\s?\d{4}$/; // multiplication table
+
+ var d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]]; // permutation table
+
+ var p = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // sanitize user input
+
+ var sanitized = str.trim(); // validate the data structure
+
+ if (!DNI.test(sanitized)) {
+ return false;
+ }
+
+ var c = 0;
+ var invertedArray = sanitized.replace(/\s/g, '').split('').map(Number).reverse();
+ invertedArray.forEach(function (val, i) {
+ c = d[c][p[i % 8][val]];
+ });
+ return c === 0;
+ },
+ IR: function IR(str) {
+ if (!str.match(/^\d{10}$/)) return false;
+ str = "0000".concat(str).slice(str.length - 6);
+ if (parseInt(str.slice(3, 9), 10) === 0) return false;
+ var lastNumber = parseInt(str.slice(9, 10), 10);
+ var sum = 0;
+
+ for (var i = 0; i < 9; i++) {
+ sum += parseInt(str.slice(i, i + 1), 10) * (10 - i);
+ }
+
+ sum %= 11;
+ return sum < 2 && lastNumber === sum || sum >= 2 && lastNumber === 11 - sum;
+ },
+ IT: function IT(str) {
+ if (str.length !== 9) return false;
+ if (str === 'CA00000AA') return false; // https://it.wikipedia.org/wiki/Carta_d%27identit%C3%A0_elettronica_italiana
+
+ return str.search(/C[A-Z][0-9]{5}[A-Z]{2}/i) > -1;
+ },
+ NO: function NO(str) {
+ var sanitized = str.trim();
+ if (isNaN(Number(sanitized))) return false;
+ if (sanitized.length !== 11) return false;
+ if (sanitized === '00000000000') return false; // https://no.wikipedia.org/wiki/F%C3%B8dselsnummer
+
+ var f = sanitized.split('').map(Number);
+ var k1 = (11 - (3 * f[0] + 7 * f[1] + 6 * f[2] + 1 * f[3] + 8 * f[4] + 9 * f[5] + 4 * f[6] + 5 * f[7] + 2 * f[8]) % 11) % 11;
+ var k2 = (11 - (5 * f[0] + 4 * f[1] + 3 * f[2] + 2 * f[3] + 7 * f[4] + 6 * f[5] + 5 * f[6] + 4 * f[7] + 3 * f[8] + 2 * k1) % 11) % 11;
+ if (k1 !== f[9] || k2 !== f[10]) return false;
+ return true;
+ },
+ TH: function TH(str) {
+ if (!str.match(/^[1-8]\d{12}$/)) return false; // validate check digit
+
+ var sum = 0;
+
+ for (var i = 0; i < 12; i++) {
+ sum += parseInt(str[i], 10) * (13 - i);
+ }
+
+ return str[12] === ((11 - sum % 11) % 10).toString();
+ },
+ LK: function LK(str) {
+ var old_nic = /^[1-9]\d{8}[vx]$/i;
+ var new_nic = /^[1-9]\d{11}$/i;
+ if (str.length === 10 && old_nic.test(str)) return true;else if (str.length === 12 && new_nic.test(str)) return true;
+ return false;
+ },
+ 'he-IL': function heIL(str) {
+ var DNI = /^\d{9}$/; // sanitize user input
+
+ var sanitized = str.trim(); // validate the data structure
+
+ if (!DNI.test(sanitized)) {
+ return false;
+ }
+
+ var id = sanitized;
+ var sum = 0,
+ incNum;
+
+ for (var i = 0; i < id.length; i++) {
+ incNum = Number(id[i]) * (i % 2 + 1); // Multiply number by 1 or 2
+
+ sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total
+ }
+
+ return sum % 10 === 0;
+ },
+ 'ar-LY': function arLY(str) {
+ // Libya National Identity Number NIN is 12 digits, the first digit is either 1 or 2
+ var NIN = /^(1|2)\d{11}$/; // sanitize user input
+
+ var sanitized = str.trim(); // validate the data structure
+
+ if (!NIN.test(sanitized)) {
+ return false;
+ }
+
+ return true;
+ },
+ 'ar-TN': function arTN(str) {
+ var DNI = /^\d{8}$/; // sanitize user input
+
+ var sanitized = str.trim(); // validate the data structure
+
+ if (!DNI.test(sanitized)) {
+ return false;
+ }
+
+ return true;
+ },
+ 'zh-CN': function zhCN(str) {
+ var provincesAndCities = ['11', // 北京
+ '12', // 天津
+ '13', // 河北
+ '14', // 山西
+ '15', // 内蒙古
+ '21', // 辽宁
+ '22', // 吉林
+ '23', // 黑龙江
+ '31', // 上海
+ '32', // 江苏
+ '33', // 浙江
+ '34', // 安徽
+ '35', // 福建
+ '36', // 江西
+ '37', // 山东
+ '41', // 河南
+ '42', // 湖北
+ '43', // 湖南
+ '44', // 广东
+ '45', // 广西
+ '46', // 海南
+ '50', // 重庆
+ '51', // 四川
+ '52', // 贵州
+ '53', // 云南
+ '54', // 西藏
+ '61', // 陕西
+ '62', // 甘肃
+ '63', // 青海
+ '64', // 宁夏
+ '65', // 新疆
+ '71', // 台湾
+ '81', // 香港
+ '82', // 澳门
+ '91' // 国外
+ ];
+ var powers = ['7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2'];
+ var parityBit = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
+
+ var checkAddressCode = function checkAddressCode(addressCode) {
+ return provincesAndCities.includes(addressCode);
+ };
+
+ var checkBirthDayCode = function checkBirthDayCode(birDayCode) {
+ var yyyy = parseInt(birDayCode.substring(0, 4), 10);
+ var mm = parseInt(birDayCode.substring(4, 6), 10);
+ var dd = parseInt(birDayCode.substring(6), 10);
+ var xdata = new Date(yyyy, mm - 1, dd);
+
+ if (xdata > new Date()) {
+ return false; // eslint-disable-next-line max-len
+ } else if (xdata.getFullYear() === yyyy && xdata.getMonth() === mm - 1 && xdata.getDate() === dd) {
+ return true;
+ }
+
+ return false;
+ };
+
+ var getParityBit = function getParityBit(idCardNo) {
+ var id17 = idCardNo.substring(0, 17);
+ var power = 0;
+
+ for (var i = 0; i < 17; i++) {
+ power += parseInt(id17.charAt(i), 10) * parseInt(powers[i], 10);
+ }
+
+ var mod = power % 11;
+ return parityBit[mod];
+ };
+
+ var checkParityBit = function checkParityBit(idCardNo) {
+ return getParityBit(idCardNo) === idCardNo.charAt(17).toUpperCase();
+ };
+
+ var check15IdCardNo = function check15IdCardNo(idCardNo) {
+ var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/.test(idCardNo);
+ if (!check) return false;
+ var addressCode = idCardNo.substring(0, 2);
+ check = checkAddressCode(addressCode);
+ if (!check) return false;
+ var birDayCode = "19".concat(idCardNo.substring(6, 12));
+ check = checkBirthDayCode(birDayCode);
+ if (!check) return false;
+ return true;
+ };
+
+ var check18IdCardNo = function check18IdCardNo(idCardNo) {
+ var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(idCardNo);
+ if (!check) return false;
+ var addressCode = idCardNo.substring(0, 2);
+ check = checkAddressCode(addressCode);
+ if (!check) return false;
+ var birDayCode = idCardNo.substring(6, 14);
+ check = checkBirthDayCode(birDayCode);
+ if (!check) return false;
+ return checkParityBit(idCardNo);
+ };
+
+ var checkIdCardNo = function checkIdCardNo(idCardNo) {
+ var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo);
+ if (!check) return false;
+
+ if (idCardNo.length === 15) {
+ return check15IdCardNo(idCardNo);
+ }
+
+ return check18IdCardNo(idCardNo);
+ };
+
+ return checkIdCardNo(str);
+ },
+ 'zh-HK': function zhHK(str) {
+ // sanitize user input
+ str = str.trim(); // HKID number starts with 1 or 2 letters, followed by 6 digits,
+ // then a checksum contained in square / round brackets or nothing
+
+ var regexHKID = /^[A-Z]{1,2}[0-9]{6}((\([0-9A]\))|(\[[0-9A]\])|([0-9A]))$/;
+ var regexIsDigit = /^[0-9]$/; // convert the user input to all uppercase and apply regex
+
+ str = str.toUpperCase();
+ if (!regexHKID.test(str)) return false;
+ str = str.replace(/\[|\]|\(|\)/g, '');
+ if (str.length === 8) str = "3".concat(str);
+ var checkSumVal = 0;
+
+ for (var i = 0; i <= 7; i++) {
+ var convertedChar = void 0;
+ if (!regexIsDigit.test(str[i])) convertedChar = (str[i].charCodeAt(0) - 55) % 11;else convertedChar = str[i];
+ checkSumVal += convertedChar * (9 - i);
+ }
+
+ checkSumVal %= 11;
+ var checkSumConverted;
+ if (checkSumVal === 0) checkSumConverted = '0';else if (checkSumVal === 1) checkSumConverted = 'A';else checkSumConverted = String(11 - checkSumVal);
+ if (checkSumConverted === str[str.length - 1]) return true;
+ return false;
+ },
+ 'zh-TW': function zhTW(str) {
+ var ALPHABET_CODES = {
+ A: 10,
+ B: 11,
+ C: 12,
+ D: 13,
+ E: 14,
+ F: 15,
+ G: 16,
+ H: 17,
+ I: 34,
+ J: 18,
+ K: 19,
+ L: 20,
+ M: 21,
+ N: 22,
+ O: 35,
+ P: 23,
+ Q: 24,
+ R: 25,
+ S: 26,
+ T: 27,
+ U: 28,
+ V: 29,
+ W: 32,
+ X: 30,
+ Y: 31,
+ Z: 33
+ };
+ var sanitized = str.trim().toUpperCase();
+ if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false;
+ return Array.from(sanitized).reduce(function (sum, number, index) {
+ if (index === 0) {
+ var code = ALPHABET_CODES[number];
+ return code % 10 * 9 + Math.floor(code / 10);
+ }
+
+ if (index === 9) {
+ return (10 - sum % 10 - Number(number)) % 10 === 0;
+ }
+
+ return sum + Number(number) * (9 - index);
+ }, 0);
+ }
+ };
+
+ function isIdentityCard(str, locale) {
+ (0, _assertString.default)(str);
+
+ if (locale in validators) {
+ return validators[locale](str);
+ } else if (locale === 'any') {
+ for (var key in validators) {
+ // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
+ // istanbul ignore else
+ if (validators.hasOwnProperty(key)) {
+ var validator = validators[key];
+
+ if (validator(str)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isIdentityCard, isIdentityCardExports));
+ return isIdentityCardExports;
+}
+
+var isEANExports = {};
+var isEAN = {
+ get exports(){ return isEANExports; },
+ set exports(v){ isEANExports = v; },
+};
+
+var hasRequiredIsEAN;
+
+function requireIsEAN () {
+ if (hasRequiredIsEAN) return isEANExports;
+ hasRequiredIsEAN = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isEAN;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /**
+ * The most commonly used EAN standard is
+ * the thirteen-digit EAN-13, while the
+ * less commonly used 8-digit EAN-8 barcode was
+ * introduced for use on small packages.
+ * Also EAN/UCC-14 is used for Grouping of individual
+ * trade items above unit level(Intermediate, Carton or Pallet).
+ * For more info about EAN-14 checkout: https://www.gtin.info/itf-14-barcodes/
+ * EAN consists of:
+ * GS1 prefix, manufacturer code, product code and check digit
+ * Reference: https://en.wikipedia.org/wiki/International_Article_Number
+ * Reference: https://www.gtin.info/
+ */
+
+ /**
+ * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14
+ * and Regular Expression for valid EANs (EAN-8, EAN-13, EAN-14),
+ * with exact numberic matching of 8 or 13 or 14 digits [0-9]
+ */
+ var LENGTH_EAN_8 = 8;
+ var LENGTH_EAN_14 = 14;
+ var validEanRegex = /^(\d{8}|\d{13}|\d{14})$/;
+ /**
+ * Get position weight given:
+ * EAN length and digit index/position
+ *
+ * @param {number} length
+ * @param {number} index
+ * @return {number}
+ */
+
+ function getPositionWeightThroughLengthAndIndex(length, index) {
+ if (length === LENGTH_EAN_8 || length === LENGTH_EAN_14) {
+ return index % 2 === 0 ? 3 : 1;
+ }
+
+ return index % 2 === 0 ? 1 : 3;
+ }
+ /**
+ * Calculate EAN Check Digit
+ * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit
+ *
+ * @param {string} ean
+ * @return {number}
+ */
+
+
+ function calculateCheckDigit(ean) {
+ var checksum = ean.slice(0, -1).split('').map(function (char, index) {
+ return Number(char) * getPositionWeightThroughLengthAndIndex(ean.length, index);
+ }).reduce(function (acc, partialSum) {
+ return acc + partialSum;
+ }, 0);
+ var remainder = 10 - checksum % 10;
+ return remainder < 10 ? remainder : 0;
+ }
+ /**
+ * Check if string is valid EAN:
+ * Matches EAN-8/EAN-13/EAN-14 regex
+ * Has valid check digit.
+ *
+ * @param {string} str
+ * @return {boolean}
+ */
+
+
+ function isEAN(str) {
+ (0, _assertString.default)(str);
+ var actualCheckDigit = Number(str.slice(-1));
+ return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isEAN, isEANExports));
+ return isEANExports;
+}
+
+var isISINExports = {};
+var isISIN = {
+ get exports(){ return isISINExports; },
+ set exports(v){ isISINExports = v; },
+};
+
+var hasRequiredIsISIN;
+
+function requireIsISIN () {
+ if (hasRequiredIsISIN) return isISINExports;
+ hasRequiredIsISIN = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISIN;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; // this link details how the check digit is calculated:
+ // https://www.isin.org/isin-format/. it is a little bit
+ // odd in that it works with digits, not numbers. in order
+ // to make only one pass through the ISIN characters, the
+ // each alpha character is handled as 2 characters within
+ // the loop.
+
+ function isISIN(str) {
+ (0, _assertString.default)(str);
+
+ if (!isin.test(str)) {
+ return false;
+ }
+
+ var double = true;
+ var sum = 0; // convert values
+
+ for (var i = str.length - 2; i >= 0; i--) {
+ if (str[i] >= 'A' && str[i] <= 'Z') {
+ var value = str[i].charCodeAt(0) - 55;
+ var lo = value % 10;
+ var hi = Math.trunc(value / 10); // letters have two digits, so handle the low order
+ // and high order digits separately.
+
+ for (var _i = 0, _arr = [lo, hi]; _i < _arr.length; _i++) {
+ var digit = _arr[_i];
+
+ if (double) {
+ if (digit >= 5) {
+ sum += 1 + (digit - 5) * 2;
+ } else {
+ sum += digit * 2;
+ }
+ } else {
+ sum += digit;
+ }
+
+ double = !double;
+ }
+ } else {
+ var _digit = str[i].charCodeAt(0) - '0'.charCodeAt(0);
+
+ if (double) {
+ if (_digit >= 5) {
+ sum += 1 + (_digit - 5) * 2;
+ } else {
+ sum += _digit * 2;
+ }
+ } else {
+ sum += _digit;
+ }
+
+ double = !double;
+ }
+ }
+
+ var check = Math.trunc((sum + 9) / 10) * 10 - sum;
+ return +str[str.length - 1] === check;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISIN, isISINExports));
+ return isISINExports;
+}
+
+var isISBNExports = {};
+var isISBN = {
+ get exports(){ return isISBNExports; },
+ set exports(v){ isISBNExports = v; },
+};
+
+var hasRequiredIsISBN;
+
+function requireIsISBN () {
+ if (hasRequiredIsISBN) return isISBNExports;
+ hasRequiredIsISBN = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISBN;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var possibleIsbn10 = /^(?:[0-9]{9}X|[0-9]{10})$/;
+ var possibleIsbn13 = /^(?:[0-9]{13})$/;
+ var factor = [1, 3];
+
+ function isISBN(isbn, options) {
+ (0, _assertString.default)(isbn); // For backwards compatibility:
+ // isISBN(str [, version]), i.e. `options` could be used as argument for the legacy `version`
+
+ var version = String((options === null || options === void 0 ? void 0 : options.version) || options);
+
+ if (!(options !== null && options !== void 0 && options.version || options)) {
+ return isISBN(isbn, {
+ version: 10
+ }) || isISBN(isbn, {
+ version: 13
+ });
+ }
+
+ var sanitizedIsbn = isbn.replace(/[\s-]+/g, '');
+ var checksum = 0;
+
+ if (version === '10') {
+ if (!possibleIsbn10.test(sanitizedIsbn)) {
+ return false;
+ }
+
+ for (var i = 0; i < version - 1; i++) {
+ checksum += (i + 1) * sanitizedIsbn.charAt(i);
+ }
+
+ if (sanitizedIsbn.charAt(9) === 'X') {
+ checksum += 10 * 10;
+ } else {
+ checksum += 10 * sanitizedIsbn.charAt(9);
+ }
+
+ if (checksum % 11 === 0) {
+ return true;
+ }
+ } else if (version === '13') {
+ if (!possibleIsbn13.test(sanitizedIsbn)) {
+ return false;
+ }
+
+ for (var _i = 0; _i < 12; _i++) {
+ checksum += factor[_i % 2] * sanitizedIsbn.charAt(_i);
+ }
+
+ if (sanitizedIsbn.charAt(12) - (10 - checksum % 10) % 10 === 0) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISBN, isISBNExports));
+ return isISBNExports;
+}
+
+var isISSNExports = {};
+var isISSN = {
+ get exports(){ return isISSNExports; },
+ set exports(v){ isISSNExports = v; },
+};
+
+var hasRequiredIsISSN;
+
+function requireIsISSN () {
+ if (hasRequiredIsISSN) return isISSNExports;
+ hasRequiredIsISSN = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISSN;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var issn = '^\\d{4}-?\\d{3}[\\dX]$';
+
+ function isISSN(str) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ (0, _assertString.default)(str);
+ var testIssn = issn;
+ testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn;
+ testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i');
+
+ if (!testIssn.test(str)) {
+ return false;
+ }
+
+ var digits = str.replace('-', '').toUpperCase();
+ var checksum = 0;
+
+ for (var i = 0; i < digits.length; i++) {
+ var digit = digits[i];
+ checksum += (digit === 'X' ? 10 : +digit) * (8 - i);
+ }
+
+ return checksum % 11 === 0;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISSN, isISSNExports));
+ return isISSNExports;
+}
+
+var isTaxIDExports = {};
+var isTaxID = {
+ get exports(){ return isTaxIDExports; },
+ set exports(v){ isTaxIDExports = v; },
+};
+
+var algorithms = {};
+
+var hasRequiredAlgorithms;
+
+function requireAlgorithms () {
+ if (hasRequiredAlgorithms) return algorithms;
+ hasRequiredAlgorithms = 1;
+
+ Object.defineProperty(algorithms, "__esModule", {
+ value: true
+ });
+ algorithms.iso7064Check = iso7064Check;
+ algorithms.luhnCheck = luhnCheck;
+ algorithms.reverseMultiplyAndSum = reverseMultiplyAndSum;
+ algorithms.verhoeffCheck = verhoeffCheck;
+
+ /**
+ * Algorithmic validation functions
+ * May be used as is or implemented in the workflow of other validators.
+ */
+
+ /*
+ * ISO 7064 validation function
+ * Called with a string of numbers (incl. check digit)
+ * to validate according to ISO 7064 (MOD 11, 10).
+ */
+ function iso7064Check(str) {
+ var checkvalue = 10;
+
+ for (var i = 0; i < str.length - 1; i++) {
+ checkvalue = (parseInt(str[i], 10) + checkvalue) % 10 === 0 ? 10 * 2 % 11 : (parseInt(str[i], 10) + checkvalue) % 10 * 2 % 11;
+ }
+
+ checkvalue = checkvalue === 1 ? 0 : 11 - checkvalue;
+ return checkvalue === parseInt(str[10], 10);
+ }
+ /*
+ * Luhn (mod 10) validation function
+ * Called with a string of numbers (incl. check digit)
+ * to validate according to the Luhn algorithm.
+ */
+
+
+ function luhnCheck(str) {
+ var checksum = 0;
+ var second = false;
+
+ for (var i = str.length - 1; i >= 0; i--) {
+ if (second) {
+ var product = parseInt(str[i], 10) * 2;
+
+ if (product > 9) {
+ // sum digits of product and add to checksum
+ checksum += product.toString().split('').map(function (a) {
+ return parseInt(a, 10);
+ }).reduce(function (a, b) {
+ return a + b;
+ }, 0);
+ } else {
+ checksum += product;
+ }
+ } else {
+ checksum += parseInt(str[i], 10);
+ }
+
+ second = !second;
+ }
+
+ return checksum % 10 === 0;
+ }
+ /*
+ * Reverse TIN multiplication and summation helper function
+ * Called with an array of single-digit integers and a base multiplier
+ * to calculate the sum of the digits multiplied in reverse.
+ * Normally used in variations of MOD 11 algorithmic checks.
+ */
+
+
+ function reverseMultiplyAndSum(digits, base) {
+ var total = 0;
+
+ for (var i = 0; i < digits.length; i++) {
+ total += digits[i] * (base - i);
+ }
+
+ return total;
+ }
+ /*
+ * Verhoeff validation helper function
+ * Called with a string of numbers
+ * to validate according to the Verhoeff algorithm.
+ */
+
+
+ function verhoeffCheck(str) {
+ var d_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]];
+ var p_table = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]]; // Copy (to prevent replacement) and reverse
+
+ var str_copy = str.split('').reverse().join('');
+ var checksum = 0;
+
+ for (var i = 0; i < str_copy.length; i++) {
+ checksum = d_table[checksum][p_table[i % 8][parseInt(str_copy[i], 10)]];
+ }
+
+ return checksum === 0;
+ }
+ return algorithms;
+}
+
+var hasRequiredIsTaxID;
+
+function requireIsTaxID () {
+ if (hasRequiredIsTaxID) return isTaxIDExports;
+ hasRequiredIsTaxID = 1;
+ (function (module, exports) {
+
+ 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); }
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isTaxID;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var algorithms = _interopRequireWildcard(requireAlgorithms());
+
+ var _isDate = _interopRequireDefault(requireIsDate());
+
+ function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
+
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ 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; }
+
+ /**
+ * TIN Validation
+ * Validates Tax Identification Numbers (TINs) from the US, EU member states and the United Kingdom.
+ *
+ * EU-UK:
+ * National TIN validity is calculated using public algorithms as made available by DG TAXUD.
+ *
+ * See `https://ec.europa.eu/taxation_customs/tin/specs/FS-TIN%20Algorithms-Public.docx` for more information.
+ *
+ * US:
+ * An Employer Identification Number (EIN), also known as a Federal Tax Identification Number,
+ * is used to identify a business entity.
+ *
+ * NOTES:
+ * - Prefix 47 is being reserved for future use
+ * - Prefixes 26, 27, 45, 46 and 47 were previously assigned by the Philadelphia campus.
+ *
+ * See `http://www.irs.gov/Businesses/Small-Businesses-&-Self-Employed/How-EINs-are-Assigned-and-Valid-EIN-Prefixes`
+ * for more information.
+ */
+ // Locale functions
+
+ /*
+ * bg-BG validation function
+ * (Edinen graždanski nomer (EGN/ЕГН), persons only)
+ * Checks if birth date (first six digits) is valid and calculates check (last) digit
+ */
+ function bgBgCheck(tin) {
+ // Extract full year, normalize month and check birth date validity
+ var century_year = tin.slice(0, 2);
+ var month = parseInt(tin.slice(2, 4), 10);
+
+ if (month > 40) {
+ month -= 40;
+ century_year = "20".concat(century_year);
+ } else if (month > 20) {
+ month -= 20;
+ century_year = "18".concat(century_year);
+ } else {
+ century_year = "19".concat(century_year);
+ }
+
+ if (month < 10) {
+ month = "0".concat(month);
+ }
+
+ var date = "".concat(century_year, "/").concat(month, "/").concat(tin.slice(4, 6));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // split digits into an array for further processing
+
+
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ }); // Calculate checksum by multiplying digits with fixed values
+
+ var multip_lookup = [2, 4, 8, 5, 10, 9, 7, 3, 6];
+ var checksum = 0;
+
+ for (var i = 0; i < multip_lookup.length; i++) {
+ checksum += digits[i] * multip_lookup[i];
+ }
+
+ checksum = checksum % 11 === 10 ? 0 : checksum % 11;
+ return checksum === digits[9];
+ }
+ /**
+ * Check if an input is a valid Canadian SIN (Social Insurance Number)
+ *
+ * The Social Insurance Number (SIN) is a 9 digit number that
+ * you need to work in Canada or to have access to government programs and benefits.
+ *
+ * https://en.wikipedia.org/wiki/Social_Insurance_Number
+ * https://www.canada.ca/en/employment-social-development/services/sin.html
+ * https://www.codercrunch.com/challenge/819302488/sin-validator
+ *
+ * @param {string} input
+ * @return {boolean}
+ */
+
+
+ function isCanadianSIN(input) {
+ var digitsArray = input.split('');
+ var even = digitsArray.filter(function (_, idx) {
+ return idx % 2;
+ }).map(function (i) {
+ return Number(i) * 2;
+ }).join('').split('');
+ var total = digitsArray.filter(function (_, idx) {
+ return !(idx % 2);
+ }).concat(even).map(function (i) {
+ return Number(i);
+ }).reduce(function (acc, cur) {
+ return acc + cur;
+ });
+ return total % 10 === 0;
+ }
+ /*
+ * cs-CZ validation function
+ * (Rodné číslo (RČ), persons only)
+ * Checks if birth date (first six digits) is valid and divisibility by 11
+ * Material not in DG TAXUD document sourced from:
+ * -`https://lorenc.info/3MA381/overeni-spravnosti-rodneho-cisla.htm`
+ * -`https://www.mvcr.cz/clanek/rady-a-sluzby-dokumenty-rodne-cislo.aspx`
+ */
+
+
+ function csCzCheck(tin) {
+ tin = tin.replace(/\W/, ''); // Extract full year from TIN length
+
+ var full_year = parseInt(tin.slice(0, 2), 10);
+
+ if (tin.length === 10) {
+ if (full_year < 54) {
+ full_year = "20".concat(full_year);
+ } else {
+ full_year = "19".concat(full_year);
+ }
+ } else {
+ if (tin.slice(6) === '000') {
+ return false;
+ } // Three-zero serial not assigned before 1954
+
+
+ if (full_year < 54) {
+ full_year = "19".concat(full_year);
+ } else {
+ return false; // No 18XX years seen in any of the resources
+ }
+ } // Add missing zero if needed
+
+
+ if (full_year.length === 3) {
+ full_year = [full_year.slice(0, 2), '0', full_year.slice(2)].join('');
+ } // Extract month from TIN and normalize
+
+
+ var month = parseInt(tin.slice(2, 4), 10);
+
+ if (month > 50) {
+ month -= 50;
+ }
+
+ if (month > 20) {
+ // Month-plus-twenty was only introduced in 2004
+ if (parseInt(full_year, 10) < 2004) {
+ return false;
+ }
+
+ month -= 20;
+ }
+
+ if (month < 10) {
+ month = "0".concat(month);
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Verify divisibility by 11
+
+
+ if (tin.length === 10) {
+ if (parseInt(tin, 10) % 11 !== 0) {
+ // Some numbers up to and including 1985 are still valid if
+ // check (last) digit equals 0 and modulo of first 9 digits equals 10
+ var checkdigit = parseInt(tin.slice(0, 9), 10) % 11;
+
+ if (parseInt(full_year, 10) < 1986 && checkdigit === 10) {
+ if (parseInt(tin.slice(9), 10) !== 0) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+ /*
+ * de-AT validation function
+ * (Abgabenkontonummer, persons/entities)
+ * Verify TIN validity by calling luhnCheck()
+ */
+
+
+ function deAtCheck(tin) {
+ return algorithms.luhnCheck(tin);
+ }
+ /*
+ * de-DE validation function
+ * (Steueridentifikationsnummer (Steuer-IdNr.), persons only)
+ * Tests for single duplicate/triplicate value, then calculates ISO 7064 check (last) digit
+ * Partial implementation of spec (same result with both algorithms always)
+ */
+
+
+ function deDeCheck(tin) {
+ // Split digits into an array for further processing
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ }); // Fill array with strings of number positions
+
+ var occurences = [];
+
+ for (var i = 0; i < digits.length - 1; i++) {
+ occurences.push('');
+
+ for (var j = 0; j < digits.length - 1; j++) {
+ if (digits[i] === digits[j]) {
+ occurences[i] += j;
+ }
+ }
+ } // Remove digits with one occurence and test for only one duplicate/triplicate
+
+
+ occurences = occurences.filter(function (a) {
+ return a.length > 1;
+ });
+
+ if (occurences.length !== 2 && occurences.length !== 3) {
+ return false;
+ } // In case of triplicate value only two digits are allowed next to each other
+
+
+ if (occurences[0].length === 3) {
+ var trip_locations = occurences[0].split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var recurrent = 0; // Amount of neighbour occurences
+
+ for (var _i = 0; _i < trip_locations.length - 1; _i++) {
+ if (trip_locations[_i] + 1 === trip_locations[_i + 1]) {
+ recurrent += 1;
+ }
+ }
+
+ if (recurrent === 2) {
+ return false;
+ }
+ }
+
+ return algorithms.iso7064Check(tin);
+ }
+ /*
+ * dk-DK validation function
+ * (CPR-nummer (personnummer), persons only)
+ * Checks if birth date (first six digits) is valid and assigned to century (seventh) digit,
+ * and calculates check (last) digit
+ */
+
+
+ function dkDkCheck(tin) {
+ tin = tin.replace(/\W/, ''); // Extract year, check if valid for given century digit and add century
+
+ var year = parseInt(tin.slice(4, 6), 10);
+ var century_digit = tin.slice(6, 7);
+
+ switch (century_digit) {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ year = "19".concat(year);
+ break;
+
+ case '4':
+ case '9':
+ if (year < 37) {
+ year = "20".concat(year);
+ } else {
+ year = "19".concat(year);
+ }
+
+ break;
+
+ default:
+ if (year < 37) {
+ year = "20".concat(year);
+ } else if (year > 58) {
+ year = "18".concat(year);
+ } else {
+ return false;
+ }
+
+ break;
+ } // Add missing zero if needed
+
+
+ if (year.length === 3) {
+ year = [year.slice(0, 2), '0', year.slice(2)].join('');
+ } // Check date validity
+
+
+ var date = "".concat(year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Split digits into an array for further processing
+
+
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var checksum = 0;
+ var weight = 4; // Multiply by weight and add to checksum
+
+ for (var i = 0; i < 9; i++) {
+ checksum += digits[i] * weight;
+ weight -= 1;
+
+ if (weight === 1) {
+ weight = 7;
+ }
+ }
+
+ checksum %= 11;
+
+ if (checksum === 1) {
+ return false;
+ }
+
+ return checksum === 0 ? digits[9] === 0 : digits[9] === 11 - checksum;
+ }
+ /*
+ * el-CY validation function
+ * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons only)
+ * Verify TIN validity by calculating ASCII value of check (last) character
+ */
+
+
+ function elCyCheck(tin) {
+ // split digits into an array for further processing
+ var digits = tin.slice(0, 8).split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var checksum = 0; // add digits in even places
+
+ for (var i = 1; i < digits.length; i += 2) {
+ checksum += digits[i];
+ } // add digits in odd places
+
+
+ for (var _i2 = 0; _i2 < digits.length; _i2 += 2) {
+ if (digits[_i2] < 2) {
+ checksum += 1 - digits[_i2];
+ } else {
+ checksum += 2 * (digits[_i2] - 2) + 5;
+
+ if (digits[_i2] > 4) {
+ checksum += 2;
+ }
+ }
+ }
+
+ return String.fromCharCode(checksum % 26 + 65) === tin.charAt(8);
+ }
+ /*
+ * el-GR validation function
+ * (Arithmos Forologikou Mitroou (AFM/ΑΦΜ), persons/entities)
+ * Verify TIN validity by calculating check (last) digit
+ * Algorithm not in DG TAXUD document- sourced from:
+ * - `http://epixeirisi.gr/%CE%9A%CE%A1%CE%99%CE%A3%CE%99%CE%9C%CE%91-%CE%98%CE%95%CE%9C%CE%91%CE%A4%CE%91-%CE%A6%CE%9F%CE%A1%CE%9F%CE%9B%CE%9F%CE%93%CE%99%CE%91%CE%A3-%CE%9A%CE%91%CE%99-%CE%9B%CE%9F%CE%93%CE%99%CE%A3%CE%A4%CE%99%CE%9A%CE%97%CE%A3/23791/%CE%91%CF%81%CE%B9%CE%B8%CE%BC%CF%8C%CF%82-%CE%A6%CE%BF%CF%81%CE%BF%CE%BB%CE%BF%CE%B3%CE%B9%CE%BA%CE%BF%CF%8D-%CE%9C%CE%B7%CF%84%CF%81%CF%8E%CE%BF%CF%85`
+ */
+
+
+ function elGrCheck(tin) {
+ // split digits into an array for further processing
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var checksum = 0;
+
+ for (var i = 0; i < 8; i++) {
+ checksum += digits[i] * Math.pow(2, 8 - i);
+ }
+
+ return checksum % 11 % 10 === digits[8];
+ }
+ /*
+ * en-GB validation function (should go here if needed)
+ * (National Insurance Number (NINO) or Unique Taxpayer Reference (UTR),
+ * persons/entities respectively)
+ */
+
+ /*
+ * en-IE validation function
+ * (Personal Public Service Number (PPS No), persons only)
+ * Verify TIN validity by calculating check (second to last) character
+ */
+
+
+ function enIeCheck(tin) {
+ var checksum = algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) {
+ return parseInt(a, 10);
+ }), 8);
+
+ if (tin.length === 9 && tin[8] !== 'W') {
+ checksum += (tin[8].charCodeAt(0) - 64) * 9;
+ }
+
+ checksum %= 23;
+
+ if (checksum === 0) {
+ return tin[7].toUpperCase() === 'W';
+ }
+
+ return tin[7].toUpperCase() === String.fromCharCode(64 + checksum);
+ } // Valid US IRS campus prefixes
+
+
+ var enUsCampusPrefix = {
+ andover: ['10', '12'],
+ atlanta: ['60', '67'],
+ austin: ['50', '53'],
+ brookhaven: ['01', '02', '03', '04', '05', '06', '11', '13', '14', '16', '21', '22', '23', '25', '34', '51', '52', '54', '55', '56', '57', '58', '59', '65'],
+ cincinnati: ['30', '32', '35', '36', '37', '38', '61'],
+ fresno: ['15', '24'],
+ internet: ['20', '26', '27', '45', '46', '47'],
+ kansas: ['40', '44'],
+ memphis: ['94', '95'],
+ ogden: ['80', '90'],
+ philadelphia: ['33', '39', '41', '42', '43', '46', '48', '62', '63', '64', '66', '68', '71', '72', '73', '74', '75', '76', '77', '81', '82', '83', '84', '85', '86', '87', '88', '91', '92', '93', '98', '99'],
+ sba: ['31']
+ }; // Return an array of all US IRS campus prefixes
+
+ function enUsGetPrefixes() {
+ var prefixes = [];
+
+ for (var location in enUsCampusPrefix) {
+ // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
+ // istanbul ignore else
+ if (enUsCampusPrefix.hasOwnProperty(location)) {
+ prefixes.push.apply(prefixes, _toConsumableArray(enUsCampusPrefix[location]));
+ }
+ }
+
+ return prefixes;
+ }
+ /*
+ * en-US validation function
+ * Verify that the TIN starts with a valid IRS campus prefix
+ */
+
+
+ function enUsCheck(tin) {
+ return enUsGetPrefixes().indexOf(tin.slice(0, 2)) !== -1;
+ }
+ /*
+ * es-ES validation function
+ * (Documento Nacional de Identidad (DNI)
+ * or Número de Identificación de Extranjero (NIE), persons only)
+ * Verify TIN validity by calculating check (last) character
+ */
+
+
+ function esEsCheck(tin) {
+ // Split characters into an array for further processing
+ var chars = tin.toUpperCase().split(''); // Replace initial letter if needed
+
+ if (isNaN(parseInt(chars[0], 10)) && chars.length > 1) {
+ var lead_replace = 0;
+
+ switch (chars[0]) {
+ case 'Y':
+ lead_replace = 1;
+ break;
+
+ case 'Z':
+ lead_replace = 2;
+ break;
+ }
+
+ chars.splice(0, 1, lead_replace); // Fill with zeros if smaller than proper
+ } else {
+ while (chars.length < 9) {
+ chars.unshift(0);
+ }
+ } // Calculate checksum and check according to lookup
+
+
+ var lookup = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E'];
+ chars = chars.join('');
+ var checksum = parseInt(chars.slice(0, 8), 10) % 23;
+ return chars[8] === lookup[checksum];
+ }
+ /*
+ * et-EE validation function
+ * (Isikukood (IK), persons only)
+ * Checks if birth date (century digit and six following) is valid and calculates check (last) digit
+ * Material not in DG TAXUD document sourced from:
+ * - `https://www.oecd.org/tax/automatic-exchange/crs-implementation-and-assistance/tax-identification-numbers/Estonia-TIN.pdf`
+ */
+
+
+ function etEeCheck(tin) {
+ // Extract year and add century
+ var full_year = tin.slice(1, 3);
+ var century_digit = tin.slice(0, 1);
+
+ switch (century_digit) {
+ case '1':
+ case '2':
+ full_year = "18".concat(full_year);
+ break;
+
+ case '3':
+ case '4':
+ full_year = "19".concat(full_year);
+ break;
+
+ default:
+ full_year = "20".concat(full_year);
+ break;
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Split digits into an array for further processing
+
+
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var checksum = 0;
+ var weight = 1; // Multiply by weight and add to checksum
+
+ for (var i = 0; i < 10; i++) {
+ checksum += digits[i] * weight;
+ weight += 1;
+
+ if (weight === 10) {
+ weight = 1;
+ }
+ } // Do again if modulo 11 of checksum is 10
+
+
+ if (checksum % 11 === 10) {
+ checksum = 0;
+ weight = 3;
+
+ for (var _i3 = 0; _i3 < 10; _i3++) {
+ checksum += digits[_i3] * weight;
+ weight += 1;
+
+ if (weight === 10) {
+ weight = 1;
+ }
+ }
+
+ if (checksum % 11 === 10) {
+ return digits[10] === 0;
+ }
+ }
+
+ return checksum % 11 === digits[10];
+ }
+ /*
+ * fi-FI validation function
+ * (Henkilötunnus (HETU), persons only)
+ * Checks if birth date (first six digits plus century symbol) is valid
+ * and calculates check (last) digit
+ */
+
+
+ function fiFiCheck(tin) {
+ // Extract year and add century
+ var full_year = tin.slice(4, 6);
+ var century_symbol = tin.slice(6, 7);
+
+ switch (century_symbol) {
+ case '+':
+ full_year = "18".concat(full_year);
+ break;
+
+ case '-':
+ full_year = "19".concat(full_year);
+ break;
+
+ default:
+ full_year = "20".concat(full_year);
+ break;
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(tin.slice(0, 2));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Calculate check character
+
+
+ var checksum = parseInt(tin.slice(0, 6) + tin.slice(7, 10), 10) % 31;
+
+ if (checksum < 10) {
+ return checksum === parseInt(tin.slice(10), 10);
+ }
+
+ checksum -= 10;
+ var letters_lookup = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'];
+ return letters_lookup[checksum] === tin.slice(10);
+ }
+ /*
+ * fr/nl-BE validation function
+ * (Numéro national (N.N.), persons only)
+ * Checks if birth date (first six digits) is valid and calculates check (last two) digits
+ */
+
+
+ function frBeCheck(tin) {
+ // Zero month/day value is acceptable
+ if (tin.slice(2, 4) !== '00' || tin.slice(4, 6) !== '00') {
+ // Extract date from first six digits of TIN
+ var date = "".concat(tin.slice(0, 2), "/").concat(tin.slice(2, 4), "/").concat(tin.slice(4, 6));
+
+ if (!(0, _isDate.default)(date, 'YY/MM/DD')) {
+ return false;
+ }
+ }
+
+ var checksum = 97 - parseInt(tin.slice(0, 9), 10) % 97;
+ var checkdigits = parseInt(tin.slice(9, 11), 10);
+
+ if (checksum !== checkdigits) {
+ checksum = 97 - parseInt("2".concat(tin.slice(0, 9)), 10) % 97;
+
+ if (checksum !== checkdigits) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ /*
+ * fr-FR validation function
+ * (Numéro fiscal de référence (numéro SPI), persons only)
+ * Verify TIN validity by calculating check (last three) digits
+ */
+
+
+ function frFrCheck(tin) {
+ tin = tin.replace(/\s/g, '');
+ var checksum = parseInt(tin.slice(0, 10), 10) % 511;
+ var checkdigits = parseInt(tin.slice(10, 13), 10);
+ return checksum === checkdigits;
+ }
+ /*
+ * fr/lb-LU validation function
+ * (numéro d’identification personnelle, persons only)
+ * Verify birth date validity and run Luhn and Verhoeff checks
+ */
+
+
+ function frLuCheck(tin) {
+ // Extract date and check validity
+ var date = "".concat(tin.slice(0, 4), "/").concat(tin.slice(4, 6), "/").concat(tin.slice(6, 8));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Run Luhn check
+
+
+ if (!algorithms.luhnCheck(tin.slice(0, 12))) {
+ return false;
+ } // Remove Luhn check digit and run Verhoeff check
+
+
+ return algorithms.verhoeffCheck("".concat(tin.slice(0, 11)).concat(tin[12]));
+ }
+ /*
+ * hr-HR validation function
+ * (Osobni identifikacijski broj (OIB), persons/entities)
+ * Verify TIN validity by calling iso7064Check(digits)
+ */
+
+
+ function hrHrCheck(tin) {
+ return algorithms.iso7064Check(tin);
+ }
+ /*
+ * hu-HU validation function
+ * (Adóazonosító jel, persons only)
+ * Verify TIN validity by calculating check (last) digit
+ */
+
+
+ function huHuCheck(tin) {
+ // split digits into an array for further processing
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var checksum = 8;
+
+ for (var i = 1; i < 9; i++) {
+ checksum += digits[i] * (i + 1);
+ }
+
+ return checksum % 11 === digits[9];
+ }
+ /*
+ * lt-LT validation function (should go here if needed)
+ * (Asmens kodas, persons/entities respectively)
+ * Current validation check is alias of etEeCheck- same format applies
+ */
+
+ /*
+ * it-IT first/last name validity check
+ * Accepts it-IT TIN-encoded names as a three-element character array and checks their validity
+ * Due to lack of clarity between resources ("Are only Italian consonants used?
+ * What happens if a person has X in their name?" etc.) only two test conditions
+ * have been implemented:
+ * Vowels may only be followed by other vowels or an X character
+ * and X characters after vowels may only be followed by other X characters.
+ */
+
+
+ function itItNameCheck(name) {
+ // true at the first occurence of a vowel
+ var vowelflag = false; // true at the first occurence of an X AFTER vowel
+ // (to properly handle last names with X as consonant)
+
+ var xflag = false;
+
+ for (var i = 0; i < 3; i++) {
+ if (!vowelflag && /[AEIOU]/.test(name[i])) {
+ vowelflag = true;
+ } else if (!xflag && vowelflag && name[i] === 'X') {
+ xflag = true;
+ } else if (i > 0) {
+ if (vowelflag && !xflag) {
+ if (!/[AEIOU]/.test(name[i])) {
+ return false;
+ }
+ }
+
+ if (xflag) {
+ if (!/X/.test(name[i])) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+ /*
+ * it-IT validation function
+ * (Codice fiscale (TIN-IT), persons only)
+ * Verify name, birth date and codice catastale validity
+ * and calculate check character.
+ * Material not in DG-TAXUD document sourced from:
+ * `https://en.wikipedia.org/wiki/Italian_fiscal_code`
+ */
+
+
+ function itItCheck(tin) {
+ // Capitalize and split characters into an array for further processing
+ var chars = tin.toUpperCase().split(''); // Check first and last name validity calling itItNameCheck()
+
+ if (!itItNameCheck(chars.slice(0, 3))) {
+ return false;
+ }
+
+ if (!itItNameCheck(chars.slice(3, 6))) {
+ return false;
+ } // Convert letters in number spaces back to numbers if any
+
+
+ var number_locations = [6, 7, 9, 10, 12, 13, 14];
+ var number_replace = {
+ L: '0',
+ M: '1',
+ N: '2',
+ P: '3',
+ Q: '4',
+ R: '5',
+ S: '6',
+ T: '7',
+ U: '8',
+ V: '9'
+ };
+
+ for (var _i4 = 0, _number_locations = number_locations; _i4 < _number_locations.length; _i4++) {
+ var i = _number_locations[_i4];
+
+ if (chars[i] in number_replace) {
+ chars.splice(i, 1, number_replace[chars[i]]);
+ }
+ } // Extract month and day, and check date validity
+
+
+ var month_replace = {
+ A: '01',
+ B: '02',
+ C: '03',
+ D: '04',
+ E: '05',
+ H: '06',
+ L: '07',
+ M: '08',
+ P: '09',
+ R: '10',
+ S: '11',
+ T: '12'
+ };
+ var month = month_replace[chars[8]];
+ var day = parseInt(chars[9] + chars[10], 10);
+
+ if (day > 40) {
+ day -= 40;
+ }
+
+ if (day < 10) {
+ day = "0".concat(day);
+ }
+
+ var date = "".concat(chars[6]).concat(chars[7], "/").concat(month, "/").concat(day);
+
+ if (!(0, _isDate.default)(date, 'YY/MM/DD')) {
+ return false;
+ } // Calculate check character by adding up even and odd characters as numbers
+
+
+ var checksum = 0;
+
+ for (var _i5 = 1; _i5 < chars.length - 1; _i5 += 2) {
+ var char_to_int = parseInt(chars[_i5], 10);
+
+ if (isNaN(char_to_int)) {
+ char_to_int = chars[_i5].charCodeAt(0) - 65;
+ }
+
+ checksum += char_to_int;
+ }
+
+ var odd_convert = {
+ // Maps of characters at odd places
+ A: 1,
+ B: 0,
+ C: 5,
+ D: 7,
+ E: 9,
+ F: 13,
+ G: 15,
+ H: 17,
+ I: 19,
+ J: 21,
+ K: 2,
+ L: 4,
+ M: 18,
+ N: 20,
+ O: 11,
+ P: 3,
+ Q: 6,
+ R: 8,
+ S: 12,
+ T: 14,
+ U: 16,
+ V: 10,
+ W: 22,
+ X: 25,
+ Y: 24,
+ Z: 23,
+ 0: 1,
+ 1: 0
+ };
+
+ for (var _i6 = 0; _i6 < chars.length - 1; _i6 += 2) {
+ var _char_to_int = 0;
+
+ if (chars[_i6] in odd_convert) {
+ _char_to_int = odd_convert[chars[_i6]];
+ } else {
+ var multiplier = parseInt(chars[_i6], 10);
+ _char_to_int = 2 * multiplier + 1;
+
+ if (multiplier > 4) {
+ _char_to_int += 2;
+ }
+ }
+
+ checksum += _char_to_int;
+ }
+
+ if (String.fromCharCode(65 + checksum % 26) !== chars[15]) {
+ return false;
+ }
+
+ return true;
+ }
+ /*
+ * lv-LV validation function
+ * (Personas kods (PK), persons only)
+ * Check validity of birth date and calculate check (last) digit
+ * Support only for old format numbers (not starting with '32', issued before 2017/07/01)
+ * Material not in DG TAXUD document sourced from:
+ * `https://boot.ritakafija.lv/forums/index.php?/topic/88314-personas-koda-algoritms-%C4%8Deksumma/`
+ */
+
+
+ function lvLvCheck(tin) {
+ tin = tin.replace(/\W/, ''); // Extract date from TIN
+
+ var day = tin.slice(0, 2);
+
+ if (day !== '32') {
+ // No date/checksum check if new format
+ var month = tin.slice(2, 4);
+
+ if (month !== '00') {
+ // No date check if unknown month
+ var full_year = tin.slice(4, 6);
+
+ switch (tin[6]) {
+ case '0':
+ full_year = "18".concat(full_year);
+ break;
+
+ case '1':
+ full_year = "19".concat(full_year);
+ break;
+
+ default:
+ full_year = "20".concat(full_year);
+ break;
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(tin.slice(2, 4), "/").concat(day);
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ }
+ } // Calculate check digit
+
+
+ var checksum = 1101;
+ var multip_lookup = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
+
+ for (var i = 0; i < tin.length - 1; i++) {
+ checksum -= parseInt(tin[i], 10) * multip_lookup[i];
+ }
+
+ return parseInt(tin[10], 10) === checksum % 11;
+ }
+
+ return true;
+ }
+ /*
+ * mt-MT validation function
+ * (Identity Card Number or Unique Taxpayer Reference, persons/entities)
+ * Verify Identity Card Number structure (no other tests found)
+ */
+
+
+ function mtMtCheck(tin) {
+ if (tin.length !== 9) {
+ // No tests for UTR
+ var chars = tin.toUpperCase().split(''); // Fill with zeros if smaller than proper
+
+ while (chars.length < 8) {
+ chars.unshift(0);
+ } // Validate format according to last character
+
+
+ switch (tin[7]) {
+ case 'A':
+ case 'P':
+ if (parseInt(chars[6], 10) === 0) {
+ return false;
+ }
+
+ break;
+
+ default:
+ {
+ var first_part = parseInt(chars.join('').slice(0, 5), 10);
+
+ if (first_part > 32000) {
+ return false;
+ }
+
+ var second_part = parseInt(chars.join('').slice(5, 7), 10);
+
+ if (first_part === second_part) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+ /*
+ * nl-NL validation function
+ * (Burgerservicenummer (BSN) or Rechtspersonen Samenwerkingsverbanden Informatie Nummer (RSIN),
+ * persons/entities respectively)
+ * Verify TIN validity by calculating check (last) digit (variant of MOD 11)
+ */
+
+
+ function nlNlCheck(tin) {
+ return algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) {
+ return parseInt(a, 10);
+ }), 9) % 11 === parseInt(tin[8], 10);
+ }
+ /*
+ * pl-PL validation function
+ * (Powszechny Elektroniczny System Ewidencji Ludności (PESEL)
+ * or Numer identyfikacji podatkowej (NIP), persons/entities)
+ * Verify TIN validity by validating birth date (PESEL) and calculating check (last) digit
+ */
+
+
+ function plPlCheck(tin) {
+ // NIP
+ if (tin.length === 10) {
+ // Calculate last digit by multiplying with lookup
+ var lookup = [6, 5, 7, 2, 3, 4, 5, 6, 7];
+ var _checksum = 0;
+
+ for (var i = 0; i < lookup.length; i++) {
+ _checksum += parseInt(tin[i], 10) * lookup[i];
+ }
+
+ _checksum %= 11;
+
+ if (_checksum === 10) {
+ return false;
+ }
+
+ return _checksum === parseInt(tin[9], 10);
+ } // PESEL
+ // Extract full year using month
+
+
+ var full_year = tin.slice(0, 2);
+ var month = parseInt(tin.slice(2, 4), 10);
+
+ if (month > 80) {
+ full_year = "18".concat(full_year);
+ month -= 80;
+ } else if (month > 60) {
+ full_year = "22".concat(full_year);
+ month -= 60;
+ } else if (month > 40) {
+ full_year = "21".concat(full_year);
+ month -= 40;
+ } else if (month > 20) {
+ full_year = "20".concat(full_year);
+ month -= 20;
+ } else {
+ full_year = "19".concat(full_year);
+ } // Add leading zero to month if needed
+
+
+ if (month < 10) {
+ month = "0".concat(month);
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Calculate last digit by mulitplying with odd one-digit numbers except 5
+
+
+ var checksum = 0;
+ var multiplier = 1;
+
+ for (var _i7 = 0; _i7 < tin.length - 1; _i7++) {
+ checksum += parseInt(tin[_i7], 10) * multiplier % 10;
+ multiplier += 2;
+
+ if (multiplier > 10) {
+ multiplier = 1;
+ } else if (multiplier === 5) {
+ multiplier += 2;
+ }
+ }
+
+ checksum = 10 - checksum % 10;
+ return checksum === parseInt(tin[10], 10);
+ }
+ /*
+ * pt-BR validation function
+ * (Cadastro de Pessoas Físicas (CPF, persons)
+ * Cadastro Nacional de Pessoas Jurídicas (CNPJ, entities)
+ * Both inputs will be validated
+ */
+
+
+ function ptBrCheck(tin) {
+ if (tin.length === 11) {
+ var _sum;
+
+ var remainder;
+ _sum = 0;
+ if ( // Reject known invalid CPFs
+ tin === '11111111111' || tin === '22222222222' || tin === '33333333333' || tin === '44444444444' || tin === '55555555555' || tin === '66666666666' || tin === '77777777777' || tin === '88888888888' || tin === '99999999999' || tin === '00000000000') return false;
+
+ for (var i = 1; i <= 9; i++) {
+ _sum += parseInt(tin.substring(i - 1, i), 10) * (11 - i);
+ }
+
+ remainder = _sum * 10 % 11;
+ if (remainder === 10) remainder = 0;
+ if (remainder !== parseInt(tin.substring(9, 10), 10)) return false;
+ _sum = 0;
+
+ for (var _i8 = 1; _i8 <= 10; _i8++) {
+ _sum += parseInt(tin.substring(_i8 - 1, _i8), 10) * (12 - _i8);
+ }
+
+ remainder = _sum * 10 % 11;
+ if (remainder === 10) remainder = 0;
+ if (remainder !== parseInt(tin.substring(10, 11), 10)) return false;
+ return true;
+ }
+
+ if ( // Reject know invalid CNPJs
+ tin === '00000000000000' || tin === '11111111111111' || tin === '22222222222222' || tin === '33333333333333' || tin === '44444444444444' || tin === '55555555555555' || tin === '66666666666666' || tin === '77777777777777' || tin === '88888888888888' || tin === '99999999999999') {
+ return false;
+ }
+
+ var length = tin.length - 2;
+ var identifiers = tin.substring(0, length);
+ var verificators = tin.substring(length);
+ var sum = 0;
+ var pos = length - 7;
+
+ for (var _i9 = length; _i9 >= 1; _i9--) {
+ sum += identifiers.charAt(length - _i9) * pos;
+ pos -= 1;
+
+ if (pos < 2) {
+ pos = 9;
+ }
+ }
+
+ var result = sum % 11 < 2 ? 0 : 11 - sum % 11;
+
+ if (result !== parseInt(verificators.charAt(0), 10)) {
+ return false;
+ }
+
+ length += 1;
+ identifiers = tin.substring(0, length);
+ sum = 0;
+ pos = length - 7;
+
+ for (var _i10 = length; _i10 >= 1; _i10--) {
+ sum += identifiers.charAt(length - _i10) * pos;
+ pos -= 1;
+
+ if (pos < 2) {
+ pos = 9;
+ }
+ }
+
+ result = sum % 11 < 2 ? 0 : 11 - sum % 11;
+
+ if (result !== parseInt(verificators.charAt(1), 10)) {
+ return false;
+ }
+
+ return true;
+ }
+ /*
+ * pt-PT validation function
+ * (Número de identificação fiscal (NIF), persons/entities)
+ * Verify TIN validity by calculating check (last) digit (variant of MOD 11)
+ */
+
+
+ function ptPtCheck(tin) {
+ var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) {
+ return parseInt(a, 10);
+ }), 9) % 11;
+
+ if (checksum > 9) {
+ return parseInt(tin[8], 10) === 0;
+ }
+
+ return checksum === parseInt(tin[8], 10);
+ }
+ /*
+ * ro-RO validation function
+ * (Cod Numeric Personal (CNP) or Cod de înregistrare fiscală (CIF),
+ * persons only)
+ * Verify CNP validity by calculating check (last) digit (test not found for CIF)
+ * Material not in DG TAXUD document sourced from:
+ * `https://en.wikipedia.org/wiki/National_identification_number#Romania`
+ */
+
+
+ function roRoCheck(tin) {
+ if (tin.slice(0, 4) !== '9000') {
+ // No test found for this format
+ // Extract full year using century digit if possible
+ var full_year = tin.slice(1, 3);
+
+ switch (tin[0]) {
+ case '1':
+ case '2':
+ full_year = "19".concat(full_year);
+ break;
+
+ case '3':
+ case '4':
+ full_year = "18".concat(full_year);
+ break;
+
+ case '5':
+ case '6':
+ full_year = "20".concat(full_year);
+ break;
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(tin.slice(3, 5), "/").concat(tin.slice(5, 7));
+
+ if (date.length === 8) {
+ if (!(0, _isDate.default)(date, 'YY/MM/DD')) {
+ return false;
+ }
+ } else if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ } // Calculate check digit
+
+
+ var digits = tin.split('').map(function (a) {
+ return parseInt(a, 10);
+ });
+ var multipliers = [2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9];
+ var checksum = 0;
+
+ for (var i = 0; i < multipliers.length; i++) {
+ checksum += digits[i] * multipliers[i];
+ }
+
+ if (checksum % 11 === 10) {
+ return digits[12] === 1;
+ }
+
+ return digits[12] === checksum % 11;
+ }
+
+ return true;
+ }
+ /*
+ * sk-SK validation function
+ * (Rodné číslo (RČ) or bezvýznamové identifikačné číslo (BIČ), persons only)
+ * Checks validity of pre-1954 birth numbers (rodné číslo) only
+ * Due to the introduction of the pseudo-random BIČ it is not possible to test
+ * post-1954 birth numbers without knowing whether they are BIČ or RČ beforehand
+ */
+
+
+ function skSkCheck(tin) {
+ if (tin.length === 9) {
+ tin = tin.replace(/\W/, '');
+
+ if (tin.slice(6) === '000') {
+ return false;
+ } // Three-zero serial not assigned before 1954
+ // Extract full year from TIN length
+
+
+ var full_year = parseInt(tin.slice(0, 2), 10);
+
+ if (full_year > 53) {
+ return false;
+ }
+
+ if (full_year < 10) {
+ full_year = "190".concat(full_year);
+ } else {
+ full_year = "19".concat(full_year);
+ } // Extract month from TIN and normalize
+
+
+ var month = parseInt(tin.slice(2, 4), 10);
+
+ if (month > 50) {
+ month -= 50;
+ }
+
+ if (month < 10) {
+ month = "0".concat(month);
+ } // Check date validity
+
+
+ var date = "".concat(full_year, "/").concat(month, "/").concat(tin.slice(4, 6));
+
+ if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ /*
+ * sl-SI validation function
+ * (Davčna številka, persons/entities)
+ * Verify TIN validity by calculating check (last) digit (variant of MOD 11)
+ */
+
+
+ function slSiCheck(tin) {
+ var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 7).map(function (a) {
+ return parseInt(a, 10);
+ }), 8) % 11;
+
+ if (checksum === 10) {
+ return parseInt(tin[7], 10) === 0;
+ }
+
+ return checksum === parseInt(tin[7], 10);
+ }
+ /*
+ * sv-SE validation function
+ * (Personnummer or samordningsnummer, persons only)
+ * Checks validity of birth date and calls luhnCheck() to validate check (last) digit
+ */
+
+
+ function svSeCheck(tin) {
+ // Make copy of TIN and normalize to two-digit year form
+ var tin_copy = tin.slice(0);
+
+ if (tin.length > 11) {
+ tin_copy = tin_copy.slice(2);
+ } // Extract date of birth
+
+
+ var full_year = '';
+ var month = tin_copy.slice(2, 4);
+ var day = parseInt(tin_copy.slice(4, 6), 10);
+
+ if (tin.length > 11) {
+ full_year = tin.slice(0, 4);
+ } else {
+ full_year = tin.slice(0, 2);
+
+ if (tin.length === 11 && day < 60) {
+ // Extract full year from centenarian symbol
+ // Should work just fine until year 10000 or so
+ var current_year = new Date().getFullYear().toString();
+ var current_century = parseInt(current_year.slice(0, 2), 10);
+ current_year = parseInt(current_year, 10);
+
+ if (tin[6] === '-') {
+ if (parseInt("".concat(current_century).concat(full_year), 10) > current_year) {
+ full_year = "".concat(current_century - 1).concat(full_year);
+ } else {
+ full_year = "".concat(current_century).concat(full_year);
+ }
+ } else {
+ full_year = "".concat(current_century - 1).concat(full_year);
+
+ if (current_year - parseInt(full_year, 10) < 100) {
+ return false;
+ }
+ }
+ }
+ } // Normalize day and check date validity
+
+
+ if (day > 60) {
+ day -= 60;
+ }
+
+ if (day < 10) {
+ day = "0".concat(day);
+ }
+
+ var date = "".concat(full_year, "/").concat(month, "/").concat(day);
+
+ if (date.length === 8) {
+ if (!(0, _isDate.default)(date, 'YY/MM/DD')) {
+ return false;
+ }
+ } else if (!(0, _isDate.default)(date, 'YYYY/MM/DD')) {
+ return false;
+ }
+
+ return algorithms.luhnCheck(tin.replace(/\W/, ''));
+ } // Locale lookup objects
+
+ /*
+ * Tax id regex formats for various locales
+ *
+ * Where not explicitly specified in DG-TAXUD document both
+ * uppercase and lowercase letters are acceptable.
+ */
+
+
+ var taxIdFormat = {
+ 'bg-BG': /^\d{10}$/,
+ 'cs-CZ': /^\d{6}\/{0,1}\d{3,4}$/,
+ 'de-AT': /^\d{9}$/,
+ 'de-DE': /^[1-9]\d{10}$/,
+ 'dk-DK': /^\d{6}-{0,1}\d{4}$/,
+ 'el-CY': /^[09]\d{7}[A-Z]$/,
+ 'el-GR': /^([0-4]|[7-9])\d{8}$/,
+ 'en-CA': /^\d{9}$/,
+ 'en-GB': /^\d{10}$|^(?!GB|NK|TN|ZZ)(?![DFIQUV])[A-Z](?![DFIQUVO])[A-Z]\d{6}[ABCD ]$/i,
+ 'en-IE': /^\d{7}[A-W][A-IW]{0,1}$/i,
+ 'en-US': /^\d{2}[- ]{0,1}\d{7}$/,
+ 'es-ES': /^(\d{0,8}|[XYZKLM]\d{7})[A-HJ-NP-TV-Z]$/i,
+ 'et-EE': /^[1-6]\d{6}(00[1-9]|0[1-9][0-9]|[1-6][0-9]{2}|70[0-9]|710)\d$/,
+ 'fi-FI': /^\d{6}[-+A]\d{3}[0-9A-FHJ-NPR-Y]$/i,
+ 'fr-BE': /^\d{11}$/,
+ 'fr-FR': /^[0-3]\d{12}$|^[0-3]\d\s\d{2}(\s\d{3}){3}$/,
+ // Conforms both to official spec and provided example
+ 'fr-LU': /^\d{13}$/,
+ 'hr-HR': /^\d{11}$/,
+ 'hu-HU': /^8\d{9}$/,
+ 'it-IT': /^[A-Z]{6}[L-NP-V0-9]{2}[A-EHLMPRST][L-NP-V0-9]{2}[A-ILMZ][L-NP-V0-9]{3}[A-Z]$/i,
+ 'lv-LV': /^\d{6}-{0,1}\d{5}$/,
+ // Conforms both to DG TAXUD spec and original research
+ 'mt-MT': /^\d{3,7}[APMGLHBZ]$|^([1-8])\1\d{7}$/i,
+ 'nl-NL': /^\d{9}$/,
+ 'pl-PL': /^\d{10,11}$/,
+ 'pt-BR': /(?:^\d{11}$)|(?:^\d{14}$)/,
+ 'pt-PT': /^\d{9}$/,
+ 'ro-RO': /^\d{13}$/,
+ 'sk-SK': /^\d{6}\/{0,1}\d{3,4}$/,
+ 'sl-SI': /^[1-9]\d{7}$/,
+ 'sv-SE': /^(\d{6}[-+]{0,1}\d{4}|(18|19|20)\d{6}[-+]{0,1}\d{4})$/
+ }; // taxIdFormat locale aliases
+
+ taxIdFormat['lb-LU'] = taxIdFormat['fr-LU'];
+ taxIdFormat['lt-LT'] = taxIdFormat['et-EE'];
+ taxIdFormat['nl-BE'] = taxIdFormat['fr-BE'];
+ taxIdFormat['fr-CA'] = taxIdFormat['en-CA']; // Algorithmic tax id check functions for various locales
+
+ var taxIdCheck = {
+ 'bg-BG': bgBgCheck,
+ 'cs-CZ': csCzCheck,
+ 'de-AT': deAtCheck,
+ 'de-DE': deDeCheck,
+ 'dk-DK': dkDkCheck,
+ 'el-CY': elCyCheck,
+ 'el-GR': elGrCheck,
+ 'en-CA': isCanadianSIN,
+ 'en-IE': enIeCheck,
+ 'en-US': enUsCheck,
+ 'es-ES': esEsCheck,
+ 'et-EE': etEeCheck,
+ 'fi-FI': fiFiCheck,
+ 'fr-BE': frBeCheck,
+ 'fr-FR': frFrCheck,
+ 'fr-LU': frLuCheck,
+ 'hr-HR': hrHrCheck,
+ 'hu-HU': huHuCheck,
+ 'it-IT': itItCheck,
+ 'lv-LV': lvLvCheck,
+ 'mt-MT': mtMtCheck,
+ 'nl-NL': nlNlCheck,
+ 'pl-PL': plPlCheck,
+ 'pt-BR': ptBrCheck,
+ 'pt-PT': ptPtCheck,
+ 'ro-RO': roRoCheck,
+ 'sk-SK': skSkCheck,
+ 'sl-SI': slSiCheck,
+ 'sv-SE': svSeCheck
+ }; // taxIdCheck locale aliases
+
+ taxIdCheck['lb-LU'] = taxIdCheck['fr-LU'];
+ taxIdCheck['lt-LT'] = taxIdCheck['et-EE'];
+ taxIdCheck['nl-BE'] = taxIdCheck['fr-BE'];
+ taxIdCheck['fr-CA'] = taxIdCheck['en-CA']; // Regexes for locales where characters should be omitted before checking format
+
+ var allsymbols = /[-\\\/!@#$%\^&\*\(\)\+\=\[\]]+/g;
+ var sanitizeRegexes = {
+ 'de-AT': allsymbols,
+ 'de-DE': /[\/\\]/g,
+ 'fr-BE': allsymbols
+ }; // sanitizeRegexes locale aliases
+
+ sanitizeRegexes['nl-BE'] = sanitizeRegexes['fr-BE'];
+ /*
+ * Validator function
+ * Return true if the passed string is a valid tax identification number
+ * for the specified locale.
+ * Throw an error exception if the locale is not supported.
+ */
+
+ function isTaxID(str) {
+ var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
+ (0, _assertString.default)(str); // Copy TIN to avoid replacement if sanitized
+
+ var strcopy = str.slice(0);
+
+ if (locale in taxIdFormat) {
+ if (locale in sanitizeRegexes) {
+ strcopy = strcopy.replace(sanitizeRegexes[locale], '');
+ }
+
+ if (!taxIdFormat[locale].test(strcopy)) {
+ return false;
+ }
+
+ if (locale in taxIdCheck) {
+ return taxIdCheck[locale](strcopy);
+ } // Fallthrough; not all locales have algorithmic checks
+
+
+ return true;
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isTaxID, isTaxIDExports));
+ return isTaxIDExports;
+}
+
+var isMobilePhone = {};
+
+var hasRequiredIsMobilePhone;
+
+function requireIsMobilePhone () {
+ if (hasRequiredIsMobilePhone) return isMobilePhone;
+ hasRequiredIsMobilePhone = 1;
+
+ Object.defineProperty(isMobilePhone, "__esModule", {
+ value: true
+ });
+ isMobilePhone.default = isMobilePhone$1;
+ isMobilePhone.locales = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /* eslint-disable max-len */
+ var phones = {
+ 'am-AM': /^(\+?374|0)((10|[9|7][0-9])\d{6}$|[2-4]\d{7}$)/,
+ 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/,
+ 'ar-BH': /^(\+?973)?(3|6)\d{7}$/,
+ 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/,
+ 'ar-LB': /^(\+?961)?((3|81)\d{6}|7\d{7})$/,
+ 'ar-EG': /^((\+?20)|0)?1[0125]\d{8}$/,
+ 'ar-IQ': /^(\+?964|0)?7[0-9]\d{8}$/,
+ 'ar-JO': /^(\+?962|0)?7[789]\d{7}$/,
+ 'ar-KW': /^(\+?965)([569]\d{7}|41\d{6})$/,
+ 'ar-LY': /^((\+?218)|0)?(9[1-6]\d{7}|[1-8]\d{7,9})$/,
+ 'ar-MA': /^(?:(?:\+|00)212|0)[5-7]\d{8}$/,
+ 'ar-OM': /^((\+|00)968)?(9[1-9])\d{6}$/,
+ 'ar-PS': /^(\+?970|0)5[6|9](\d{7})$/,
+ 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/,
+ 'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/,
+ 'ar-TN': /^(\+?216)?[2459]\d{7}$/,
+ 'az-AZ': /^(\+994|0)(10|5[015]|7[07]|99)\d{7}$/,
+ 'bs-BA': /^((((\+|00)3876)|06))((([0-3]|[5-6])\d{6})|(4\d{7}))$/,
+ 'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/,
+ 'bg-BG': /^(\+?359|0)?8[789]\d{7}$/,
+ 'bn-BD': /^(\+?880|0)1[13456789][0-9]{8}$/,
+ 'ca-AD': /^(\+376)?[346]\d{5}$/,
+ 'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
+ 'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/,
+ 'de-DE': /^((\+49|0)1)(5[0-25-9]\d|6([23]|0\d?)|7([0-57-9]|6\d))\d{7,9}$/,
+ 'de-AT': /^(\+43|0)\d{1,4}\d{3,12}$/,
+ 'de-CH': /^(\+41|0)([1-9])\d{1,9}$/,
+ 'de-LU': /^(\+352)?((6\d1)\d{6})$/,
+ 'dv-MV': /^(\+?960)?(7[2-9]|9[1-9])\d{5}$/,
+ 'el-GR': /^(\+?30|0)?6(8[5-9]|9(?![26])[0-9])\d{7}$/,
+ 'el-CY': /^(\+?357?)?(9(9|6)\d{6})$/,
+ 'en-AI': /^(\+?1|0)264(?:2(35|92)|4(?:6[1-2]|76|97)|5(?:3[6-9]|8[1-4])|7(?:2(4|9)|72))\d{4}$/,
+ 'en-AU': /^(\+?61|0)4\d{8}$/,
+ 'en-AG': /^(?:\+1|1)268(?:464|7(?:1[3-9]|[28]\d|3[0246]|64|7[0-689]))\d{4}$/,
+ 'en-BM': /^(\+?1)?441(((3|7)\d{6}$)|(5[0-3][0-9]\d{4}$)|(59\d{5}$))/,
+ 'en-BS': /^(\+?1[-\s]?|0)?\(?242\)?[-\s]?\d{3}[-\s]?\d{4}$/,
+ 'en-GB': /^(\+?44|0)7\d{9}$/,
+ 'en-GG': /^(\+?44|0)1481\d{6}$/,
+ 'en-GH': /^(\+233|0)(20|50|24|54|27|57|26|56|23|28|55|59)\d{7}$/,
+ 'en-GY': /^(\+592|0)6\d{6}$/,
+ 'en-HK': /^(\+?852[-\s]?)?[456789]\d{3}[-\s]?\d{4}$/,
+ 'en-MO': /^(\+?853[-\s]?)?[6]\d{3}[-\s]?\d{4}$/,
+ 'en-IE': /^(\+?353|0)8[356789]\d{7}$/,
+ 'en-IN': /^(\+?91|0)?[6789]\d{9}$/,
+ 'en-JM': /^(\+?876)?\d{7}$/,
+ 'en-KE': /^(\+?254|0)(7|1)\d{8}$/,
+ 'en-SS': /^(\+?211|0)(9[1257])\d{7}$/,
+ 'en-KI': /^((\+686|686)?)?( )?((6|7)(2|3|8)[0-9]{6})$/,
+ 'en-KN': /^(?:\+1|1)869(?:46\d|48[89]|55[6-8]|66\d|76[02-7])\d{4}$/,
+ 'en-LS': /^(\+?266)(22|28|57|58|59|27|52)\d{6}$/,
+ 'en-MT': /^(\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/,
+ 'en-MU': /^(\+?230|0)?\d{8}$/,
+ 'en-NA': /^(\+?264|0)(6|8)\d{7}$/,
+ 'en-NG': /^(\+?234|0)?[789]\d{9}$/,
+ 'en-NZ': /^(\+?64|0)[28]\d{7,9}$/,
+ 'en-PG': /^(\+?675|0)?(7\d|8[18])\d{6}$/,
+ 'en-PK': /^((00|\+)?92|0)3[0-6]\d{8}$/,
+ 'en-PH': /^(09|\+639)\d{9}$/,
+ 'en-RW': /^(\+?250|0)?[7]\d{8}$/,
+ 'en-SG': /^(\+65)?[3689]\d{7}$/,
+ 'en-SL': /^(\+?232|0)\d{8}$/,
+ 'en-TZ': /^(\+?255|0)?[67]\d{8}$/,
+ 'en-UG': /^(\+?256|0)?[7]\d{8}$/,
+ 'en-US': /^((\+1|1)?( |-)?)?(\([2-9][0-9]{2}\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/,
+ 'en-ZA': /^(\+?27|0)\d{9}$/,
+ 'en-ZM': /^(\+?26)?09[567]\d{7}$/,
+ 'en-ZW': /^(\+263)[0-9]{9}$/,
+ 'en-BW': /^(\+?267)?(7[1-8]{1})\d{6}$/,
+ 'es-AR': /^\+?549(11|[2368]\d)\d{8}$/,
+ 'es-BO': /^(\+?591)?(6|7)\d{7}$/,
+ 'es-CO': /^(\+?57)?3(0(0|1|2|4|5)|1\d|2[0-4]|5(0|1))\d{7}$/,
+ 'es-CL': /^(\+?56|0)[2-9]\d{1}\d{7}$/,
+ 'es-CR': /^(\+506)?[2-8]\d{7}$/,
+ 'es-CU': /^(\+53|0053)?5\d{7}/,
+ 'es-DO': /^(\+?1)?8[024]9\d{7}$/,
+ 'es-HN': /^(\+?504)?[9|8|3|2]\d{7}$/,
+ 'es-EC': /^(\+?593|0)([2-7]|9[2-9])\d{7}$/,
+ 'es-ES': /^(\+?34)?[6|7]\d{8}$/,
+ 'es-PE': /^(\+?51)?9\d{8}$/,
+ 'es-MX': /^(\+?52)?(1|01)?\d{10,11}$/,
+ 'es-NI': /^(\+?505)\d{7,8}$/,
+ 'es-PA': /^(\+?507)\d{7,8}$/,
+ 'es-PY': /^(\+?595|0)9[9876]\d{7}$/,
+ 'es-SV': /^(\+?503)?[67]\d{7}$/,
+ 'es-UY': /^(\+598|0)9[1-9][\d]{6}$/,
+ 'es-VE': /^(\+?58)?(2|4)\d{9}$/,
+ 'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/,
+ 'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/,
+ 'fi-FI': /^(\+?358|0)\s?(4[0-6]|50)\s?(\d\s?){4,8}$/,
+ 'fj-FJ': /^(\+?679)?\s?\d{3}\s?\d{4}$/,
+ 'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/,
+ 'fr-BF': /^(\+226|0)[67]\d{7}$/,
+ 'fr-BJ': /^(\+229)\d{8}$/,
+ 'fr-CD': /^(\+?243|0)?(8|9)\d{8}$/,
+ 'fr-CM': /^(\+?237)6[0-9]{8}$/,
+ 'fr-FR': /^(\+?33|0)[67]\d{8}$/,
+ 'fr-GF': /^(\+?594|0|00594)[67]\d{8}$/,
+ 'fr-GP': /^(\+?590|0|00590)[67]\d{8}$/,
+ 'fr-MQ': /^(\+?596|0|00596)[67]\d{8}$/,
+ 'fr-PF': /^(\+?689)?8[789]\d{6}$/,
+ 'fr-RE': /^(\+?262|0|00262)[67]\d{8}$/,
+ 'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}$/,
+ 'hu-HU': /^(\+?36|06)(20|30|31|50|70)\d{7}$/,
+ 'id-ID': /^(\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\s?|\d]{5,11})$/,
+ 'ir-IR': /^(\+98|0)?9\d{9}$/,
+ 'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/,
+ 'it-SM': /^((\+378)|(0549)|(\+390549)|(\+3780549))?6\d{5,9}$/,
+ 'ja-JP': /^(\+81[ \-]?(\(0\))?|0)[6789]0[ \-]?\d{4}[ \-]?\d{4}$/,
+ 'ka-GE': /^(\+?995)?(79\d{7}|5\d{8})$/,
+ 'kk-KZ': /^(\+?7|8)?7\d{9}$/,
+ 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/,
+ 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/,
+ 'ky-KG': /^(\+?7\s?\+?7|0)\s?\d{2}\s?\d{3}\s?\d{4}$/,
+ 'lt-LT': /^(\+370|8)\d{8}$/,
+ 'lv-LV': /^(\+?371)2\d{7}$/,
+ 'mg-MG': /^((\+?261|0)(2|3)\d)?\d{7}$/,
+ 'mn-MN': /^(\+|00|011)?976(77|81|88|91|94|95|96|99)\d{6}$/,
+ 'my-MM': /^(\+?959|09|9)(2[5-7]|3[1-2]|4[0-5]|6[6-9]|7[5-9]|9[6-9])[0-9]{7}$/,
+ 'ms-MY': /^(\+?60|0)1(([0145](-|\s)?\d{7,8})|([236-9](-|\s)?\d{7}))$/,
+ 'mz-MZ': /^(\+?258)?8[234567]\d{7}$/,
+ 'nb-NO': /^(\+?47)?[49]\d{7}$/,
+ 'ne-NP': /^(\+?977)?9[78]\d{8}$/,
+ 'nl-BE': /^(\+?32|0)4\d{8}$/,
+ 'nl-NL': /^(((\+|00)?31\(0\))|((\+|00)?31)|0)6{1}\d{8}$/,
+ 'nl-AW': /^(\+)?297(56|59|64|73|74|99)\d{5}$/,
+ 'nn-NO': /^(\+?47)?[49]\d{7}$/,
+ 'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/,
+ 'pt-BR': /^((\+?55\ ?[1-9]{2}\ ?)|(\+?55\ ?\([1-9]{2}\)\ ?)|(0[1-9]{2}\ ?)|(\([1-9]{2}\)\ ?)|([1-9]{2}\ ?))((\d{4}\-?\d{4})|(9[1-9]{1}\d{3}\-?\d{4}))$/,
+ 'pt-PT': /^(\+?351)?9[1236]\d{7}$/,
+ 'pt-AO': /^(\+244)\d{9}$/,
+ 'ro-MD': /^(\+?373|0)((6(0|1|2|6|7|8|9))|(7(6|7|8|9)))\d{6}$/,
+ 'ro-RO': /^(\+?40|0)\s?7\d{2}(\/|\s|\.|-)?\d{3}(\s|\.|-)?\d{3}$/,
+ 'ru-RU': /^(\+?7|8)?9\d{9}$/,
+ 'si-LK': /^(?:0|94|\+94)?(7(0|1|2|4|5|6|7|8)( |-)?)\d{7}$/,
+ 'sl-SI': /^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$/,
+ 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
+ 'sq-AL': /^(\+355|0)6[789]\d{6}$/,
+ 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/,
+ 'sv-SE': /^(\+?46|0)[\s\-]?7[\s\-]?[02369]([\s\-]?\d){7}$/,
+ 'tg-TJ': /^(\+?992)?[5][5]\d{7}$/,
+ 'th-TH': /^(\+66|66|0)\d{9}$/,
+ 'tr-TR': /^(\+?90|0)?5\d{9}$/,
+ 'tk-TM': /^(\+993|993|8)\d{8}$/,
+ 'uk-UA': /^(\+?38|8)?0\d{9}$/,
+ 'uz-UZ': /^(\+?998)?(6[125-79]|7[1-69]|88|9\d)\d{7}$/,
+ 'vi-VN': /^((\+?84)|0)((3([2-9]))|(5([25689]))|(7([0|6-9]))|(8([1-9]))|(9([0-9])))([0-9]{7})$/,
+ 'zh-CN': /^((\+|00)86)?(1[3-9]|9[28])\d{9}$/,
+ 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/,
+ 'dz-BT': /^(\+?975|0)?(17|16|77|02)\d{6}$/,
+ 'ar-YE': /^(((\+|00)9677|0?7)[0137]\d{7}|((\+|00)967|0)[1-7]\d{6})$/,
+ 'ar-EH': /^(\+?212|0)[\s\-]?(5288|5289)[\s\-]?\d{5}$/,
+ 'fa-AF': /^(\+93|0)?(2{1}[0-8]{1}|[3-5]{1}[0-4]{1})(\d{7})$/
+ };
+ /* eslint-enable max-len */
+ // aliases
+
+ phones['en-CA'] = phones['en-US'];
+ phones['fr-CA'] = phones['en-CA'];
+ phones['fr-BE'] = phones['nl-BE'];
+ phones['zh-HK'] = phones['en-HK'];
+ phones['zh-MO'] = phones['en-MO'];
+ phones['ga-IE'] = phones['en-IE'];
+ phones['fr-CH'] = phones['de-CH'];
+ phones['it-CH'] = phones['fr-CH'];
+
+ function isMobilePhone$1(str, locale, options) {
+ (0, _assertString.default)(str);
+
+ if (options && options.strictMode && !str.startsWith('+')) {
+ return false;
+ }
+
+ if (Array.isArray(locale)) {
+ return locale.some(function (key) {
+ // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
+ // istanbul ignore else
+ if (phones.hasOwnProperty(key)) {
+ var phone = phones[key];
+
+ if (phone.test(str)) {
+ return true;
+ }
+ }
+
+ return false;
+ });
+ } else if (locale in phones) {
+ return phones[locale].test(str); // alias falsey locale as 'any'
+ } else if (!locale || locale === 'any') {
+ for (var key in phones) {
+ // istanbul ignore else
+ if (phones.hasOwnProperty(key)) {
+ var phone = phones[key];
+
+ if (phone.test(str)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+
+ var locales = Object.keys(phones);
+ isMobilePhone.locales = locales;
+ return isMobilePhone;
+}
+
+var isEthereumAddressExports = {};
+var isEthereumAddress = {
+ get exports(){ return isEthereumAddressExports; },
+ set exports(v){ isEthereumAddressExports = v; },
+};
+
+var hasRequiredIsEthereumAddress;
+
+function requireIsEthereumAddress () {
+ if (hasRequiredIsEthereumAddress) return isEthereumAddressExports;
+ hasRequiredIsEthereumAddress = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isEthereumAddress;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var eth = /^(0x)[0-9a-f]{40}$/i;
+
+ function isEthereumAddress(str) {
+ (0, _assertString.default)(str);
+ return eth.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isEthereumAddress, isEthereumAddressExports));
+ return isEthereumAddressExports;
+}
+
+var isCurrencyExports = {};
+var isCurrency = {
+ get exports(){ return isCurrencyExports; },
+ set exports(v){ isCurrencyExports = v; },
+};
+
+var hasRequiredIsCurrency;
+
+function requireIsCurrency () {
+ if (hasRequiredIsCurrency) return isCurrencyExports;
+ hasRequiredIsCurrency = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isCurrency;
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function currencyRegex(options) {
+ var decimal_digits = "\\d{".concat(options.digits_after_decimal[0], "}");
+ options.digits_after_decimal.forEach(function (digit, index) {
+ if (index !== 0) decimal_digits = "".concat(decimal_digits, "|\\d{").concat(digit, "}");
+ });
+ var symbol = "(".concat(options.symbol.replace(/\W/, function (m) {
+ return "\\".concat(m);
+ }), ")").concat(options.require_symbol ? '' : '?'),
+ negative = '-?',
+ whole_dollar_amount_without_sep = '[1-9]\\d*',
+ whole_dollar_amount_with_sep = "[1-9]\\d{0,2}(\\".concat(options.thousands_separator, "\\d{3})*"),
+ valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep],
+ whole_dollar_amount = "(".concat(valid_whole_dollar_amounts.join('|'), ")?"),
+ decimal_amount = "(\\".concat(options.decimal_separator, "(").concat(decimal_digits, "))").concat(options.require_decimal ? '' : '?');
+ var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); // default is negative sign before symbol, but there are two other options (besides parens)
+
+ if (options.allow_negatives && !options.parens_for_negatives) {
+ if (options.negative_sign_after_digits) {
+ pattern += negative;
+ } else if (options.negative_sign_before_digits) {
+ pattern = negative + pattern;
+ }
+ } // South African Rand, for example, uses R 123 (space) and R-123 (no space)
+
+
+ if (options.allow_negative_sign_placeholder) {
+ pattern = "( (?!\\-))?".concat(pattern);
+ } else if (options.allow_space_after_symbol) {
+ pattern = " ?".concat(pattern);
+ } else if (options.allow_space_after_digits) {
+ pattern += '( (?!$))?';
+ }
+
+ if (options.symbol_after_digits) {
+ pattern += symbol;
+ } else {
+ pattern = symbol + pattern;
+ }
+
+ if (options.allow_negatives) {
+ if (options.parens_for_negatives) {
+ pattern = "(\\(".concat(pattern, "\\)|").concat(pattern, ")");
+ } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) {
+ pattern = negative + pattern;
+ }
+ } // ensure there's a dollar and/or decimal amount, and that
+ // it doesn't start with a space or a negative sign followed by a space
+
+
+ return new RegExp("^(?!-? )(?=.*\\d)".concat(pattern, "$"));
+ }
+
+ var default_currency_options = {
+ symbol: '$',
+ require_symbol: false,
+ allow_space_after_symbol: false,
+ symbol_after_digits: false,
+ allow_negatives: true,
+ parens_for_negatives: false,
+ negative_sign_before_digits: false,
+ negative_sign_after_digits: false,
+ allow_negative_sign_placeholder: false,
+ thousands_separator: ',',
+ decimal_separator: '.',
+ allow_decimal: true,
+ require_decimal: false,
+ digits_after_decimal: [2],
+ allow_space_after_digits: false
+ };
+
+ function isCurrency(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, default_currency_options);
+ return currencyRegex(options).test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isCurrency, isCurrencyExports));
+ return isCurrencyExports;
+}
+
+var isBtcAddressExports = {};
+var isBtcAddress = {
+ get exports(){ return isBtcAddressExports; },
+ set exports(v){ isBtcAddressExports = v; },
+};
+
+var hasRequiredIsBtcAddress;
+
+function requireIsBtcAddress () {
+ if (hasRequiredIsBtcAddress) return isBtcAddressExports;
+ hasRequiredIsBtcAddress = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBtcAddress;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var bech32 = /^(bc1)[a-z0-9]{25,39}$/;
+ var base58 = /^(1|3)[A-HJ-NP-Za-km-z1-9]{25,39}$/;
+
+ function isBtcAddress(str) {
+ (0, _assertString.default)(str);
+ return bech32.test(str) || base58.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBtcAddress, isBtcAddressExports));
+ return isBtcAddressExports;
+}
+
+var isISO6391Exports = {};
+var isISO6391 = {
+ get exports(){ return isISO6391Exports; },
+ set exports(v){ isISO6391Exports = v; },
+};
+
+var hasRequiredIsISO6391;
+
+function requireIsISO6391 () {
+ if (hasRequiredIsISO6391) return isISO6391Exports;
+ hasRequiredIsISO6391 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISO6391;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var isISO6391Set = new Set(['aa', 'ab', 'ae', 'af', 'ak', 'am', 'an', 'ar', 'as', 'av', 'ay', 'az', 'az', 'ba', 'be', 'bg', 'bh', 'bi', 'bm', 'bn', 'bo', 'br', 'bs', 'ca', 'ce', 'ch', 'co', 'cr', 'cs', 'cu', 'cv', 'cy', 'da', 'de', 'dv', 'dz', 'ee', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'ff', 'fi', 'fj', 'fo', 'fr', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu', 'gv', 'ha', 'he', 'hi', 'ho', 'hr', 'ht', 'hu', 'hy', 'hz', 'ia', 'id', 'ie', 'ig', 'ii', 'ik', 'io', 'is', 'it', 'iu', 'ja', 'jv', 'ka', 'kg', 'ki', 'kj', 'kk', 'kl', 'km', 'kn', 'ko', 'kr', 'ks', 'ku', 'kv', 'kw', 'ky', 'la', 'lb', 'lg', 'li', 'ln', 'lo', 'lt', 'lu', 'lv', 'mg', 'mh', 'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'mt', 'my', 'na', 'nb', 'nd', 'ne', 'ng', 'nl', 'nn', 'no', 'nr', 'nv', 'ny', 'oc', 'oj', 'om', 'or', 'os', 'pa', 'pi', 'pl', 'ps', 'pt', 'qu', 'rm', 'rn', 'ro', 'ru', 'rw', 'sa', 'sc', 'sd', 'se', 'sg', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'ss', 'st', 'su', 'sv', 'sw', 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'to', 'tr', 'ts', 'tt', 'tw', 'ty', 'ug', 'uk', 'ur', 'uz', 've', 'vi', 'vo', 'wa', 'wo', 'xh', 'yi', 'yo', 'za', 'zh', 'zu']);
+
+ function isISO6391(str) {
+ (0, _assertString.default)(str);
+ return isISO6391Set.has(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISO6391, isISO6391Exports));
+ return isISO6391Exports;
+}
+
+var isISO8601Exports = {};
+var isISO8601 = {
+ get exports(){ return isISO8601Exports; },
+ set exports(v){ isISO8601Exports = v; },
+};
+
+var hasRequiredIsISO8601;
+
+function requireIsISO8601 () {
+ if (hasRequiredIsISO8601) return isISO8601Exports;
+ hasRequiredIsISO8601 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISO8601;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /* eslint-disable max-len */
+ // from http://goo.gl/0ejHHW
+ var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; // same as above, except with a strict 'T' separator between date and time
+
+ var iso8601StrictSeparator = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
+ /* eslint-enable max-len */
+
+ var isValidDate = function isValidDate(str) {
+ // str must have passed the ISO8601 check
+ // this check is meant to catch invalid dates
+ // like 2009-02-31
+ // first check for ordinal dates
+ var ordinalMatch = str.match(/^(\d{4})-?(\d{3})([ T]{1}\.*|$)/);
+
+ if (ordinalMatch) {
+ var oYear = Number(ordinalMatch[1]);
+ var oDay = Number(ordinalMatch[2]); // if is leap year
+
+ if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366;
+ return oDay <= 365;
+ }
+
+ var match = str.match(/(\d{4})-?(\d{0,2})-?(\d*)/).map(Number);
+ var year = match[1];
+ var month = match[2];
+ var day = match[3];
+ var monthString = month ? "0".concat(month).slice(-2) : month;
+ var dayString = day ? "0".concat(day).slice(-2) : day; // create a date object and compare
+
+ var d = new Date("".concat(year, "-").concat(monthString || '01', "-").concat(dayString || '01'));
+
+ if (month && day) {
+ return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;
+ }
+
+ return true;
+ };
+
+ function isISO8601(str) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ (0, _assertString.default)(str);
+ var check = options.strictSeparator ? iso8601StrictSeparator.test(str) : iso8601.test(str);
+ if (check && options.strict) return isValidDate(str);
+ return check;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISO8601, isISO8601Exports));
+ return isISO8601Exports;
+}
+
+var isRFC3339Exports = {};
+var isRFC3339 = {
+ get exports(){ return isRFC3339Exports; },
+ set exports(v){ isRFC3339Exports = v; },
+};
+
+var hasRequiredIsRFC3339;
+
+function requireIsRFC3339 () {
+ if (hasRequiredIsRFC3339) return isRFC3339Exports;
+ hasRequiredIsRFC3339 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isRFC3339;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */
+ var dateFullYear = /[0-9]{4}/;
+ var dateMonth = /(0[1-9]|1[0-2])/;
+ var dateMDay = /([12]\d|0[1-9]|3[01])/;
+ var timeHour = /([01][0-9]|2[0-3])/;
+ var timeMinute = /[0-5][0-9]/;
+ var timeSecond = /([0-5][0-9]|60)/;
+ var timeSecFrac = /(\.[0-9]+)?/;
+ var timeNumOffset = new RegExp("[-+]".concat(timeHour.source, ":").concat(timeMinute.source));
+ var timeOffset = new RegExp("([zZ]|".concat(timeNumOffset.source, ")"));
+ var partialTime = new RegExp("".concat(timeHour.source, ":").concat(timeMinute.source, ":").concat(timeSecond.source).concat(timeSecFrac.source));
+ var fullDate = new RegExp("".concat(dateFullYear.source, "-").concat(dateMonth.source, "-").concat(dateMDay.source));
+ var fullTime = new RegExp("".concat(partialTime.source).concat(timeOffset.source));
+ var rfc3339 = new RegExp("^".concat(fullDate.source, "[ tT]").concat(fullTime.source, "$"));
+
+ function isRFC3339(str) {
+ (0, _assertString.default)(str);
+ return rfc3339.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isRFC3339, isRFC3339Exports));
+ return isRFC3339Exports;
+}
+
+var isISO31661Alpha3Exports = {};
+var isISO31661Alpha3 = {
+ get exports(){ return isISO31661Alpha3Exports; },
+ set exports(v){ isISO31661Alpha3Exports = v; },
+};
+
+var hasRequiredIsISO31661Alpha3;
+
+function requireIsISO31661Alpha3 () {
+ if (hasRequiredIsISO31661Alpha3) return isISO31661Alpha3Exports;
+ hasRequiredIsISO31661Alpha3 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isISO31661Alpha3;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
+ var validISO31661Alpha3CountriesCodes = new Set(['AFG', 'ALA', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATA', 'ATG', 'ARG', 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHS', 'BHR', 'BGD', 'BRB', 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BES', 'BIH', 'BWA', 'BVT', 'BRA', 'IOT', 'BRN', 'BGR', 'BFA', 'BDI', 'KHM', 'CMR', 'CAN', 'CPV', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'CXR', 'CCK', 'COL', 'COM', 'COG', 'COD', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP', 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ', 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'GUF', 'PYF', 'ATF', 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD', 'GLP', 'GUM', 'GTM', 'GGY', 'GIN', 'GNB', 'GUY', 'HTI', 'HMD', 'VAT', 'HND', 'HKG', 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR', 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'PRK', 'KOR', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR', 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS', 'MDV', 'MLI', 'MLT', 'MHL', 'MTQ', 'MRT', 'MUS', 'MYT', 'MEX', 'FSM', 'MDA', 'MCO', 'MNG', 'MNE', 'MSR', 'MAR', 'MOZ', 'MMR', 'NAM', 'NRU', 'NPL', 'NLD', 'NCL', 'NZL', 'NIC', 'NER', 'NGA', 'NIU', 'NFK', 'MNP', 'NOR', 'OMN', 'PAK', 'PLW', 'PSE', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'PCN', 'POL', 'PRT', 'PRI', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'BLM', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP', 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SGS', 'SSD', 'ESP', 'LKA', 'SDN', 'SUR', 'SJM', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA', 'THA', 'TLS', 'TGO', 'TKL', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TCA', 'TUV', 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'UMI', 'URY', 'UZB', 'VUT', 'VEN', 'VNM', 'VGB', 'VIR', 'WLF', 'ESH', 'YEM', 'ZMB', 'ZWE']);
+
+ function isISO31661Alpha3(str) {
+ (0, _assertString.default)(str);
+ return validISO31661Alpha3CountriesCodes.has(str.toUpperCase());
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isISO31661Alpha3, isISO31661Alpha3Exports));
+ return isISO31661Alpha3Exports;
+}
+
+var isISO4217 = {};
+
+var hasRequiredIsISO4217;
+
+function requireIsISO4217 () {
+ if (hasRequiredIsISO4217) return isISO4217;
+ hasRequiredIsISO4217 = 1;
+
+ Object.defineProperty(isISO4217, "__esModule", {
+ value: true
+ });
+ isISO4217.default = isISO4217$1;
+ isISO4217.CurrencyCodes = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // from https://en.wikipedia.org/wiki/ISO_4217
+ var validISO4217CurrencyCodes = new Set(['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'CNY', 'COP', 'COU', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'USN', 'UYI', 'UYU', 'UYW', 'UZS', 'VES', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XBA', 'XBB', 'XBC', 'XBD', 'XCD', 'XDR', 'XOF', 'XPD', 'XPF', 'XPT', 'XSU', 'XTS', 'XUA', 'XXX', 'YER', 'ZAR', 'ZMW', 'ZWL']);
+
+ function isISO4217$1(str) {
+ (0, _assertString.default)(str);
+ return validISO4217CurrencyCodes.has(str.toUpperCase());
+ }
+
+ var CurrencyCodes = validISO4217CurrencyCodes;
+ isISO4217.CurrencyCodes = CurrencyCodes;
+ return isISO4217;
+}
+
+var isBase32Exports = {};
+var isBase32 = {
+ get exports(){ return isBase32Exports; },
+ set exports(v){ isBase32Exports = v; },
+};
+
+var hasRequiredIsBase32;
+
+function requireIsBase32 () {
+ if (hasRequiredIsBase32) return isBase32Exports;
+ hasRequiredIsBase32 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBase32;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var base32 = /^[A-Z2-7]+=*$/;
+ var crockfordBase32 = /^[A-HJKMNP-TV-Z0-9]+$/;
+ var defaultBase32Options = {
+ crockford: false
+ };
+
+ function isBase32(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, defaultBase32Options);
+
+ if (options.crockford) {
+ return crockfordBase32.test(str);
+ }
+
+ var len = str.length;
+
+ if (len % 8 === 0 && base32.test(str)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBase32, isBase32Exports));
+ return isBase32Exports;
+}
+
+var isBase58Exports = {};
+var isBase58 = {
+ get exports(){ return isBase58Exports; },
+ set exports(v){ isBase58Exports = v; },
+};
+
+var hasRequiredIsBase58;
+
+function requireIsBase58 () {
+ if (hasRequiredIsBase58) return isBase58Exports;
+ hasRequiredIsBase58 = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isBase58;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // Accepted chars - 123456789ABCDEFGH JKLMN PQRSTUVWXYZabcdefghijk mnopqrstuvwxyz
+ var base58Reg = /^[A-HJ-NP-Za-km-z1-9]*$/;
+
+ function isBase58(str) {
+ (0, _assertString.default)(str);
+
+ if (base58Reg.test(str)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isBase58, isBase58Exports));
+ return isBase58Exports;
+}
+
+var isDataURIExports = {};
+var isDataURI = {
+ get exports(){ return isDataURIExports; },
+ set exports(v){ isDataURIExports = v; },
+};
+
+var hasRequiredIsDataURI;
+
+function requireIsDataURI () {
+ if (hasRequiredIsDataURI) return isDataURIExports;
+ hasRequiredIsDataURI = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isDataURI;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var validMediaType = /^[a-z]+\/[a-z0-9\-\+\._]+$/i;
+ var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i;
+ var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i;
+
+ function isDataURI(str) {
+ (0, _assertString.default)(str);
+ var data = str.split(',');
+
+ if (data.length < 2) {
+ return false;
+ }
+
+ var attributes = data.shift().trim().split(';');
+ var schemeAndMediaType = attributes.shift();
+
+ if (schemeAndMediaType.slice(0, 5) !== 'data:') {
+ return false;
+ }
+
+ var mediaType = schemeAndMediaType.slice(5);
+
+ if (mediaType !== '' && !validMediaType.test(mediaType)) {
+ return false;
+ }
+
+ for (var i = 0; i < attributes.length; i++) {
+ if (!(i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') && !validAttribute.test(attributes[i])) {
+ return false;
+ }
+ }
+
+ for (var _i = 0; _i < data.length; _i++) {
+ if (!validData.test(data[_i])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isDataURI, isDataURIExports));
+ return isDataURIExports;
+}
+
+var isMagnetURIExports = {};
+var isMagnetURI = {
+ get exports(){ return isMagnetURIExports; },
+ set exports(v){ isMagnetURIExports = v; },
+};
+
+var hasRequiredIsMagnetURI;
+
+function requireIsMagnetURI () {
+ if (hasRequiredIsMagnetURI) return isMagnetURIExports;
+ hasRequiredIsMagnetURI = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isMagnetURI;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var magnetURIComponent = /(?:^magnet:\?|[^?&]&)xt(?:\.1)?=urn:(?:(?:aich|bitprint|btih|ed2k|ed2khash|kzhash|md5|sha1|tree:tiger):[a-z0-9]{32}(?:[a-z0-9]{8})?|btmh:1220[a-z0-9]{64})(?:$|&)/i;
+
+ function isMagnetURI(url) {
+ (0, _assertString.default)(url);
+
+ if (url.indexOf('magnet:?') !== 0) {
+ return false;
+ }
+
+ return magnetURIComponent.test(url);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isMagnetURI, isMagnetURIExports));
+ return isMagnetURIExports;
+}
+
+var isMimeTypeExports = {};
+var isMimeType = {
+ get exports(){ return isMimeTypeExports; },
+ set exports(v){ isMimeTypeExports = v; },
+};
+
+var hasRequiredIsMimeType;
+
+function requireIsMimeType () {
+ if (hasRequiredIsMimeType) return isMimeTypeExports;
+ hasRequiredIsMimeType = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isMimeType;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ /*
+ Checks if the provided string matches to a correct Media type format (MIME type)
+
+ This function only checks is the string format follows the
+ etablished rules by the according RFC specifications.
+ This function supports 'charset' in textual media types
+ (https://tools.ietf.org/html/rfc6657).
+
+ This function does not check against all the media types listed
+ by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml)
+ because of lightness purposes : it would require to include
+ all these MIME types in this librairy, which would weigh it
+ significantly. This kind of effort maybe is not worth for the use that
+ this function has in this entire librairy.
+
+ More informations in the RFC specifications :
+ - https://tools.ietf.org/html/rfc2045
+ - https://tools.ietf.org/html/rfc2046
+ - https://tools.ietf.org/html/rfc7231#section-3.1.1.1
+ - https://tools.ietf.org/html/rfc7231#section-3.1.1.5
+ */
+ // Match simple MIME types
+ // NB :
+ // Subtype length must not exceed 100 characters.
+ // This rule does not comply to the RFC specs (what is the max length ?).
+ var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+_]{1,100}$/i; // eslint-disable-line max-len
+ // Handle "charset" in "text/*"
+
+ var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len
+ // Handle "boundary" in "multipart/*"
+
+ var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len
+
+ function isMimeType(str) {
+ (0, _assertString.default)(str);
+ return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isMimeType, isMimeTypeExports));
+ return isMimeTypeExports;
+}
+
+var isLatLongExports = {};
+var isLatLong = {
+ get exports(){ return isLatLongExports; },
+ set exports(v){ isLatLongExports = v; },
+};
+
+var hasRequiredIsLatLong;
+
+function requireIsLatLong () {
+ if (hasRequiredIsLatLong) return isLatLongExports;
+ hasRequiredIsLatLong = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isLatLong;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/;
+ var long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/;
+ var latDMS = /^(([1-8]?\d)\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|90\D+0\D+0)\D+[NSns]?$/i;
+ var longDMS = /^\s*([1-7]?\d{1,2}\D+([1-5]?\d|60)\D+([1-5]?\d|60)(\.\d+)?|180\D+0\D+0)\D+[EWew]?$/i;
+ var defaultLatLongOptions = {
+ checkDMS: false
+ };
+
+ function isLatLong(str, options) {
+ (0, _assertString.default)(str);
+ options = (0, _merge.default)(options, defaultLatLongOptions);
+ if (!str.includes(',')) return false;
+ var pair = str.split(',');
+ if (pair[0].startsWith('(') && !pair[1].endsWith(')') || pair[1].endsWith(')') && !pair[0].startsWith('(')) return false;
+
+ if (options.checkDMS) {
+ return latDMS.test(pair[0]) && longDMS.test(pair[1]);
+ }
+
+ return lat.test(pair[0]) && long.test(pair[1]);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isLatLong, isLatLongExports));
+ return isLatLongExports;
+}
+
+var isPostalCode = {};
+
+var hasRequiredIsPostalCode;
+
+function requireIsPostalCode () {
+ if (hasRequiredIsPostalCode) return isPostalCode;
+ hasRequiredIsPostalCode = 1;
+
+ Object.defineProperty(isPostalCode, "__esModule", {
+ value: true
+ });
+ isPostalCode.default = isPostalCode$1;
+ isPostalCode.locales = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ // common patterns
+ var threeDigit = /^\d{3}$/;
+ var fourDigit = /^\d{4}$/;
+ var fiveDigit = /^\d{5}$/;
+ var sixDigit = /^\d{6}$/;
+ var patterns = {
+ AD: /^AD\d{3}$/,
+ AT: fourDigit,
+ AU: fourDigit,
+ AZ: /^AZ\d{4}$/,
+ BA: /^([7-8]\d{4}$)/,
+ BE: fourDigit,
+ BG: fourDigit,
+ BR: /^\d{5}-\d{3}$/,
+ BY: /^2[1-4]\d{4}$/,
+ CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i,
+ CH: fourDigit,
+ CN: /^(0[1-7]|1[012356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[1-5]|8[1345]|9[09])\d{4}$/,
+ CZ: /^\d{3}\s?\d{2}$/,
+ DE: fiveDigit,
+ DK: fourDigit,
+ DO: fiveDigit,
+ DZ: fiveDigit,
+ EE: fiveDigit,
+ ES: /^(5[0-2]{1}|[0-4]{1}\d{1})\d{3}$/,
+ FI: fiveDigit,
+ FR: /^\d{2}\s?\d{3}$/,
+ GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i,
+ GR: /^\d{3}\s?\d{2}$/,
+ HR: /^([1-5]\d{4}$)/,
+ HT: /^HT\d{4}$/,
+ HU: fourDigit,
+ ID: fiveDigit,
+ IE: /^(?!.*(?:o))[A-Za-z]\d[\dw]\s\w{4}$/i,
+ IL: /^(\d{5}|\d{7})$/,
+ IN: /^((?!10|29|35|54|55|65|66|86|87|88|89)[1-9][0-9]{5})$/,
+ IR: /^(?!(\d)\1{3})[13-9]{4}[1346-9][013-9]{5}$/,
+ IS: threeDigit,
+ IT: fiveDigit,
+ JP: /^\d{3}\-\d{4}$/,
+ KE: fiveDigit,
+ KR: /^(\d{5}|\d{6})$/,
+ LI: /^(948[5-9]|949[0-7])$/,
+ LT: /^LT\-\d{5}$/,
+ LU: fourDigit,
+ LV: /^LV\-\d{4}$/,
+ LK: fiveDigit,
+ MG: threeDigit,
+ MX: fiveDigit,
+ MT: /^[A-Za-z]{3}\s{0,1}\d{4}$/,
+ MY: fiveDigit,
+ NL: /^\d{4}\s?[a-z]{2}$/i,
+ NO: fourDigit,
+ NP: /^(10|21|22|32|33|34|44|45|56|57)\d{3}$|^(977)$/i,
+ NZ: fourDigit,
+ PL: /^\d{2}\-\d{3}$/,
+ PR: /^00[679]\d{2}([ -]\d{4})?$/,
+ PT: /^\d{4}\-\d{3}?$/,
+ RO: sixDigit,
+ RU: sixDigit,
+ SA: fiveDigit,
+ SE: /^[1-9]\d{2}\s?\d{2}$/,
+ SG: sixDigit,
+ SI: fourDigit,
+ SK: /^\d{3}\s?\d{2}$/,
+ TH: fiveDigit,
+ TN: fourDigit,
+ TW: /^\d{3}(\d{2})?$/,
+ UA: fiveDigit,
+ US: /^\d{5}(-\d{4})?$/,
+ ZA: fourDigit,
+ ZM: fiveDigit
+ };
+ var locales = Object.keys(patterns);
+ isPostalCode.locales = locales;
+
+ function isPostalCode$1(str, locale) {
+ (0, _assertString.default)(str);
+
+ if (locale in patterns) {
+ return patterns[locale].test(str);
+ } else if (locale === 'any') {
+ for (var key in patterns) {
+ // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes
+ // istanbul ignore else
+ if (patterns.hasOwnProperty(key)) {
+ var pattern = patterns[key];
+
+ if (pattern.test(str)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+ return isPostalCode;
+}
+
+var ltrimExports = {};
+var ltrim = {
+ get exports(){ return ltrimExports; },
+ set exports(v){ ltrimExports = v; },
+};
+
+var hasRequiredLtrim;
+
+function requireLtrim () {
+ if (hasRequiredLtrim) return ltrimExports;
+ hasRequiredLtrim = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = ltrim;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function ltrim(str, chars) {
+ (0, _assertString.default)(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
+
+ var pattern = chars ? new RegExp("^[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+"), 'g') : /^\s+/g;
+ return str.replace(pattern, '');
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (ltrim, ltrimExports));
+ return ltrimExports;
+}
+
+var rtrimExports = {};
+var rtrim = {
+ get exports(){ return rtrimExports; },
+ set exports(v){ rtrimExports = v; },
+};
+
+var hasRequiredRtrim;
+
+function requireRtrim () {
+ if (hasRequiredRtrim) return rtrimExports;
+ hasRequiredRtrim = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = rtrim;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function rtrim(str, chars) {
+ (0, _assertString.default)(str);
+
+ if (chars) {
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
+ var pattern = new RegExp("[".concat(chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), "]+$"), 'g');
+ return str.replace(pattern, '');
+ } // Use a faster and more safe than regex trim method https://blog.stevenlevithan.com/archives/faster-trim-javascript
+
+
+ var strIndex = str.length - 1;
+
+ while (/\s/.test(str.charAt(strIndex))) {
+ strIndex -= 1;
+ }
+
+ return str.slice(0, strIndex + 1);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (rtrim, rtrimExports));
+ return rtrimExports;
+}
+
+var trimExports = {};
+var trim = {
+ get exports(){ return trimExports; },
+ set exports(v){ trimExports = v; },
+};
+
+var hasRequiredTrim;
+
+function requireTrim () {
+ if (hasRequiredTrim) return trimExports;
+ hasRequiredTrim = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = trim;
+
+ var _rtrim = _interopRequireDefault(requireRtrim());
+
+ var _ltrim = _interopRequireDefault(requireLtrim());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function trim(str, chars) {
+ return (0, _rtrim.default)((0, _ltrim.default)(str, chars), chars);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (trim, trimExports));
+ return trimExports;
+}
+
+var _escapeExports = {};
+var _escape = {
+ get exports(){ return _escapeExports; },
+ set exports(v){ _escapeExports = v; },
+};
+
+var hasRequired_escape;
+
+function require_escape () {
+ if (hasRequired_escape) return _escapeExports;
+ hasRequired_escape = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = escape;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function escape(str) {
+ (0, _assertString.default)(str);
+ return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`');
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (_escape, _escapeExports));
+ return _escapeExports;
+}
+
+var _unescapeExports = {};
+var _unescape = {
+ get exports(){ return _unescapeExports; },
+ set exports(v){ _unescapeExports = v; },
+};
+
+var hasRequired_unescape;
+
+function require_unescape () {
+ if (hasRequired_unescape) return _unescapeExports;
+ hasRequired_unescape = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = unescape;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function unescape(str) {
+ (0, _assertString.default)(str);
+ return str.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`').replace(/&/g, '&'); // & replacement has to be the last one to prevent
+ // bugs with intermediate strings containing escape sequences
+ // See: https://github.com/validatorjs/validator.js/issues/1827
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (_unescape, _unescapeExports));
+ return _unescapeExports;
+}
+
+var stripLowExports = {};
+var stripLow = {
+ get exports(){ return stripLowExports; },
+ set exports(v){ stripLowExports = v; },
+};
+
+var blacklistExports = {};
+var blacklist = {
+ get exports(){ return blacklistExports; },
+ set exports(v){ blacklistExports = v; },
+};
+
+var hasRequiredBlacklist;
+
+function requireBlacklist () {
+ if (hasRequiredBlacklist) return blacklistExports;
+ hasRequiredBlacklist = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = blacklist;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function blacklist(str, chars) {
+ (0, _assertString.default)(str);
+ return str.replace(new RegExp("[".concat(chars, "]+"), 'g'), '');
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (blacklist, blacklistExports));
+ return blacklistExports;
+}
+
+var hasRequiredStripLow;
+
+function requireStripLow () {
+ if (hasRequiredStripLow) return stripLowExports;
+ hasRequiredStripLow = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = stripLow;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var _blacklist = _interopRequireDefault(requireBlacklist());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function stripLow(str, keep_new_lines) {
+ (0, _assertString.default)(str);
+ var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F';
+ return (0, _blacklist.default)(str, chars);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (stripLow, stripLowExports));
+ return stripLowExports;
+}
+
+var whitelistExports = {};
+var whitelist = {
+ get exports(){ return whitelistExports; },
+ set exports(v){ whitelistExports = v; },
+};
+
+var hasRequiredWhitelist;
+
+function requireWhitelist () {
+ if (hasRequiredWhitelist) return whitelistExports;
+ hasRequiredWhitelist = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = whitelist;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function whitelist(str, chars) {
+ (0, _assertString.default)(str);
+ return str.replace(new RegExp("[^".concat(chars, "]+"), 'g'), '');
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (whitelist, whitelistExports));
+ return whitelistExports;
+}
+
+var isWhitelistedExports = {};
+var isWhitelisted = {
+ get exports(){ return isWhitelistedExports; },
+ set exports(v){ isWhitelistedExports = v; },
+};
+
+var hasRequiredIsWhitelisted;
+
+function requireIsWhitelisted () {
+ if (hasRequiredIsWhitelisted) return isWhitelistedExports;
+ hasRequiredIsWhitelisted = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isWhitelisted;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ function isWhitelisted(str, chars) {
+ (0, _assertString.default)(str);
+
+ for (var i = str.length - 1; i >= 0; i--) {
+ if (chars.indexOf(str[i]) === -1) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isWhitelisted, isWhitelistedExports));
+ return isWhitelistedExports;
+}
+
+var normalizeEmailExports = {};
+var normalizeEmail = {
+ get exports(){ return normalizeEmailExports; },
+ set exports(v){ normalizeEmailExports = v; },
+};
+
+var hasRequiredNormalizeEmail;
+
+function requireNormalizeEmail () {
+ if (hasRequiredNormalizeEmail) return normalizeEmailExports;
+ hasRequiredNormalizeEmail = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = normalizeEmail;
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var default_normalize_email_options = {
+ // The following options apply to all email addresses
+ // Lowercases the local part of the email address.
+ // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024).
+ // The domain is always lowercased, as per RFC 1035
+ all_lowercase: true,
+ // The following conversions are specific to GMail
+ // Lowercases the local part of the GMail address (known to be case-insensitive)
+ gmail_lowercase: true,
+ // Removes dots from the local part of the email address, as that's ignored by GMail
+ gmail_remove_dots: true,
+ // Removes the subaddress (e.g. "+foo") from the email address
+ gmail_remove_subaddress: true,
+ // Conversts the googlemail.com domain to gmail.com
+ gmail_convert_googlemaildotcom: true,
+ // The following conversions are specific to Outlook.com / Windows Live / Hotmail
+ // Lowercases the local part of the Outlook.com address (known to be case-insensitive)
+ outlookdotcom_lowercase: true,
+ // Removes the subaddress (e.g. "+foo") from the email address
+ outlookdotcom_remove_subaddress: true,
+ // The following conversions are specific to Yahoo
+ // Lowercases the local part of the Yahoo address (known to be case-insensitive)
+ yahoo_lowercase: true,
+ // Removes the subaddress (e.g. "-foo") from the email address
+ yahoo_remove_subaddress: true,
+ // The following conversions are specific to Yandex
+ // Lowercases the local part of the Yandex address (known to be case-insensitive)
+ yandex_lowercase: true,
+ // The following conversions are specific to iCloud
+ // Lowercases the local part of the iCloud address (known to be case-insensitive)
+ icloud_lowercase: true,
+ // Removes the subaddress (e.g. "+foo") from the email address
+ icloud_remove_subaddress: true
+ }; // List of domains used by iCloud
+
+ var icloud_domains = ['icloud.com', 'me.com']; // List of domains used by Outlook.com and its predecessors
+ // This list is likely incomplete.
+ // Partial reference:
+ // https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/
+
+ var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; // List of domains used by Yahoo Mail
+ // This list is likely incomplete
+
+ var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; // List of domains used by yandex.ru
+
+ var yandex_domains = ['yandex.ru', 'yandex.ua', 'yandex.kz', 'yandex.com', 'yandex.by', 'ya.ru']; // replace single dots, but not multiple consecutive dots
+
+ function dotsReplacer(match) {
+ if (match.length > 1) {
+ return match;
+ }
+
+ return '';
+ }
+
+ function normalizeEmail(email, options) {
+ options = (0, _merge.default)(options, default_normalize_email_options);
+ var raw_parts = email.split('@');
+ var domain = raw_parts.pop();
+ var user = raw_parts.join('@');
+ var parts = [user, domain]; // The domain is always lowercased, as it's case-insensitive per RFC 1035
+
+ parts[1] = parts[1].toLowerCase();
+
+ if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {
+ // Address is GMail
+ if (options.gmail_remove_subaddress) {
+ parts[0] = parts[0].split('+')[0];
+ }
+
+ if (options.gmail_remove_dots) {
+ // this does not replace consecutive dots like example..email@gmail.com
+ parts[0] = parts[0].replace(/\.+/g, dotsReplacer);
+ }
+
+ if (!parts[0].length) {
+ return false;
+ }
+
+ if (options.all_lowercase || options.gmail_lowercase) {
+ parts[0] = parts[0].toLowerCase();
+ }
+
+ parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1];
+ } else if (icloud_domains.indexOf(parts[1]) >= 0) {
+ // Address is iCloud
+ if (options.icloud_remove_subaddress) {
+ parts[0] = parts[0].split('+')[0];
+ }
+
+ if (!parts[0].length) {
+ return false;
+ }
+
+ if (options.all_lowercase || options.icloud_lowercase) {
+ parts[0] = parts[0].toLowerCase();
+ }
+ } else if (outlookdotcom_domains.indexOf(parts[1]) >= 0) {
+ // Address is Outlook.com
+ if (options.outlookdotcom_remove_subaddress) {
+ parts[0] = parts[0].split('+')[0];
+ }
+
+ if (!parts[0].length) {
+ return false;
+ }
+
+ if (options.all_lowercase || options.outlookdotcom_lowercase) {
+ parts[0] = parts[0].toLowerCase();
+ }
+ } else if (yahoo_domains.indexOf(parts[1]) >= 0) {
+ // Address is Yahoo
+ if (options.yahoo_remove_subaddress) {
+ var components = parts[0].split('-');
+ parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0];
+ }
+
+ if (!parts[0].length) {
+ return false;
+ }
+
+ if (options.all_lowercase || options.yahoo_lowercase) {
+ parts[0] = parts[0].toLowerCase();
+ }
+ } else if (yandex_domains.indexOf(parts[1]) >= 0) {
+ if (options.all_lowercase || options.yandex_lowercase) {
+ parts[0] = parts[0].toLowerCase();
+ }
+
+ parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preferred
+ } else if (options.all_lowercase) {
+ // Any other address
+ parts[0] = parts[0].toLowerCase();
+ }
+
+ return parts.join('@');
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (normalizeEmail, normalizeEmailExports));
+ return normalizeEmailExports;
+}
+
+var isSlugExports = {};
+var isSlug = {
+ get exports(){ return isSlugExports; },
+ set exports(v){ isSlugExports = v; },
+};
+
+var hasRequiredIsSlug;
+
+function requireIsSlug () {
+ if (hasRequiredIsSlug) return isSlugExports;
+ hasRequiredIsSlug = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isSlug;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var charsetRegex = /^[^\s-_](?!.*?[-_]{2,})[a-z0-9-\\][^\s]*[^-_\s]$/;
+
+ function isSlug(str) {
+ (0, _assertString.default)(str);
+ return charsetRegex.test(str);
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isSlug, isSlugExports));
+ return isSlugExports;
+}
+
+var isLicensePlateExports = {};
+var isLicensePlate = {
+ get exports(){ return isLicensePlateExports; },
+ set exports(v){ isLicensePlateExports = v; },
+};
+
+var hasRequiredIsLicensePlate;
+
+function requireIsLicensePlate () {
+ if (hasRequiredIsLicensePlate) return isLicensePlateExports;
+ hasRequiredIsLicensePlate = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isLicensePlate;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var validators = {
+ 'cs-CZ': function csCZ(str) {
+ return /^(([ABCDEFHIJKLMNPRSTUVXYZ]|[0-9])-?){5,8}$/.test(str);
+ },
+ 'de-DE': function deDE(str) {
+ return /^((A|AA|AB|AC|AE|AH|AK|AM|AN|AÖ|AP|AS|AT|AU|AW|AZ|B|BA|BB|BC|BE|BF|BH|BI|BK|BL|BM|BN|BO|BÖ|BS|BT|BZ|C|CA|CB|CE|CO|CR|CW|D|DA|DD|DE|DH|DI|DL|DM|DN|DO|DU|DW|DZ|E|EA|EB|ED|EE|EF|EG|EH|EI|EL|EM|EN|ER|ES|EU|EW|F|FB|FD|FF|FG|FI|FL|FN|FO|FR|FS|FT|FÜ|FW|FZ|G|GA|GC|GD|GE|GF|GG|GI|GK|GL|GM|GN|GÖ|GP|GR|GS|GT|GÜ|GV|GW|GZ|H|HA|HB|HC|HD|HE|HF|HG|HH|HI|HK|HL|HM|HN|HO|HP|HR|HS|HU|HV|HX|HY|HZ|IK|IL|IN|IZ|J|JE|JL|K|KA|KB|KC|KE|KF|KG|KH|KI|KK|KL|KM|KN|KO|KR|KS|KT|KU|KW|KY|L|LA|LB|LC|LD|LF|LG|LH|LI|LL|LM|LN|LÖ|LP|LR|LU|M|MA|MB|MC|MD|ME|MG|MH|MI|MK|ML|MM|MN|MO|MQ|MR|MS|MÜ|MW|MY|MZ|N|NB|ND|NE|NF|NH|NI|NK|NM|NÖ|NP|NR|NT|NU|NW|NY|NZ|OA|OB|OC|OD|OE|OF|OG|OH|OK|OL|OP|OS|OZ|P|PA|PB|PE|PF|PI|PL|PM|PN|PR|PS|PW|PZ|R|RA|RC|RD|RE|RG|RH|RI|RL|RM|RN|RO|RP|RS|RT|RU|RV|RW|RZ|S|SB|SC|SE|SG|SI|SK|SL|SM|SN|SO|SP|SR|ST|SU|SW|SY|SZ|TE|TF|TG|TO|TP|TR|TS|TT|TÜ|ÜB|UE|UH|UL|UM|UN|V|VB|VG|VK|VR|VS|W|WA|WB|WE|WF|WI|WK|WL|WM|WN|WO|WR|WS|WT|WÜ|WW|WZ|Z|ZE|ZI|ZP|ZR|ZW|ZZ)[- ]?[A-Z]{1,2}[- ]?\d{1,4}|(ABG|ABI|AIB|AIC|ALF|ALZ|ANA|ANG|ANK|APD|ARN|ART|ASL|ASZ|AUR|AZE|BAD|BAR|BBG|BCH|BED|BER|BGD|BGL|BID|BIN|BIR|BIT|BIW|BKS|BLB|BLK|BNA|BOG|BOH|BOR|BOT|BRA|BRB|BRG|BRK|BRL|BRV|BSB|BSK|BTF|BÜD|BUL|BÜR|BÜS|BÜZ|CAS|CHA|CLP|CLZ|COC|COE|CUX|DAH|DAN|DAU|DBR|DEG|DEL|DGF|DIL|DIN|DIZ|DKB|DLG|DON|DUD|DÜW|EBE|EBN|EBS|ECK|EIC|EIL|EIN|EIS|EMD|EMS|ERB|ERH|ERK|ERZ|ESB|ESW|FDB|FDS|FEU|FFB|FKB|FLÖ|FOR|FRG|FRI|FRW|FTL|FÜS|GAN|GAP|GDB|GEL|GEO|GER|GHA|GHC|GLA|GMN|GNT|GOA|GOH|GRA|GRH|GRI|GRM|GRZ|GTH|GUB|GUN|GVM|HAB|HAL|HAM|HAS|HBN|HBS|HCH|HDH|HDL|HEB|HEF|HEI|HER|HET|HGN|HGW|HHM|HIG|HIP|HMÜ|HOG|HOH|HOL|HOM|HOR|HÖS|HOT|HRO|HSK|HST|HVL|HWI|IGB|ILL|JÜL|KEH|KEL|KEM|KIB|KLE|KLZ|KÖN|KÖT|KÖZ|KRU|KÜN|KUS|KYF|LAN|LAU|LBS|LBZ|LDK|LDS|LEO|LER|LEV|LIB|LIF|LIP|LÖB|LOS|LRO|LSZ|LÜN|LUP|LWL|MAB|MAI|MAK|MAL|MED|MEG|MEI|MEK|MEL|MER|MET|MGH|MGN|MHL|MIL|MKK|MOD|MOL|MON|MOS|MSE|MSH|MSP|MST|MTK|MTL|MÜB|MÜR|MYK|MZG|NAB|NAI|NAU|NDH|NEA|NEB|NEC|NEN|NES|NEW|NMB|NMS|NOH|NOL|NOM|NOR|NVP|NWM|OAL|OBB|OBG|OCH|OHA|ÖHR|OHV|OHZ|OPR|OSL|OVI|OVL|OVP|PAF|PAN|PAR|PCH|PEG|PIR|PLÖ|PRÜ|QFT|QLB|RDG|REG|REH|REI|RID|RIE|ROD|ROF|ROK|ROL|ROS|ROT|ROW|RSL|RÜD|RÜG|SAB|SAD|SAN|SAW|SBG|SBK|SCZ|SDH|SDL|SDT|SEB|SEE|SEF|SEL|SFB|SFT|SGH|SHA|SHG|SHK|SHL|SIG|SIM|SLE|SLF|SLK|SLN|SLS|SLÜ|SLZ|SMÜ|SOB|SOG|SOK|SÖM|SON|SPB|SPN|SRB|SRO|STA|STB|STD|STE|STL|SUL|SÜW|SWA|SZB|TBB|TDO|TET|TIR|TÖL|TUT|UEM|UER|UFF|USI|VAI|VEC|VER|VIB|VIE|VIT|VOH|WAF|WAK|WAN|WAR|WAT|WBS|WDA|WEL|WEN|WER|WES|WHV|WIL|WIS|WIT|WIZ|WLG|WMS|WND|WOB|WOH|WOL|WOR|WOS|WRN|WSF|WST|WSW|WTL|WTM|WUG|WÜM|WUN|WUR|WZL|ZEL|ZIG)[- ]?(([A-Z][- ]?\d{1,4})|([A-Z]{2}[- ]?\d{1,3})))[- ]?(E|H)?$/.test(str);
+ },
+ 'de-LI': function deLI(str) {
+ return /^FL[- ]?\d{1,5}[UZ]?$/.test(str);
+ },
+ 'en-IN': function enIN(str) {
+ return /^[A-Z]{2}[ -]?[0-9]{1,2}(?:[ -]?[A-Z])(?:[ -]?[A-Z]*)?[ -]?[0-9]{4}$/.test(str);
+ },
+ 'es-AR': function esAR(str) {
+ return /^(([A-Z]{2} ?[0-9]{3} ?[A-Z]{2})|([A-Z]{3} ?[0-9]{3}))$/.test(str);
+ },
+ 'fi-FI': function fiFI(str) {
+ return /^(?=.{4,7})(([A-Z]{1,3}|[0-9]{1,3})[\s-]?([A-Z]{1,3}|[0-9]{1,5}))$/.test(str);
+ },
+ 'hu-HU': function huHU(str) {
+ return /^((((?!AAA)(([A-NPRSTVZWXY]{1})([A-PR-Z]{1})([A-HJ-NPR-Z]))|(A[ABC]I)|A[ABC]O|A[A-W]Q|BPI|BPO|UCO|UDO|XAO)-(?!000)\d{3})|(M\d{6})|((CK|DT|CD|HC|H[ABEFIKLMNPRSTVX]|MA|OT|R[A-Z]) \d{2}-\d{2})|(CD \d{3}-\d{3})|(C-(C|X) \d{4})|(X-(A|B|C) \d{4})|(([EPVZ]-\d{5}))|(S A[A-Z]{2} \d{2})|(SP \d{2}-\d{2}))$/.test(str);
+ },
+ 'pt-BR': function ptBR(str) {
+ return /^[A-Z]{3}[ -]?[0-9][A-Z][0-9]{2}|[A-Z]{3}[ -]?[0-9]{4}$/.test(str);
+ },
+ 'pt-PT': function ptPT(str) {
+ return /^([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})[ -·]?([A-Z]{2}|[0-9]{2})$/.test(str);
+ },
+ 'sq-AL': function sqAL(str) {
+ return /^[A-Z]{2}[- ]?((\d{3}[- ]?(([A-Z]{2})|T))|(R[- ]?\d{3}))$/.test(str);
+ },
+ 'sv-SE': function svSE(str) {
+ return /^[A-HJ-PR-UW-Z]{3} ?[\d]{2}[A-HJ-PR-UW-Z1-9]$|(^[A-ZÅÄÖ ]{2,7}$)/.test(str.trim());
+ }
+ };
+
+ function isLicensePlate(str, locale) {
+ (0, _assertString.default)(str);
+
+ if (locale in validators) {
+ return validators[locale](str);
+ } else if (locale === 'any') {
+ for (var key in validators) {
+ /* eslint guard-for-in: 0 */
+ var validator = validators[key];
+
+ if (validator(str)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ throw new Error("Invalid locale '".concat(locale, "'"));
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isLicensePlate, isLicensePlateExports));
+ return isLicensePlateExports;
+}
+
+var isStrongPasswordExports = {};
+var isStrongPassword = {
+ get exports(){ return isStrongPasswordExports; },
+ set exports(v){ isStrongPasswordExports = v; },
+};
+
+var hasRequiredIsStrongPassword;
+
+function requireIsStrongPassword () {
+ if (hasRequiredIsStrongPassword) return isStrongPasswordExports;
+ hasRequiredIsStrongPassword = 1;
+ (function (module, exports) {
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = isStrongPassword;
+
+ var _merge = _interopRequireDefault(requireMerge());
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var upperCaseRegex = /^[A-Z]$/;
+ var lowerCaseRegex = /^[a-z]$/;
+ var numberRegex = /^[0-9]$/;
+ var symbolRegex = /^[-#!$@£%^&*()_+|~=`{}\[\]:";'<>?,.\/ ]$/;
+ var defaultOptions = {
+ minLength: 8,
+ minLowercase: 1,
+ minUppercase: 1,
+ minNumbers: 1,
+ minSymbols: 1,
+ returnScore: false,
+ pointsPerUnique: 1,
+ pointsPerRepeat: 0.5,
+ pointsForContainingLower: 10,
+ pointsForContainingUpper: 10,
+ pointsForContainingNumber: 10,
+ pointsForContainingSymbol: 10
+ };
+ /* Counts number of occurrences of each char in a string
+ * could be moved to util/ ?
+ */
+
+ function countChars(str) {
+ var result = {};
+ Array.from(str).forEach(function (char) {
+ var curVal = result[char];
+
+ if (curVal) {
+ result[char] += 1;
+ } else {
+ result[char] = 1;
+ }
+ });
+ return result;
+ }
+ /* Return information about a password */
+
+
+ function analyzePassword(password) {
+ var charMap = countChars(password);
+ var analysis = {
+ length: password.length,
+ uniqueChars: Object.keys(charMap).length,
+ uppercaseCount: 0,
+ lowercaseCount: 0,
+ numberCount: 0,
+ symbolCount: 0
+ };
+ Object.keys(charMap).forEach(function (char) {
+ /* istanbul ignore else */
+ if (upperCaseRegex.test(char)) {
+ analysis.uppercaseCount += charMap[char];
+ } else if (lowerCaseRegex.test(char)) {
+ analysis.lowercaseCount += charMap[char];
+ } else if (numberRegex.test(char)) {
+ analysis.numberCount += charMap[char];
+ } else if (symbolRegex.test(char)) {
+ analysis.symbolCount += charMap[char];
+ }
+ });
+ return analysis;
+ }
+
+ function scorePassword(analysis, scoringOptions) {
+ var points = 0;
+ points += analysis.uniqueChars * scoringOptions.pointsPerUnique;
+ points += (analysis.length - analysis.uniqueChars) * scoringOptions.pointsPerRepeat;
+
+ if (analysis.lowercaseCount > 0) {
+ points += scoringOptions.pointsForContainingLower;
+ }
+
+ if (analysis.uppercaseCount > 0) {
+ points += scoringOptions.pointsForContainingUpper;
+ }
+
+ if (analysis.numberCount > 0) {
+ points += scoringOptions.pointsForContainingNumber;
+ }
+
+ if (analysis.symbolCount > 0) {
+ points += scoringOptions.pointsForContainingSymbol;
+ }
+
+ return points;
+ }
+
+ function isStrongPassword(str) {
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
+ (0, _assertString.default)(str);
+ var analysis = analyzePassword(str);
+ options = (0, _merge.default)(options || {}, defaultOptions);
+
+ if (options.returnScore) {
+ return scorePassword(analysis, options);
+ }
+
+ return analysis.length >= options.minLength && analysis.lowercaseCount >= options.minLowercase && analysis.uppercaseCount >= options.minUppercase && analysis.numberCount >= options.minNumbers && analysis.symbolCount >= options.minSymbols;
+ }
+
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (isStrongPassword, isStrongPasswordExports));
+ return isStrongPasswordExports;
+}
+
+var isVAT = {};
+
+var hasRequiredIsVAT;
+
+function requireIsVAT () {
+ if (hasRequiredIsVAT) return isVAT;
+ hasRequiredIsVAT = 1;
+
+ 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); }
+
+ Object.defineProperty(isVAT, "__esModule", {
+ value: true
+ });
+ isVAT.default = isVAT$1;
+ isVAT.vatMatchers = void 0;
+
+ var _assertString = _interopRequireDefault(requireAssertString());
+
+ var algorithms = _interopRequireWildcard(requireAlgorithms());
+
+ function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
+
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var PT = function PT(str) {
+ var match = str.match(/^(PT)?(\d{9})$/);
+
+ if (!match) {
+ return false;
+ }
+
+ var tin = match[2];
+ var checksum = 11 - algorithms.reverseMultiplyAndSum(tin.split('').slice(0, 8).map(function (a) {
+ return parseInt(a, 10);
+ }), 9) % 11;
+
+ if (checksum > 9) {
+ return parseInt(tin[8], 10) === 0;
+ }
+
+ return checksum === parseInt(tin[8], 10);
+ };
+
+ var vatMatchers = {
+ /**
+ * European Union VAT identification numbers
+ */
+ AT: function AT(str) {
+ return /^(AT)?U\d{8}$/.test(str);
+ },
+ BE: function BE(str) {
+ return /^(BE)?\d{10}$/.test(str);
+ },
+ BG: function BG(str) {
+ return /^(BG)?\d{9,10}$/.test(str);
+ },
+ HR: function HR(str) {
+ return /^(HR)?\d{11}$/.test(str);
+ },
+ CY: function CY(str) {
+ return /^(CY)?\w{9}$/.test(str);
+ },
+ CZ: function CZ(str) {
+ return /^(CZ)?\d{8,10}$/.test(str);
+ },
+ DK: function DK(str) {
+ return /^(DK)?\d{8}$/.test(str);
+ },
+ EE: function EE(str) {
+ return /^(EE)?\d{9}$/.test(str);
+ },
+ FI: function FI(str) {
+ return /^(FI)?\d{8}$/.test(str);
+ },
+ FR: function FR(str) {
+ return /^(FR)?\w{2}\d{9}$/.test(str);
+ },
+ DE: function DE(str) {
+ return /^(DE)?\d{9}$/.test(str);
+ },
+ EL: function EL(str) {
+ return /^(EL)?\d{9}$/.test(str);
+ },
+ HU: function HU(str) {
+ return /^(HU)?\d{8}$/.test(str);
+ },
+ IE: function IE(str) {
+ return /^(IE)?\d{7}\w{1}(W)?$/.test(str);
+ },
+ IT: function IT(str) {
+ return /^(IT)?\d{11}$/.test(str);
+ },
+ LV: function LV(str) {
+ return /^(LV)?\d{11}$/.test(str);
+ },
+ LT: function LT(str) {
+ return /^(LT)?\d{9,12}$/.test(str);
+ },
+ LU: function LU(str) {
+ return /^(LU)?\d{8}$/.test(str);
+ },
+ MT: function MT(str) {
+ return /^(MT)?\d{8}$/.test(str);
+ },
+ NL: function NL(str) {
+ return /^(NL)?\d{9}B\d{2}$/.test(str);
+ },
+ PL: function PL(str) {
+ return /^(PL)?(\d{10}|(\d{3}-\d{3}-\d{2}-\d{2})|(\d{3}-\d{2}-\d{2}-\d{3}))$/.test(str);
+ },
+ PT: PT,
+ RO: function RO(str) {
+ return /^(RO)?\d{2,10}$/.test(str);
+ },
+ SK: function SK(str) {
+ return /^(SK)?\d{10}$/.test(str);
+ },
+ SI: function SI(str) {
+ return /^(SI)?\d{8}$/.test(str);
+ },
+ ES: function ES(str) {
+ return /^(ES)?\w\d{7}[A-Z]$/.test(str);
+ },
+ SE: function SE(str) {
+ return /^(SE)?\d{12}$/.test(str);
+ },
+
+ /**
+ * VAT numbers of non-EU countries
+ */
+ AL: function AL(str) {
+ return /^(AL)?\w{9}[A-Z]$/.test(str);
+ },
+ MK: function MK(str) {
+ return /^(MK)?\d{13}$/.test(str);
+ },
+ AU: function AU(str) {
+ return /^(AU)?\d{11}$/.test(str);
+ },
+ BY: function BY(str) {
+ return /^(УНП )?\d{9}$/.test(str);
+ },
+ CA: function CA(str) {
+ return /^(CA)?\d{9}$/.test(str);
+ },
+ IS: function IS(str) {
+ return /^(IS)?\d{5,6}$/.test(str);
+ },
+ IN: function IN(str) {
+ return /^(IN)?\d{15}$/.test(str);
+ },
+ ID: function ID(str) {
+ return /^(ID)?(\d{15}|(\d{2}.\d{3}.\d{3}.\d{1}-\d{3}.\d{3}))$/.test(str);
+ },
+ IL: function IL(str) {
+ return /^(IL)?\d{9}$/.test(str);
+ },
+ KZ: function KZ(str) {
+ return /^(KZ)?\d{9}$/.test(str);
+ },
+ NZ: function NZ(str) {
+ return /^(NZ)?\d{9}$/.test(str);
+ },
+ NG: function NG(str) {
+ return /^(NG)?(\d{12}|(\d{8}-\d{4}))$/.test(str);
+ },
+ NO: function NO(str) {
+ return /^(NO)?\d{9}MVA$/.test(str);
+ },
+ PH: function PH(str) {
+ return /^(PH)?(\d{12}|\d{3} \d{3} \d{3} \d{3})$/.test(str);
+ },
+ RU: function RU(str) {
+ return /^(RU)?(\d{10}|\d{12})$/.test(str);
+ },
+ SM: function SM(str) {
+ return /^(SM)?\d{5}$/.test(str);
+ },
+ SA: function SA(str) {
+ return /^(SA)?\d{15}$/.test(str);
+ },
+ RS: function RS(str) {
+ return /^(RS)?\d{9}$/.test(str);
+ },
+ CH: function CH(str) {
+ return /^(CH)?(\d{6}|\d{9}|(\d{3}.\d{3})|(\d{3}.\d{3}.\d{3}))(TVA|MWST|IVA)$/.test(str);
+ },
+ TR: function TR(str) {
+ return /^(TR)?\d{10}$/.test(str);
+ },
+ UA: function UA(str) {
+ return /^(UA)?\d{12}$/.test(str);
+ },
+ GB: function GB(str) {
+ return /^GB((\d{3} \d{4} ([0-8][0-9]|9[0-6]))|(\d{9} \d{3})|(((GD[0-4])|(HA[5-9]))[0-9]{2}))$/.test(str);
+ },
+ UZ: function UZ(str) {
+ return /^(UZ)?\d{9}$/.test(str);
+ },
+
+ /**
+ * VAT numbers of Latin American countries
+ */
+ AR: function AR(str) {
+ return /^(AR)?\d{11}$/.test(str);
+ },
+ BO: function BO(str) {
+ return /^(BO)?\d{7}$/.test(str);
+ },
+ BR: function BR(str) {
+ return /^(BR)?((\d{2}.\d{3}.\d{3}\/\d{4}-\d{2})|(\d{3}.\d{3}.\d{3}-\d{2}))$/.test(str);
+ },
+ CL: function CL(str) {
+ return /^(CL)?\d{8}-\d{1}$/.test(str);
+ },
+ CO: function CO(str) {
+ return /^(CO)?\d{10}$/.test(str);
+ },
+ CR: function CR(str) {
+ return /^(CR)?\d{9,12}$/.test(str);
+ },
+ EC: function EC(str) {
+ return /^(EC)?\d{13}$/.test(str);
+ },
+ SV: function SV(str) {
+ return /^(SV)?\d{4}-\d{6}-\d{3}-\d{1}$/.test(str);
+ },
+ GT: function GT(str) {
+ return /^(GT)?\d{7}-\d{1}$/.test(str);
+ },
+ HN: function HN(str) {
+ return /^(HN)?$/.test(str);
+ },
+ MX: function MX(str) {
+ return /^(MX)?\w{3,4}\d{6}\w{3}$/.test(str);
+ },
+ NI: function NI(str) {
+ return /^(NI)?\d{3}-\d{6}-\d{4}\w{1}$/.test(str);
+ },
+ PA: function PA(str) {
+ return /^(PA)?$/.test(str);
+ },
+ PY: function PY(str) {
+ return /^(PY)?\d{6,8}-\d{1}$/.test(str);
+ },
+ PE: function PE(str) {
+ return /^(PE)?\d{11}$/.test(str);
+ },
+ DO: function DO(str) {
+ return /^(DO)?(\d{11}|(\d{3}-\d{7}-\d{1})|[1,4,5]{1}\d{8}|([1,4,5]{1})-\d{2}-\d{5}-\d{1})$/.test(str);
+ },
+ UY: function UY(str) {
+ return /^(UY)?\d{12}$/.test(str);
+ },
+ VE: function VE(str) {
+ return /^(VE)?[J,G,V,E]{1}-(\d{9}|(\d{8}-\d{1}))$/.test(str);
+ }
+ };
+ isVAT.vatMatchers = vatMatchers;
+
+ function isVAT$1(str, countryCode) {
+ (0, _assertString.default)(str);
+ (0, _assertString.default)(countryCode);
+
+ if (countryCode in vatMatchers) {
+ return vatMatchers[countryCode](str);
+ }
+
+ throw new Error("Invalid country code: '".concat(countryCode, "'"));
+ }
+ return isVAT;
+}
+
+var hasRequiredValidator;
+
+function requireValidator () {
+ if (hasRequiredValidator) return validatorExports;
+ hasRequiredValidator = 1;
+ (function (module, exports) {
+
+ 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); }
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports.default = void 0;
+
+ var _toDate = _interopRequireDefault(requireToDate());
+
+ var _toFloat = _interopRequireDefault(requireToFloat());
+
+ var _toInt = _interopRequireDefault(requireToInt());
+
+ var _toBoolean = _interopRequireDefault(requireToBoolean());
+
+ var _equals = _interopRequireDefault(requireEquals());
+
+ var _contains = _interopRequireDefault(requireContains());
+
+ var _matches = _interopRequireDefault(requireMatches());
+
+ var _isEmail = _interopRequireDefault(requireIsEmail());
+
+ var _isURL = _interopRequireDefault(requireIsURL());
+
+ var _isMACAddress = _interopRequireDefault(requireIsMACAddress());
+
+ var _isIP = _interopRequireDefault(requireIsIP());
+
+ var _isIPRange = _interopRequireDefault(requireIsIPRange());
+
+ var _isFQDN = _interopRequireDefault(requireIsFQDN());
+
+ var _isDate = _interopRequireDefault(requireIsDate());
+
+ var _isTime = _interopRequireDefault(requireIsTime());
+
+ var _isBoolean = _interopRequireDefault(requireIsBoolean());
+
+ var _isLocale = _interopRequireDefault(requireIsLocale());
+
+ var _isAlpha = _interopRequireWildcard(requireIsAlpha());
+
+ var _isAlphanumeric = _interopRequireWildcard(requireIsAlphanumeric());
+
+ var _isNumeric = _interopRequireDefault(requireIsNumeric());
+
+ var _isPassportNumber = _interopRequireDefault(requireIsPassportNumber());
+
+ var _isPort = _interopRequireDefault(requireIsPort());
+
+ var _isLowercase = _interopRequireDefault(requireIsLowercase());
+
+ var _isUppercase = _interopRequireDefault(requireIsUppercase());
+
+ var _isIMEI = _interopRequireDefault(requireIsIMEI());
+
+ var _isAscii = _interopRequireDefault(requireIsAscii());
+
+ var _isFullWidth = _interopRequireDefault(requireIsFullWidth());
+
+ var _isHalfWidth = _interopRequireDefault(requireIsHalfWidth());
+
+ var _isVariableWidth = _interopRequireDefault(requireIsVariableWidth());
+
+ var _isMultibyte = _interopRequireDefault(requireIsMultibyte());
+
+ var _isSemVer = _interopRequireDefault(requireIsSemVer());
+
+ var _isSurrogatePair = _interopRequireDefault(requireIsSurrogatePair());
+
+ var _isInt = _interopRequireDefault(requireIsInt());
+
+ var _isFloat = _interopRequireWildcard(requireIsFloat());
+
+ var _isDecimal = _interopRequireDefault(requireIsDecimal());
+
+ var _isHexadecimal = _interopRequireDefault(requireIsHexadecimal());
+
+ var _isOctal = _interopRequireDefault(requireIsOctal());
+
+ var _isDivisibleBy = _interopRequireDefault(requireIsDivisibleBy());
+
+ var _isHexColor = _interopRequireDefault(requireIsHexColor());
+
+ var _isRgbColor = _interopRequireDefault(requireIsRgbColor());
+
+ var _isHSL = _interopRequireDefault(requireIsHSL());
+
+ var _isISRC = _interopRequireDefault(requireIsISRC());
+
+ var _isIBAN = _interopRequireWildcard(requireIsIBAN());
+
+ var _isBIC = _interopRequireDefault(requireIsBIC());
+
+ var _isMD = _interopRequireDefault(requireIsMD5());
+
+ var _isHash = _interopRequireDefault(requireIsHash());
+
+ var _isJWT = _interopRequireDefault(requireIsJWT());
+
+ var _isJSON = _interopRequireDefault(requireIsJSON());
+
+ var _isEmpty = _interopRequireDefault(requireIsEmpty());
+
+ var _isLength = _interopRequireDefault(requireIsLength());
+
+ var _isByteLength = _interopRequireDefault(requireIsByteLength());
+
+ var _isUUID = _interopRequireDefault(requireIsUUID());
+
+ var _isMongoId = _interopRequireDefault(requireIsMongoId());
+
+ var _isAfter = _interopRequireDefault(requireIsAfter());
+
+ var _isBefore = _interopRequireDefault(requireIsBefore());
+
+ var _isIn = _interopRequireDefault(requireIsIn());
+
+ var _isLuhnNumber = _interopRequireDefault(requireIsLuhnNumber());
+
+ var _isCreditCard = _interopRequireDefault(requireIsCreditCard());
+
+ var _isIdentityCard = _interopRequireDefault(requireIsIdentityCard());
+
+ var _isEAN = _interopRequireDefault(requireIsEAN());
+
+ var _isISIN = _interopRequireDefault(requireIsISIN());
+
+ var _isISBN = _interopRequireDefault(requireIsISBN());
+
+ var _isISSN = _interopRequireDefault(requireIsISSN());
+
+ var _isTaxID = _interopRequireDefault(requireIsTaxID());
+
+ var _isMobilePhone = _interopRequireWildcard(requireIsMobilePhone());
+
+ var _isEthereumAddress = _interopRequireDefault(requireIsEthereumAddress());
+
+ var _isCurrency = _interopRequireDefault(requireIsCurrency());
+
+ var _isBtcAddress = _interopRequireDefault(requireIsBtcAddress());
+
+ var _isISO = _interopRequireDefault(requireIsISO6391());
+
+ var _isISO2 = _interopRequireDefault(requireIsISO8601());
+
+ var _isRFC = _interopRequireDefault(requireIsRFC3339());
+
+ var _isISO31661Alpha = _interopRequireDefault(requireIsISO31661Alpha2());
+
+ var _isISO31661Alpha2 = _interopRequireDefault(requireIsISO31661Alpha3());
+
+ var _isISO3 = _interopRequireDefault(requireIsISO4217());
+
+ var _isBase = _interopRequireDefault(requireIsBase32());
+
+ var _isBase2 = _interopRequireDefault(requireIsBase58());
+
+ var _isBase3 = _interopRequireDefault(requireIsBase64());
+
+ var _isDataURI = _interopRequireDefault(requireIsDataURI());
+
+ var _isMagnetURI = _interopRequireDefault(requireIsMagnetURI());
+
+ var _isMimeType = _interopRequireDefault(requireIsMimeType());
+
+ var _isLatLong = _interopRequireDefault(requireIsLatLong());
+
+ var _isPostalCode = _interopRequireWildcard(requireIsPostalCode());
+
+ var _ltrim = _interopRequireDefault(requireLtrim());
+
+ var _rtrim = _interopRequireDefault(requireRtrim());
+
+ var _trim = _interopRequireDefault(requireTrim());
+
+ var _escape = _interopRequireDefault(require_escape());
+
+ var _unescape = _interopRequireDefault(require_unescape());
+
+ var _stripLow = _interopRequireDefault(requireStripLow());
+
+ var _whitelist = _interopRequireDefault(requireWhitelist());
+
+ var _blacklist = _interopRequireDefault(requireBlacklist());
+
+ var _isWhitelisted = _interopRequireDefault(requireIsWhitelisted());
+
+ var _normalizeEmail = _interopRequireDefault(requireNormalizeEmail());
+
+ var _isSlug = _interopRequireDefault(requireIsSlug());
+
+ var _isLicensePlate = _interopRequireDefault(requireIsLicensePlate());
+
+ var _isStrongPassword = _interopRequireDefault(requireIsStrongPassword());
+
+ var _isVAT = _interopRequireDefault(requireIsVAT());
+
+ function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
+
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+ var version = '13.9.0';
+ var validator = {
+ version: version,
+ toDate: _toDate.default,
+ toFloat: _toFloat.default,
+ toInt: _toInt.default,
+ toBoolean: _toBoolean.default,
+ equals: _equals.default,
+ contains: _contains.default,
+ matches: _matches.default,
+ isEmail: _isEmail.default,
+ isURL: _isURL.default,
+ isMACAddress: _isMACAddress.default,
+ isIP: _isIP.default,
+ isIPRange: _isIPRange.default,
+ isFQDN: _isFQDN.default,
+ isBoolean: _isBoolean.default,
+ isIBAN: _isIBAN.default,
+ isBIC: _isBIC.default,
+ isAlpha: _isAlpha.default,
+ isAlphaLocales: _isAlpha.locales,
+ isAlphanumeric: _isAlphanumeric.default,
+ isAlphanumericLocales: _isAlphanumeric.locales,
+ isNumeric: _isNumeric.default,
+ isPassportNumber: _isPassportNumber.default,
+ isPort: _isPort.default,
+ isLowercase: _isLowercase.default,
+ isUppercase: _isUppercase.default,
+ isAscii: _isAscii.default,
+ isFullWidth: _isFullWidth.default,
+ isHalfWidth: _isHalfWidth.default,
+ isVariableWidth: _isVariableWidth.default,
+ isMultibyte: _isMultibyte.default,
+ isSemVer: _isSemVer.default,
+ isSurrogatePair: _isSurrogatePair.default,
+ isInt: _isInt.default,
+ isIMEI: _isIMEI.default,
+ isFloat: _isFloat.default,
+ isFloatLocales: _isFloat.locales,
+ isDecimal: _isDecimal.default,
+ isHexadecimal: _isHexadecimal.default,
+ isOctal: _isOctal.default,
+ isDivisibleBy: _isDivisibleBy.default,
+ isHexColor: _isHexColor.default,
+ isRgbColor: _isRgbColor.default,
+ isHSL: _isHSL.default,
+ isISRC: _isISRC.default,
+ isMD5: _isMD.default,
+ isHash: _isHash.default,
+ isJWT: _isJWT.default,
+ isJSON: _isJSON.default,
+ isEmpty: _isEmpty.default,
+ isLength: _isLength.default,
+ isLocale: _isLocale.default,
+ isByteLength: _isByteLength.default,
+ isUUID: _isUUID.default,
+ isMongoId: _isMongoId.default,
+ isAfter: _isAfter.default,
+ isBefore: _isBefore.default,
+ isIn: _isIn.default,
+ isLuhnNumber: _isLuhnNumber.default,
+ isCreditCard: _isCreditCard.default,
+ isIdentityCard: _isIdentityCard.default,
+ isEAN: _isEAN.default,
+ isISIN: _isISIN.default,
+ isISBN: _isISBN.default,
+ isISSN: _isISSN.default,
+ isMobilePhone: _isMobilePhone.default,
+ isMobilePhoneLocales: _isMobilePhone.locales,
+ isPostalCode: _isPostalCode.default,
+ isPostalCodeLocales: _isPostalCode.locales,
+ isEthereumAddress: _isEthereumAddress.default,
+ isCurrency: _isCurrency.default,
+ isBtcAddress: _isBtcAddress.default,
+ isISO6391: _isISO.default,
+ isISO8601: _isISO2.default,
+ isRFC3339: _isRFC.default,
+ isISO31661Alpha2: _isISO31661Alpha.default,
+ isISO31661Alpha3: _isISO31661Alpha2.default,
+ isISO4217: _isISO3.default,
+ isBase32: _isBase.default,
+ isBase58: _isBase2.default,
+ isBase64: _isBase3.default,
+ isDataURI: _isDataURI.default,
+ isMagnetURI: _isMagnetURI.default,
+ isMimeType: _isMimeType.default,
+ isLatLong: _isLatLong.default,
+ ltrim: _ltrim.default,
+ rtrim: _rtrim.default,
+ trim: _trim.default,
+ escape: _escape.default,
+ unescape: _unescape.default,
+ stripLow: _stripLow.default,
+ whitelist: _whitelist.default,
+ blacklist: _blacklist.default,
+ isWhitelisted: _isWhitelisted.default,
+ normalizeEmail: _normalizeEmail.default,
+ toString: toString,
+ isSlug: _isSlug.default,
+ isStrongPassword: _isStrongPassword.default,
+ isTaxID: _isTaxID.default,
+ isDate: _isDate.default,
+ isTime: _isTime.default,
+ isLicensePlate: _isLicensePlate.default,
+ isVAT: _isVAT.default,
+ ibanLocales: _isIBAN.locales
+ };
+ var _default = validator;
+ exports.default = _default;
+ module.exports = exports.default;
+ module.exports.default = exports.default;
+} (validator$1, validatorExports));
+ return validatorExports;
+}
+
+var eventsource;
+var hasRequiredEventsource;
+
+function requireEventsource () {
+ if (hasRequiredEventsource) return eventsource;
+ hasRequiredEventsource = 1;
+ var parse = Url$2.parse;
+ var events = require$$0$f;
+ var https = https$3;
+ var http = http$6;
+ var util = require$$1$7;
+
+ var httpsOptions = [
+ 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',
+ 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity'
+ ];
+
+ var bom = [239, 187, 191];
+ var colon = 58;
+ var space = 32;
+ var lineFeed = 10;
+ var carriageReturn = 13;
+
+ function hasBom (buf) {
+ return bom.every(function (charCode, index) {
+ return buf[index] === charCode
+ })
+ }
+
+ /**
+ * Creates a new EventSource object
+ *
+ * @param {String} url the URL to which to connect
+ * @param {Object} [eventSourceInitDict] extra init params. See README for details.
+ * @api public
+ **/
+ function EventSource (url, eventSourceInitDict) {
+ var readyState = EventSource.CONNECTING;
+ var headers = eventSourceInitDict && eventSourceInitDict.headers;
+ var hasNewOrigin = false;
+ Object.defineProperty(this, 'readyState', {
+ get: function () {
+ return readyState
+ }
+ });
+
+ Object.defineProperty(this, 'url', {
+ get: function () {
+ return url
+ }
+ });
+
+ var self = this;
+ self.reconnectInterval = 1000;
+ self.connectionInProgress = false;
+
+ function onConnectionClosed (message) {
+ if (readyState === EventSource.CLOSED) return
+ readyState = EventSource.CONNECTING;
+ _emit('error', new Event('error', {message: message}));
+
+ // The url may have been changed by a temporary redirect. If that's the case,
+ // revert it now, and flag that we are no longer pointing to a new origin
+ if (reconnectUrl) {
+ url = reconnectUrl;
+ reconnectUrl = null;
+ hasNewOrigin = false;
+ }
+ setTimeout(function () {
+ if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
+ return
+ }
+ self.connectionInProgress = true;
+ connect();
+ }, self.reconnectInterval);
+ }
+
+ var req;
+ var lastEventId = '';
+ if (headers && headers['Last-Event-ID']) {
+ lastEventId = headers['Last-Event-ID'];
+ delete headers['Last-Event-ID'];
+ }
+
+ var discardTrailingNewline = false;
+ var data = '';
+ var eventName = '';
+
+ var reconnectUrl = null;
+
+ function connect () {
+ var options = parse(url);
+ var isSecure = options.protocol === 'https:';
+ options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
+ if (lastEventId) options.headers['Last-Event-ID'] = lastEventId;
+ if (headers) {
+ var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers;
+ for (var i in reqHeaders) {
+ var header = reqHeaders[i];
+ if (header) {
+ options.headers[i] = header;
+ }
+ }
+ }
+
+ // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
+ // but for now exists as a backwards-compatibility layer
+ options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized);
+
+ if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {
+ options.createConnection = eventSourceInitDict.createConnection;
+ }
+
+ // If specify http proxy, make the request to sent to the proxy server,
+ // and include the original url in path and Host headers
+ var useProxy = eventSourceInitDict && eventSourceInitDict.proxy;
+ if (useProxy) {
+ var proxy = parse(eventSourceInitDict.proxy);
+ isSecure = proxy.protocol === 'https:';
+
+ options.protocol = isSecure ? 'https:' : 'http:';
+ options.path = url;
+ options.headers.Host = options.host;
+ options.hostname = proxy.hostname;
+ options.host = proxy.host;
+ options.port = proxy.port;
+ }
+
+ // If https options are specified, merge them into the request options
+ if (eventSourceInitDict && eventSourceInitDict.https) {
+ for (var optName in eventSourceInitDict.https) {
+ if (httpsOptions.indexOf(optName) === -1) {
+ continue
+ }
+
+ var option = eventSourceInitDict.https[optName];
+ if (option !== undefined) {
+ options[optName] = option;
+ }
+ }
+ }
+
+ // Pass this on to the XHR
+ if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {
+ options.withCredentials = eventSourceInitDict.withCredentials;
+ }
+
+ req = (isSecure ? https : http).request(options, function (res) {
+ self.connectionInProgress = false;
+ // Handle HTTP errors
+ if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
+ _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}));
+ onConnectionClosed();
+ return
+ }
+
+ // Handle HTTP redirects
+ if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
+ var location = res.headers.location;
+ if (!location) {
+ // Server sent redirect response without Location header.
+ _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}));
+ return
+ }
+ var prevOrigin = getOrigin(url);
+ var nextOrigin = getOrigin(location);
+ hasNewOrigin = prevOrigin !== nextOrigin;
+ if (res.statusCode === 307) reconnectUrl = url;
+ url = location;
+ process.nextTick(connect);
+ return
+ }
+
+ if (res.statusCode !== 200) {
+ _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}));
+ return self.close()
+ }
+
+ readyState = EventSource.OPEN;
+ res.on('close', function () {
+ res.removeAllListeners('close');
+ res.removeAllListeners('end');
+ onConnectionClosed();
+ });
+
+ res.on('end', function () {
+ res.removeAllListeners('close');
+ res.removeAllListeners('end');
+ onConnectionClosed();
+ });
+ _emit('open', new Event('open'));
+
+ // text/event-stream parser adapted from webkit's
+ // Source/WebCore/page/EventSource.cpp
+ var isFirst = true;
+ var buf;
+ var startingPos = 0;
+ var startingFieldLength = -1;
+ res.on('data', function (chunk) {
+ buf = buf ? Buffer.concat([buf, chunk]) : chunk;
+ if (isFirst && hasBom(buf)) {
+ buf = buf.slice(bom.length);
+ }
+
+ isFirst = false;
+ var pos = 0;
+ var length = buf.length;
+
+ while (pos < length) {
+ if (discardTrailingNewline) {
+ if (buf[pos] === lineFeed) {
+ ++pos;
+ }
+ discardTrailingNewline = false;
+ }
+
+ var lineLength = -1;
+ var fieldLength = startingFieldLength;
+ var c;
+
+ for (var i = startingPos; lineLength < 0 && i < length; ++i) {
+ c = buf[i];
+ if (c === colon) {
+ if (fieldLength < 0) {
+ fieldLength = i - pos;
+ }
+ } else if (c === carriageReturn) {
+ discardTrailingNewline = true;
+ lineLength = i - pos;
+ } else if (c === lineFeed) {
+ lineLength = i - pos;
+ }
+ }
+
+ if (lineLength < 0) {
+ startingPos = length - pos;
+ startingFieldLength = fieldLength;
+ break
+ } else {
+ startingPos = 0;
+ startingFieldLength = -1;
+ }
+
+ parseEventStreamLine(buf, pos, fieldLength, lineLength);
+
+ pos += lineLength + 1;
+ }
+
+ if (pos === length) {
+ buf = void 0;
+ } else if (pos > 0) {
+ buf = buf.slice(pos);
+ }
+ });
+ });
+
+ req.on('error', function (err) {
+ self.connectionInProgress = false;
+ onConnectionClosed(err.message);
+ });
+
+ if (req.setNoDelay) req.setNoDelay(true);
+ req.end();
+ }
+
+ connect();
+
+ function _emit () {
+ if (self.listeners(arguments[0]).length > 0) {
+ self.emit.apply(self, arguments);
+ }
+ }
+
+ this._close = function () {
+ if (readyState === EventSource.CLOSED) return
+ readyState = EventSource.CLOSED;
+ if (req.abort) req.abort();
+ if (req.xhr && req.xhr.abort) req.xhr.abort();
+ };
+
+ function parseEventStreamLine (buf, pos, fieldLength, lineLength) {
+ if (lineLength === 0) {
+ if (data.length > 0) {
+ var type = eventName || 'message';
+ _emit(type, new MessageEvent(type, {
+ data: data.slice(0, -1), // remove trailing newline
+ lastEventId: lastEventId,
+ origin: getOrigin(url)
+ }));
+ data = '';
+ }
+ eventName = void 0;
+ } else if (fieldLength > 0) {
+ var noValue = fieldLength < 0;
+ var step = 0;
+ var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString();
+
+ if (noValue) {
+ step = lineLength;
+ } else if (buf[pos + fieldLength + 1] !== space) {
+ step = fieldLength + 1;
+ } else {
+ step = fieldLength + 2;
+ }
+ pos += step;
+
+ var valueLength = lineLength - step;
+ var value = buf.slice(pos, pos + valueLength).toString();
+
+ if (field === 'data') {
+ data += value + '\n';
+ } else if (field === 'event') {
+ eventName = value;
+ } else if (field === 'id') {
+ lastEventId = value;
+ } else if (field === 'retry') {
+ var retry = parseInt(value, 10);
+ if (!Number.isNaN(retry)) {
+ self.reconnectInterval = retry;
+ }
+ }
+ }
+ }
+ }
+
+ eventsource = EventSource;
+
+ util.inherits(EventSource, events.EventEmitter);
+ EventSource.prototype.constructor = EventSource; // make stacktraces readable
+
+ ['open', 'error', 'message'].forEach(function (method) {
+ Object.defineProperty(EventSource.prototype, 'on' + method, {
+ /**
+ * Returns the current listener
+ *
+ * @return {Mixed} the set function or undefined
+ * @api private
+ */
+ get: function get () {
+ var listener = this.listeners(method)[0];
+ return listener ? (listener._listener ? listener._listener : listener) : undefined
+ },
+
+ /**
+ * Start listening for events
+ *
+ * @param {Function} listener the listener
+ * @return {Mixed} the set function or undefined
+ * @api private
+ */
+ set: function set (listener) {
+ this.removeAllListeners(method);
+ this.addEventListener(method, listener);
+ }
+ });
+ });
+
+ /**
+ * Ready states
+ */
+ Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0});
+ Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1});
+ Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2});
+
+ EventSource.prototype.CONNECTING = 0;
+ EventSource.prototype.OPEN = 1;
+ EventSource.prototype.CLOSED = 2;
+
+ /**
+ * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
+ * @api public
+ */
+ EventSource.prototype.close = function () {
+ this._close();
+ };
+
+ /**
+ * Emulates the W3C Browser based WebSocket interface using addEventListener.
+ *
+ * @param {String} type A string representing the event type to listen out for
+ * @param {Function} listener callback
+ * @see https://developer.mozilla.org/en/DOM/element.addEventListener
+ * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
+ * @api public
+ */
+ EventSource.prototype.addEventListener = function addEventListener (type, listener) {
+ if (typeof listener === 'function') {
+ // store a reference so we can return the original function again
+ listener._listener = listener;
+ this.on(type, listener);
+ }
+ };
+
+ /**
+ * Emulates the W3C Browser based WebSocket interface using dispatchEvent.
+ *
+ * @param {Event} event An event to be dispatched
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
+ * @api public
+ */
+ EventSource.prototype.dispatchEvent = function dispatchEvent (event) {
+ if (!event.type) {
+ throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')
+ }
+ // if event is instance of an CustomEvent (or has 'details' property),
+ // send the detail object as the payload for the event
+ this.emit(event.type, event.detail);
+ };
+
+ /**
+ * Emulates the W3C Browser based WebSocket interface using removeEventListener.
+ *
+ * @param {String} type A string representing the event type to remove
+ * @param {Function} listener callback
+ * @see https://developer.mozilla.org/en/DOM/element.removeEventListener
+ * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
+ * @api public
+ */
+ EventSource.prototype.removeEventListener = function removeEventListener (type, listener) {
+ if (typeof listener === 'function') {
+ listener._listener = undefined;
+ this.removeListener(type, listener);
+ }
+ };
+
+ /**
+ * W3C Event
+ *
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
+ * @api private
+ */
+ function Event (type, optionalProperties) {
+ Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
+ if (optionalProperties) {
+ for (var f in optionalProperties) {
+ if (optionalProperties.hasOwnProperty(f)) {
+ Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true });
+ }
+ }
+ }
+ }
+
+ /**
+ * W3C MessageEvent
+ *
+ * @see http://www.w3.org/TR/webmessaging/#event-definitions
+ * @api private
+ */
+ function MessageEvent (type, eventInitDict) {
+ Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
+ for (var f in eventInitDict) {
+ if (eventInitDict.hasOwnProperty(f)) {
+ Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true });
+ }
+ }
+ }
+
+ /**
+ * Returns a new object of headers that does not include any authorization and cookie headers
+ *
+ * @param {Object} headers An object of headers ({[headerName]: headerValue})
+ * @return {Object} a new object of headers
+ * @api private
+ */
+ function removeUnsafeHeaders (headers) {
+ var safe = {};
+ for (var key in headers) {
+ if (/^(cookie|authorization)$/i.test(key)) {
+ continue
+ }
+
+ safe[key] = headers[key];
+ }
+
+ return safe
+ }
+
+ /**
+ * Transform an URL to a valid origin value.
+ *
+ * @param {String|Object} url URL to transform to it's origin.
+ * @returns {String} The origin.
+ * @api private
+ */
+ function getOrigin (url) {
+ if (typeof url === 'string') url = parse(url);
+ if (!url.protocol || !url.hostname) return 'null'
+ return (url.protocol + '//' + url.host).toLowerCase()
+ }
+ return eventsource;
+}
+
+var nodeExports = {};
+var node = {
+ get exports(){ return nodeExports; },
+ set exports(v){ nodeExports = v; },
+};
+
+var Mime_1;
+var hasRequiredMime$1;
+
+function requireMime$1 () {
+ if (hasRequiredMime$1) return Mime_1;
+ hasRequiredMime$1 = 1;
+
+ /**
+ * @param typeMap [Object] Map of MIME type -> Array[extensions]
+ * @param ...
+ */
+ function Mime() {
+ this._types = Object.create(null);
+ this._extensions = Object.create(null);
+
+ for (let i = 0; i < arguments.length; i++) {
+ this.define(arguments[i]);
+ }
+
+ this.define = this.define.bind(this);
+ this.getType = this.getType.bind(this);
+ this.getExtension = this.getExtension.bind(this);
+ }
+
+ /**
+ * Define mimetype -> extension mappings. Each key is a mime-type that maps
+ * to an array of extensions associated with the type. The first extension is
+ * used as the default extension for the type.
+ *
+ * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
+ *
+ * If a type declares an extension that has already been defined, an error will
+ * be thrown. To suppress this error and force the extension to be associated
+ * with the new type, pass `force`=true. Alternatively, you may prefix the
+ * extension with "*" to map the type to extension, without mapping the
+ * extension to the type.
+ *
+ * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
+ *
+ *
+ * @param map (Object) type definitions
+ * @param force (Boolean) if true, force overriding of existing definitions
+ */
+ Mime.prototype.define = function(typeMap, force) {
+ for (let type in typeMap) {
+ let extensions = typeMap[type].map(function(t) {
+ return t.toLowerCase();
+ });
+ type = type.toLowerCase();
+
+ for (let i = 0; i < extensions.length; i++) {
+ const ext = extensions[i];
+
+ // '*' prefix = not the preferred type for this extension. So fixup the
+ // extension, and skip it.
+ if (ext[0] === '*') {
+ continue;
+ }
+
+ if (!force && (ext in this._types)) {
+ throw new Error(
+ 'Attempt to change mapping for "' + ext +
+ '" extension from "' + this._types[ext] + '" to "' + type +
+ '". Pass `force=true` to allow this, otherwise remove "' + ext +
+ '" from the list of extensions for "' + type + '".'
+ );
+ }
+
+ this._types[ext] = type;
+ }
+
+ // Use first extension as default
+ if (force || !this._extensions[type]) {
+ const ext = extensions[0];
+ this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
+ }
+ }
+ };
+
+ /**
+ * Lookup a mime type based on extension
+ */
+ Mime.prototype.getType = function(path) {
+ path = String(path);
+ let last = path.replace(/^.*[/\\]/, '').toLowerCase();
+ let ext = last.replace(/^.*\./, '').toLowerCase();
+
+ let hasPath = last.length < path.length;
+ let hasDot = ext.length < last.length - 1;
+
+ return (hasDot || !hasPath) && this._types[ext] || null;
+ };
+
+ /**
+ * Return file extension associated with a mime type
+ */
+ Mime.prototype.getExtension = function(type) {
+ type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
+ return type && this._extensions[type.toLowerCase()] || null;
+ };
+
+ Mime_1 = Mime;
+ return Mime_1;
+}
+
+var standard$1;
+var hasRequiredStandard;
+
+function requireStandard () {
+ if (hasRequiredStandard) return standard$1;
+ hasRequiredStandard = 1;
+ standard$1 = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
+ return standard$1;
+}
+
+var other;
+var hasRequiredOther;
+
+function requireOther () {
+ if (hasRequiredOther) return other;
+ hasRequiredOther = 1;
+ other = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};
+ return other;
+}
+
+var mime;
+var hasRequiredMime;
+
+function requireMime () {
+ if (hasRequiredMime) return mime;
+ hasRequiredMime = 1;
+
+ let Mime = requireMime$1();
+ mime = new Mime(requireStandard(), requireOther());
+ return mime;
+}
+
+var delayed_stream;
+var hasRequiredDelayed_stream;
+
+function requireDelayed_stream () {
+ if (hasRequiredDelayed_stream) return delayed_stream;
+ hasRequiredDelayed_stream = 1;
+ var Stream = Stream$2.Stream;
+ var util = require$$1$7;
+
+ delayed_stream = DelayedStream;
+ function DelayedStream() {
+ this.source = null;
+ this.dataSize = 0;
+ this.maxDataSize = 1024 * 1024;
+ this.pauseStream = true;
+
+ this._maxDataSizeExceeded = false;
+ this._released = false;
+ this._bufferedEvents = [];
+ }
+ util.inherits(DelayedStream, Stream);
+
+ DelayedStream.create = function(source, options) {
+ var delayedStream = new this();
+
+ options = options || {};
+ for (var option in options) {
+ delayedStream[option] = options[option];
+ }
+
+ delayedStream.source = source;
+
+ var realEmit = source.emit;
+ source.emit = function() {
+ delayedStream._handleEmit(arguments);
+ return realEmit.apply(source, arguments);
+ };
+
+ source.on('error', function() {});
+ if (delayedStream.pauseStream) {
+ source.pause();
+ }
+
+ return delayedStream;
+ };
+
+ Object.defineProperty(DelayedStream.prototype, 'readable', {
+ configurable: true,
+ enumerable: true,
+ get: function() {
+ return this.source.readable;
+ }
+ });
+
+ DelayedStream.prototype.setEncoding = function() {
+ return this.source.setEncoding.apply(this.source, arguments);
+ };
+
+ DelayedStream.prototype.resume = function() {
+ if (!this._released) {
+ this.release();
+ }
+
+ this.source.resume();
+ };
+
+ DelayedStream.prototype.pause = function() {
+ this.source.pause();
+ };
+
+ DelayedStream.prototype.release = function() {
+ this._released = true;
+
+ this._bufferedEvents.forEach(function(args) {
+ this.emit.apply(this, args);
+ }.bind(this));
+ this._bufferedEvents = [];
+ };
+
+ DelayedStream.prototype.pipe = function() {
+ var r = Stream.prototype.pipe.apply(this, arguments);
+ this.resume();
+ return r;
+ };
+
+ DelayedStream.prototype._handleEmit = function(args) {
+ if (this._released) {
+ this.emit.apply(this, args);
+ return;
+ }
+
+ if (args[0] === 'data') {
+ this.dataSize += args[1].length;
+ this._checkIfMaxDataSizeExceeded();
+ }
+
+ this._bufferedEvents.push(args);
+ };
+
+ DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
+ if (this._maxDataSizeExceeded) {
+ return;
+ }
+
+ if (this.dataSize <= this.maxDataSize) {
+ return;
+ }
+
+ this._maxDataSizeExceeded = true;
+ var message =
+ 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
+ this.emit('error', new Error(message));
+ };
+ return delayed_stream;
+}
+
+var combined_stream;
+var hasRequiredCombined_stream;
+
+function requireCombined_stream () {
+ if (hasRequiredCombined_stream) return combined_stream;
+ hasRequiredCombined_stream = 1;
+ var util = require$$1$7;
+ var Stream = Stream$2.Stream;
+ var DelayedStream = requireDelayed_stream();
+
+ combined_stream = CombinedStream;
+ function CombinedStream() {
+ this.writable = false;
+ this.readable = true;
+ this.dataSize = 0;
+ this.maxDataSize = 2 * 1024 * 1024;
+ this.pauseStreams = true;
+
+ this._released = false;
+ this._streams = [];
+ this._currentStream = null;
+ this._insideLoop = false;
+ this._pendingNext = false;
+ }
+ util.inherits(CombinedStream, Stream);
+
+ CombinedStream.create = function(options) {
+ var combinedStream = new this();
+
+ options = options || {};
+ for (var option in options) {
+ combinedStream[option] = options[option];
+ }
+
+ return combinedStream;
+ };
+
+ CombinedStream.isStreamLike = function(stream) {
+ return (typeof stream !== 'function')
+ && (typeof stream !== 'string')
+ && (typeof stream !== 'boolean')
+ && (typeof stream !== 'number')
+ && (!Buffer.isBuffer(stream));
+ };
+
+ CombinedStream.prototype.append = function(stream) {
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+
+ if (isStreamLike) {
+ if (!(stream instanceof DelayedStream)) {
+ var newStream = DelayedStream.create(stream, {
+ maxDataSize: Infinity,
+ pauseStream: this.pauseStreams,
+ });
+ stream.on('data', this._checkDataSize.bind(this));
+ stream = newStream;
+ }
+
+ this._handleErrors(stream);
+
+ if (this.pauseStreams) {
+ stream.pause();
+ }
+ }
+
+ this._streams.push(stream);
+ return this;
+ };
+
+ CombinedStream.prototype.pipe = function(dest, options) {
+ Stream.prototype.pipe.call(this, dest, options);
+ this.resume();
+ return dest;
+ };
+
+ CombinedStream.prototype._getNext = function() {
+ this._currentStream = null;
+
+ if (this._insideLoop) {
+ this._pendingNext = true;
+ return; // defer call
+ }
+
+ this._insideLoop = true;
+ try {
+ do {
+ this._pendingNext = false;
+ this._realGetNext();
+ } while (this._pendingNext);
+ } finally {
+ this._insideLoop = false;
+ }
+ };
+
+ CombinedStream.prototype._realGetNext = function() {
+ var stream = this._streams.shift();
+
+
+ if (typeof stream == 'undefined') {
+ this.end();
+ return;
+ }
+
+ if (typeof stream !== 'function') {
+ this._pipeNext(stream);
+ return;
+ }
+
+ var getStream = stream;
+ getStream(function(stream) {
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+ if (isStreamLike) {
+ stream.on('data', this._checkDataSize.bind(this));
+ this._handleErrors(stream);
+ }
+
+ this._pipeNext(stream);
+ }.bind(this));
+ };
+
+ CombinedStream.prototype._pipeNext = function(stream) {
+ this._currentStream = stream;
+
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+ if (isStreamLike) {
+ stream.on('end', this._getNext.bind(this));
+ stream.pipe(this, {end: false});
+ return;
+ }
+
+ var value = stream;
+ this.write(value);
+ this._getNext();
+ };
+
+ CombinedStream.prototype._handleErrors = function(stream) {
+ var self = this;
+ stream.on('error', function(err) {
+ self._emitError(err);
+ });
+ };
+
+ CombinedStream.prototype.write = function(data) {
+ this.emit('data', data);
+ };
+
+ CombinedStream.prototype.pause = function() {
+ if (!this.pauseStreams) {
+ return;
+ }
+
+ if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
+ this.emit('pause');
+ };
+
+ CombinedStream.prototype.resume = function() {
+ if (!this._released) {
+ this._released = true;
+ this.writable = true;
+ this._getNext();
+ }
+
+ if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
+ this.emit('resume');
+ };
+
+ CombinedStream.prototype.end = function() {
+ this._reset();
+ this.emit('end');
+ };
+
+ CombinedStream.prototype.destroy = function() {
+ this._reset();
+ this.emit('close');
+ };
+
+ CombinedStream.prototype._reset = function() {
+ this.writable = false;
+ this._streams = [];
+ this._currentStream = null;
+ };
+
+ CombinedStream.prototype._checkDataSize = function() {
+ this._updateDataSize();
+ if (this.dataSize <= this.maxDataSize) {
+ return;
+ }
+
+ var message =
+ 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
+ this._emitError(new Error(message));
+ };
+
+ CombinedStream.prototype._updateDataSize = function() {
+ this.dataSize = 0;
+
+ var self = this;
+ this._streams.forEach(function(stream) {
+ if (!stream.dataSize) {
+ return;
+ }
+
+ self.dataSize += stream.dataSize;
+ });
+
+ if (this._currentStream && this._currentStream.dataSize) {
+ this.dataSize += this._currentStream.dataSize;
+ }
+ };
+
+ CombinedStream.prototype._emitError = function(err) {
+ this._reset();
+ this.emit('error', err);
+ };
+ return combined_stream;
+}
+
+var defer_1;
+var hasRequiredDefer;
+
+function requireDefer () {
+ if (hasRequiredDefer) return defer_1;
+ hasRequiredDefer = 1;
+ defer_1 = defer;
+
+ /**
+ * Runs provided function on next iteration of the event loop
+ *
+ * @param {function} fn - function to run
+ */
+ function defer(fn)
+ {
+ var nextTick = typeof setImmediate == 'function'
+ ? setImmediate
+ : (
+ typeof process == 'object' && typeof process.nextTick == 'function'
+ ? process.nextTick
+ : null
+ );
+
+ if (nextTick)
+ {
+ nextTick(fn);
+ }
+ else
+ {
+ setTimeout(fn, 0);
+ }
+ }
+ return defer_1;
+}
+
+var async_1;
+var hasRequiredAsync;
+
+function requireAsync () {
+ if (hasRequiredAsync) return async_1;
+ hasRequiredAsync = 1;
+ var defer = requireDefer();
+
+ // API
+ async_1 = async;
+
+ /**
+ * Runs provided callback asynchronously
+ * even if callback itself is not
+ *
+ * @param {function} callback - callback to invoke
+ * @returns {function} - augmented callback
+ */
+ function async(callback)
+ {
+ var isAsync = false;
+
+ // check if async happened
+ defer(function() { isAsync = true; });
+
+ return function async_callback(err, result)
+ {
+ if (isAsync)
+ {
+ callback(err, result);
+ }
+ else
+ {
+ defer(function nextTick_callback()
+ {
+ callback(err, result);
+ });
+ }
+ };
+ }
+ return async_1;
+}
+
+var abort_1;
+var hasRequiredAbort;
+
+function requireAbort () {
+ if (hasRequiredAbort) return abort_1;
+ hasRequiredAbort = 1;
+ // API
+ abort_1 = abort;
+
+ /**
+ * Aborts leftover active jobs
+ *
+ * @param {object} state - current state object
+ */
+ function abort(state)
+ {
+ Object.keys(state.jobs).forEach(clean.bind(state));
+
+ // reset leftover jobs
+ state.jobs = {};
+ }
+
+ /**
+ * Cleans up leftover job by invoking abort function for the provided job id
+ *
+ * @this state
+ * @param {string|number} key - job id to abort
+ */
+ function clean(key)
+ {
+ if (typeof this.jobs[key] == 'function')
+ {
+ this.jobs[key]();
+ }
+ }
+ return abort_1;
+}
+
+var iterate_1;
+var hasRequiredIterate;
+
+function requireIterate () {
+ if (hasRequiredIterate) return iterate_1;
+ hasRequiredIterate = 1;
+ var async = requireAsync()
+ , abort = requireAbort()
+ ;
+
+ // API
+ iterate_1 = iterate;
+
+ /**
+ * Iterates over each job object
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {object} state - current job status
+ * @param {function} callback - invoked when all elements processed
+ */
+ function iterate(list, iterator, state, callback)
+ {
+ // store current index
+ var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
+
+ state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
+ {
+ // don't repeat yourself
+ // skip secondary callbacks
+ if (!(key in state.jobs))
+ {
+ return;
+ }
+
+ // clean up jobs
+ delete state.jobs[key];
+
+ if (error)
+ {
+ // don't process rest of the results
+ // stop still active jobs
+ // and reset the list
+ abort(state);
+ }
+ else
+ {
+ state.results[key] = output;
+ }
+
+ // return salvaged results
+ callback(error, state.results);
+ });
+ }
+
+ /**
+ * Runs iterator over provided job element
+ *
+ * @param {function} iterator - iterator to invoke
+ * @param {string|number} key - key/index of the element in the list of jobs
+ * @param {mixed} item - job description
+ * @param {function} callback - invoked after iterator is done with the job
+ * @returns {function|mixed} - job abort function or something else
+ */
+ function runJob(iterator, key, item, callback)
+ {
+ var aborter;
+
+ // allow shortcut if iterator expects only two arguments
+ if (iterator.length == 2)
+ {
+ aborter = iterator(item, async(callback));
+ }
+ // otherwise go with full three arguments
+ else
+ {
+ aborter = iterator(item, key, async(callback));
+ }
+
+ return aborter;
+ }
+ return iterate_1;
+}
+
+var state_1;
+var hasRequiredState;
+
+function requireState () {
+ if (hasRequiredState) return state_1;
+ hasRequiredState = 1;
+ // API
+ state_1 = state;
+
+ /**
+ * Creates initial state object
+ * for iteration over list
+ *
+ * @param {array|object} list - list to iterate over
+ * @param {function|null} sortMethod - function to use for keys sort,
+ * or `null` to keep them as is
+ * @returns {object} - initial state object
+ */
+ function state(list, sortMethod)
+ {
+ var isNamedList = !Array.isArray(list)
+ , initState =
+ {
+ index : 0,
+ keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
+ jobs : {},
+ results : isNamedList ? {} : [],
+ size : isNamedList ? Object.keys(list).length : list.length
+ }
+ ;
+
+ if (sortMethod)
+ {
+ // sort array keys based on it's values
+ // sort object's keys just on own merit
+ initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
+ {
+ return sortMethod(list[a], list[b]);
+ });
+ }
+
+ return initState;
+ }
+ return state_1;
+}
+
+var terminator_1;
+var hasRequiredTerminator;
+
+function requireTerminator () {
+ if (hasRequiredTerminator) return terminator_1;
+ hasRequiredTerminator = 1;
+ var abort = requireAbort()
+ , async = requireAsync()
+ ;
+
+ // API
+ terminator_1 = terminator;
+
+ /**
+ * Terminates jobs in the attached state context
+ *
+ * @this AsyncKitState#
+ * @param {function} callback - final callback to invoke after termination
+ */
+ function terminator(callback)
+ {
+ if (!Object.keys(this.jobs).length)
+ {
+ return;
+ }
+
+ // fast forward iteration index
+ this.index = this.size;
+
+ // abort jobs
+ abort(this);
+
+ // send back results we have so far
+ async(callback)(null, this.results);
+ }
+ return terminator_1;
+}
+
+var parallel_1;
+var hasRequiredParallel;
+
+function requireParallel () {
+ if (hasRequiredParallel) return parallel_1;
+ hasRequiredParallel = 1;
+ var iterate = requireIterate()
+ , initState = requireState()
+ , terminator = requireTerminator()
+ ;
+
+ // Public API
+ parallel_1 = parallel;
+
+ /**
+ * Runs iterator over provided array elements in parallel
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {function} callback - invoked when all elements processed
+ * @returns {function} - jobs terminator
+ */
+ function parallel(list, iterator, callback)
+ {
+ var state = initState(list);
+
+ while (state.index < (state['keyedList'] || list).length)
+ {
+ iterate(list, iterator, state, function(error, result)
+ {
+ if (error)
+ {
+ callback(error, result);
+ return;
+ }
+
+ // looks like it's the last one
+ if (Object.keys(state.jobs).length === 0)
+ {
+ callback(null, state.results);
+ return;
+ }
+ });
+
+ state.index++;
+ }
+
+ return terminator.bind(state, callback);
+ }
+ return parallel_1;
+}
+
+var serialOrderedExports = {};
+var serialOrdered = {
+ get exports(){ return serialOrderedExports; },
+ set exports(v){ serialOrderedExports = v; },
+};
+
+var hasRequiredSerialOrdered;
+
+function requireSerialOrdered () {
+ if (hasRequiredSerialOrdered) return serialOrderedExports;
+ hasRequiredSerialOrdered = 1;
+ var iterate = requireIterate()
+ , initState = requireState()
+ , terminator = requireTerminator()
+ ;
+
+ // Public API
+ serialOrdered.exports = serialOrdered$1;
+ // sorting helpers
+ serialOrderedExports.ascending = ascending;
+ serialOrderedExports.descending = descending;
+
+ /**
+ * Runs iterator over provided sorted array elements in series
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {function} sortMethod - custom sort function
+ * @param {function} callback - invoked when all elements processed
+ * @returns {function} - jobs terminator
+ */
+ function serialOrdered$1(list, iterator, sortMethod, callback)
+ {
+ var state = initState(list, sortMethod);
+
+ iterate(list, iterator, state, function iteratorHandler(error, result)
+ {
+ if (error)
+ {
+ callback(error, result);
+ return;
+ }
+
+ state.index++;
+
+ // are we there yet?
+ if (state.index < (state['keyedList'] || list).length)
+ {
+ iterate(list, iterator, state, iteratorHandler);
+ return;
+ }
+
+ // done here
+ callback(null, state.results);
+ });
+
+ return terminator.bind(state, callback);
+ }
+
+ /*
+ * -- Sort methods
+ */
+
+ /**
+ * sort helper to sort array elements in ascending order
+ *
+ * @param {mixed} a - an item to compare
+ * @param {mixed} b - an item to compare
+ * @returns {number} - comparison result
+ */
+ function ascending(a, b)
+ {
+ return a < b ? -1 : a > b ? 1 : 0;
+ }
+
+ /**
+ * sort helper to sort array elements in descending order
+ *
+ * @param {mixed} a - an item to compare
+ * @param {mixed} b - an item to compare
+ * @returns {number} - comparison result
+ */
+ function descending(a, b)
+ {
+ return -1 * ascending(a, b);
+ }
+ return serialOrderedExports;
+}
+
+var serial_1;
+var hasRequiredSerial;
+
+function requireSerial () {
+ if (hasRequiredSerial) return serial_1;
+ hasRequiredSerial = 1;
+ var serialOrdered = requireSerialOrdered();
+
+ // Public API
+ serial_1 = serial;
+
+ /**
+ * Runs iterator over provided array elements in series
+ *
+ * @param {array|object} list - array or object (named list) to iterate over
+ * @param {function} iterator - iterator to run
+ * @param {function} callback - invoked when all elements processed
+ * @returns {function} - jobs terminator
+ */
+ function serial(list, iterator, callback)
+ {
+ return serialOrdered(list, iterator, null, callback);
+ }
+ return serial_1;
+}
+
+var asynckit;
+var hasRequiredAsynckit;
+
+function requireAsynckit () {
+ if (hasRequiredAsynckit) return asynckit;
+ hasRequiredAsynckit = 1;
+ asynckit =
+ {
+ parallel : requireParallel(),
+ serial : requireSerial(),
+ serialOrdered : requireSerialOrdered()
+ };
+ return asynckit;
+}
+
+var populate;
+var hasRequiredPopulate;
+
+function requirePopulate () {
+ if (hasRequiredPopulate) return populate;
+ hasRequiredPopulate = 1;
+ // populates missing values
+ populate = function(dst, src) {
+
+ Object.keys(src).forEach(function(prop)
+ {
+ dst[prop] = dst[prop] || src[prop];
+ });
+
+ return dst;
+ };
+ return populate;
+}
+
+var form_data;
+var hasRequiredForm_data;
+
+function requireForm_data () {
+ if (hasRequiredForm_data) return form_data;
+ hasRequiredForm_data = 1;
+ var CombinedStream = requireCombined_stream();
+ var util = require$$1$7;
+ var path = require$$0$c;
+ var http = http$6;
+ var https = https$3;
+ var parseUrl = Url$2.parse;
+ var fs = require$$0$e;
+ var Stream = Stream$2.Stream;
+ var mime = mimeTypes;
+ var asynckit = requireAsynckit();
+ var populate = requirePopulate();
+
+ // Public API
+ form_data = FormData;
+
+ // make it a Stream
+ util.inherits(FormData, CombinedStream);
+
+ /**
+ * Create readable "multipart/form-data" streams.
+ * Can be used to submit forms
+ * and file uploads to other web applications.
+ *
+ * @constructor
+ * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
+ */
+ function FormData(options) {
+ if (!(this instanceof FormData)) {
+ return new FormData(options);
+ }
+
+ this._overheadLength = 0;
+ this._valueLength = 0;
+ this._valuesToMeasure = [];
+
+ CombinedStream.call(this);
+
+ options = options || {};
+ for (var option in options) {
+ this[option] = options[option];
+ }
+ }
+
+ FormData.LINE_BREAK = '\r\n';
+ FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
+
+ FormData.prototype.append = function(field, value, options) {
+
+ options = options || {};
+
+ // allow filename as single option
+ if (typeof options == 'string') {
+ options = {filename: options};
+ }
+
+ var append = CombinedStream.prototype.append.bind(this);
+
+ // all that streamy business can't handle numbers
+ if (typeof value == 'number') {
+ value = '' + value;
+ }
+
+ // https://github.com/felixge/node-form-data/issues/38
+ if (util.isArray(value)) {
+ // Please convert your array into string
+ // the way web server expects it
+ this._error(new Error('Arrays are not supported.'));
+ return;
+ }
+
+ var header = this._multiPartHeader(field, value, options);
+ var footer = this._multiPartFooter();
+
+ append(header);
+ append(value);
+ append(footer);
+
+ // pass along options.knownLength
+ this._trackLength(header, value, options);
+ };
+
+ FormData.prototype._trackLength = function(header, value, options) {
+ var valueLength = 0;
+
+ // used w/ getLengthSync(), when length is known.
+ // e.g. for streaming directly from a remote server,
+ // w/ a known file a size, and not wanting to wait for
+ // incoming file to finish to get its size.
+ if (options.knownLength != null) {
+ valueLength += +options.knownLength;
+ } else if (Buffer.isBuffer(value)) {
+ valueLength = value.length;
+ } else if (typeof value === 'string') {
+ valueLength = Buffer.byteLength(value);
+ }
+
+ this._valueLength += valueLength;
+
+ // @check why add CRLF? does this account for custom/multiple CRLFs?
+ this._overheadLength +=
+ Buffer.byteLength(header) +
+ FormData.LINE_BREAK.length;
+
+ // empty or either doesn't have path or not an http response or not a stream
+ if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) {
+ return;
+ }
+
+ // no need to bother with the length
+ if (!options.knownLength) {
+ this._valuesToMeasure.push(value);
+ }
+ };
+
+ FormData.prototype._lengthRetriever = function(value, callback) {
+
+ if (value.hasOwnProperty('fd')) {
+
+ // take read range into a account
+ // `end` = Infinity –> read file till the end
+ //
+ // TODO: Looks like there is bug in Node fs.createReadStream
+ // it doesn't respect `end` options without `start` options
+ // Fix it when node fixes it.
+ // https://github.com/joyent/node/issues/7819
+ if (value.end != undefined && value.end != Infinity && value.start != undefined) {
+
+ // when end specified
+ // no need to calculate range
+ // inclusive, starts with 0
+ callback(null, value.end + 1 - (value.start ? value.start : 0));
+
+ // not that fast snoopy
+ } else {
+ // still need to fetch file size from fs
+ fs.stat(value.path, function(err, stat) {
+
+ var fileSize;
+
+ if (err) {
+ callback(err);
+ return;
+ }
+
+ // update final size based on the range options
+ fileSize = stat.size - (value.start ? value.start : 0);
+ callback(null, fileSize);
+ });
+ }
+
+ // or http response
+ } else if (value.hasOwnProperty('httpVersion')) {
+ callback(null, +value.headers['content-length']);
+
+ // or request stream http://github.com/mikeal/request
+ } else if (value.hasOwnProperty('httpModule')) {
+ // wait till response come back
+ value.on('response', function(response) {
+ value.pause();
+ callback(null, +response.headers['content-length']);
+ });
+ value.resume();
+
+ // something else
+ } else {
+ callback('Unknown stream');
+ }
+ };
+
+ FormData.prototype._multiPartHeader = function(field, value, options) {
+ // custom header specified (as string)?
+ // it becomes responsible for boundary
+ // (e.g. to handle extra CRLFs on .NET servers)
+ if (typeof options.header == 'string') {
+ return options.header;
+ }
+
+ var contentDisposition = this._getContentDisposition(value, options);
+ var contentType = this._getContentType(value, options);
+
+ var contents = '';
+ var headers = {
+ // add custom disposition as third element or keep it two elements if not
+ 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
+ // if no content type. allow it to be empty array
+ 'Content-Type': [].concat(contentType || [])
+ };
+
+ // allow custom headers.
+ if (typeof options.header == 'object') {
+ populate(headers, options.header);
+ }
+
+ var header;
+ for (var prop in headers) {
+ if (!headers.hasOwnProperty(prop)) continue;
+ header = headers[prop];
+
+ // skip nullish headers.
+ if (header == null) {
+ continue;
+ }
+
+ // convert all headers to arrays.
+ if (!Array.isArray(header)) {
+ header = [header];
+ }
+
+ // add non-empty headers.
+ if (header.length) {
+ contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
+ }
+ }
+
+ return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
+ };
+
+ FormData.prototype._getContentDisposition = function(value, options) {
+
+ var filename
+ , contentDisposition
+ ;
+
+ if (typeof options.filepath === 'string') {
+ // custom filepath for relative paths
+ filename = path.normalize(options.filepath).replace(/\\/g, '/');
+ } else if (options.filename || value.name || value.path) {
+ // custom filename take precedence
+ // formidable and the browser add a name property
+ // fs- and request- streams have path property
+ filename = path.basename(options.filename || value.name || value.path);
+ } else if (value.readable && value.hasOwnProperty('httpVersion')) {
+ // or try http response
+ filename = path.basename(value.client._httpMessage.path || '');
+ }
+
+ if (filename) {
+ contentDisposition = 'filename="' + filename + '"';
+ }
+
+ return contentDisposition;
+ };
+
+ FormData.prototype._getContentType = function(value, options) {
+
+ // use custom content-type above all
+ var contentType = options.contentType;
+
+ // or try `name` from formidable, browser
+ if (!contentType && value.name) {
+ contentType = mime.lookup(value.name);
+ }
+
+ // or try `path` from fs-, request- streams
+ if (!contentType && value.path) {
+ contentType = mime.lookup(value.path);
+ }
+
+ // or if it's http-reponse
+ if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
+ contentType = value.headers['content-type'];
+ }
+
+ // or guess it from the filepath or filename
+ if (!contentType && (options.filepath || options.filename)) {
+ contentType = mime.lookup(options.filepath || options.filename);
+ }
+
+ // fallback to the default content type if `value` is not simple value
+ if (!contentType && typeof value == 'object') {
+ contentType = FormData.DEFAULT_CONTENT_TYPE;
+ }
+
+ return contentType;
+ };
+
+ FormData.prototype._multiPartFooter = function() {
+ return function(next) {
+ var footer = FormData.LINE_BREAK;
+
+ var lastPart = (this._streams.length === 0);
+ if (lastPart) {
+ footer += this._lastBoundary();
+ }
+
+ next(footer);
+ }.bind(this);
+ };
+
+ FormData.prototype._lastBoundary = function() {
+ return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
+ };
+
+ FormData.prototype.getHeaders = function(userHeaders) {
+ var header;
+ var formHeaders = {
+ 'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
+ };
+
+ for (header in userHeaders) {
+ if (userHeaders.hasOwnProperty(header)) {
+ formHeaders[header.toLowerCase()] = userHeaders[header];
+ }
+ }
+
+ return formHeaders;
+ };
+
+ FormData.prototype.setBoundary = function(boundary) {
+ this._boundary = boundary;
+ };
+
+ FormData.prototype.getBoundary = function() {
+ if (!this._boundary) {
+ this._generateBoundary();
+ }
+
+ return this._boundary;
+ };
+
+ FormData.prototype.getBuffer = function() {
+ var dataBuffer = new Buffer.alloc( 0 );
+ var boundary = this.getBoundary();
+
+ // Create the form content. Add Line breaks to the end of data.
+ for (var i = 0, len = this._streams.length; i < len; i++) {
+ if (typeof this._streams[i] !== 'function') {
+
+ // Add content to the buffer.
+ if(Buffer.isBuffer(this._streams[i])) {
+ dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
+ }else {
+ dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
+ }
+
+ // Add break after content.
+ if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
+ dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );
+ }
+ }
+ }
+
+ // Add the footer and return the Buffer object.
+ return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
+ };
+
+ FormData.prototype._generateBoundary = function() {
+ // This generates a 50 character boundary similar to those used by Firefox.
+ // They are optimized for boyer-moore parsing.
+ var boundary = '--------------------------';
+ for (var i = 0; i < 24; i++) {
+ boundary += Math.floor(Math.random() * 10).toString(16);
+ }
+
+ this._boundary = boundary;
+ };
+
+ // Note: getLengthSync DOESN'T calculate streams length
+ // As workaround one can calculate file size manually
+ // and add it as knownLength option
+ FormData.prototype.getLengthSync = function() {
+ var knownLength = this._overheadLength + this._valueLength;
+
+ // Don't get confused, there are 3 "internal" streams for each keyval pair
+ // so it basically checks if there is any value added to the form
+ if (this._streams.length) {
+ knownLength += this._lastBoundary().length;
+ }
+
+ // https://github.com/form-data/form-data/issues/40
+ if (!this.hasKnownLength()) {
+ // Some async length retrievers are present
+ // therefore synchronous length calculation is false.
+ // Please use getLength(callback) to get proper length
+ this._error(new Error('Cannot calculate proper length in synchronous way.'));
+ }
+
+ return knownLength;
+ };
+
+ // Public API to check if length of added values is known
+ // https://github.com/form-data/form-data/issues/196
+ // https://github.com/form-data/form-data/issues/262
+ FormData.prototype.hasKnownLength = function() {
+ var hasKnownLength = true;
+
+ if (this._valuesToMeasure.length) {
+ hasKnownLength = false;
+ }
+
+ return hasKnownLength;
+ };
+
+ FormData.prototype.getLength = function(cb) {
+ var knownLength = this._overheadLength + this._valueLength;
+
+ if (this._streams.length) {
+ knownLength += this._lastBoundary().length;
+ }
+
+ if (!this._valuesToMeasure.length) {
+ process.nextTick(cb.bind(this, null, knownLength));
+ return;
+ }
+
+ asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
+ if (err) {
+ cb(err);
+ return;
+ }
+
+ values.forEach(function(length) {
+ knownLength += length;
+ });
+
+ cb(null, knownLength);
+ });
+ };
+
+ FormData.prototype.submit = function(params, cb) {
+ var request
+ , options
+ , defaults = {method: 'post'}
+ ;
+
+ // parse provided url if it's string
+ // or treat it as options object
+ if (typeof params == 'string') {
+
+ params = parseUrl(params);
+ options = populate({
+ port: params.port,
+ path: params.pathname,
+ host: params.hostname,
+ protocol: params.protocol
+ }, defaults);
+
+ // use custom params
+ } else {
+
+ options = populate(params, defaults);
+ // if no port provided use default one
+ if (!options.port) {
+ options.port = options.protocol == 'https:' ? 443 : 80;
+ }
+ }
+
+ // put that good code in getHeaders to some use
+ options.headers = this.getHeaders(params.headers);
+
+ // https if specified, fallback to http in any other case
+ if (options.protocol == 'https:') {
+ request = https.request(options);
+ } else {
+ request = http.request(options);
+ }
+
+ // get content length and fire away
+ this.getLength(function(err, length) {
+ if (err && err !== 'Unknown stream') {
+ this._error(err);
+ return;
+ }
+
+ // add content length
+ if (length) {
+ request.setHeader('Content-Length', length);
+ }
+
+ this.pipe(request);
+ if (cb) {
+ var onResponse;
+
+ var callback = function (error, responce) {
+ request.removeListener('error', callback);
+ request.removeListener('response', onResponse);
+
+ return cb.call(this, error, responce);
+ };
+
+ onResponse = callback.bind(this, null);
+
+ request.on('error', callback);
+ request.on('response', onResponse);
+ }
+ }.bind(this));
+
+ return request;
+ };
+
+ FormData.prototype._error = function(err) {
+ if (!this.error) {
+ this.error = err;
+ this.pause();
+ this.emit('error', err);
+ }
+ };
+
+ FormData.prototype.toString = function () {
+ return '[object FormData]';
+ };
+ return form_data;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var PersistentFile_1;
+var hasRequiredPersistentFile;
+
+function requirePersistentFile () {
+ if (hasRequiredPersistentFile) return PersistentFile_1;
+ hasRequiredPersistentFile = 1;
+
+ const fs = require$$0$e;
+ const crypto = require$$0$j;
+ const { EventEmitter } = require$$0$f;
+
+ class PersistentFile extends EventEmitter {
+ constructor({ filepath, newFilename, originalFilename, mimetype, hashAlgorithm }) {
+ super();
+
+ this.lastModifiedDate = null;
+ Object.assign(this, { filepath, newFilename, originalFilename, mimetype, hashAlgorithm });
+
+ this.size = 0;
+ this._writeStream = null;
+
+ if (typeof this.hashAlgorithm === 'string') {
+ this.hash = crypto.createHash(this.hashAlgorithm);
+ } else {
+ this.hash = null;
+ }
+ }
+
+ open() {
+ this._writeStream = new fs.WriteStream(this.filepath);
+ this._writeStream.on('error', (err) => {
+ this.emit('error', err);
+ });
+ }
+
+ toJSON() {
+ const json = {
+ size: this.size,
+ filepath: this.filepath,
+ newFilename: this.newFilename,
+ mimetype: this.mimetype,
+ mtime: this.lastModifiedDate,
+ length: this.length,
+ originalFilename: this.originalFilename,
+ };
+ if (this.hash && this.hash !== '') {
+ json.hash = this.hash;
+ }
+ return json;
+ }
+
+ toString() {
+ return `PersistentFile: ${this.newFilename}, Original: ${this.originalFilename}, Path: ${this.filepath}`;
+ }
+
+ write(buffer, cb) {
+ if (this.hash) {
+ this.hash.update(buffer);
+ }
+
+ if (this._writeStream.closed) {
+ cb();
+ return;
+ }
+
+ this._writeStream.write(buffer, () => {
+ this.lastModifiedDate = new Date();
+ this.size += buffer.length;
+ this.emit('progress', this.size);
+ cb();
+ });
+ }
+
+ end(cb) {
+ if (this.hash) {
+ this.hash = this.hash.digest('hex');
+ }
+ this._writeStream.end(() => {
+ this.emit('end');
+ cb();
+ });
+ }
+
+ destroy() {
+ this._writeStream.destroy();
+ fs.unlink(this.filepath, () => {});
+ }
+ }
+
+ PersistentFile_1 = PersistentFile;
+ return PersistentFile_1;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var VolatileFile_1;
+var hasRequiredVolatileFile;
+
+function requireVolatileFile () {
+ if (hasRequiredVolatileFile) return VolatileFile_1;
+ hasRequiredVolatileFile = 1;
+
+ const crypto = require$$0$j;
+ const { EventEmitter } = require$$0$f;
+
+ class VolatileFile extends EventEmitter {
+ constructor({ filepath, newFilename, originalFilename, mimetype, hashAlgorithm, createFileWriteStream }) {
+ super();
+
+ this.lastModifiedDate = null;
+ Object.assign(this, { filepath, newFilename, originalFilename, mimetype, hashAlgorithm, createFileWriteStream });
+
+ this.size = 0;
+ this._writeStream = null;
+
+ if (typeof this.hashAlgorithm === 'string') {
+ this.hash = crypto.createHash(this.hashAlgorithm);
+ } else {
+ this.hash = null;
+ }
+ }
+
+ open() {
+ this._writeStream = this.createFileWriteStream(this);
+ this._writeStream.on('error', (err) => {
+ this.emit('error', err);
+ });
+ }
+
+ destroy() {
+ this._writeStream.destroy();
+ }
+
+ toJSON() {
+ const json = {
+ size: this.size,
+ newFilename: this.newFilename,
+ length: this.length,
+ originalFilename: this.originalFilename,
+ mimetype: this.mimetype,
+ };
+ if (this.hash && this.hash !== '') {
+ json.hash = this.hash;
+ }
+ return json;
+ }
+
+ toString() {
+ return `VolatileFile: ${this.originalFilename}`;
+ }
+
+ write(buffer, cb) {
+ if (this.hash) {
+ this.hash.update(buffer);
+ }
+
+ if (this._writeStream.closed || this._writeStream.destroyed) {
+ cb();
+ return;
+ }
+
+ this._writeStream.write(buffer, () => {
+ this.size += buffer.length;
+ this.emit('progress', this.size);
+ cb();
+ });
+ }
+
+ end(cb) {
+ if (this.hash) {
+ this.hash = this.hash.digest('hex');
+ }
+ this._writeStream.end(() => {
+ this.emit('end');
+ cb();
+ });
+ }
+ }
+
+ VolatileFile_1 = VolatileFile;
+ return VolatileFile_1;
+}
+
+var IDX=256, HEX=[];
+while (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1);
+
+function index (len) {
+ len = len || 16;
+ var str='', num=0;
+ return function () {
+ if (!str || num === 256) {
+ str=''; num=(1+len)/2 | 0;
+ while (num--) str += HEX[256 * Math.random() | 0];
+ str = str.substring(num=0, len-2);
+ }
+ return str + HEX[num++];
+ };
+}
+
+var dist$1 = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ default: index
+});
+
+var require$$2$1 = /*@__PURE__*/getAugmentedNamespace(dist$1);
+
+var raw;
+var hasRequiredRaw;
+
+function requireRaw () {
+ if (hasRequiredRaw) return raw;
+ hasRequiredRaw = 1;
+
+ var domain; // The domain module is executed on demand
+ var hasSetImmediate = typeof setImmediate === "function";
+
+ // Use the fastest means possible to execute a task in its own turn, with
+ // priority over other events including network IO events in Node.js.
+ //
+ // An exception thrown by a task will permanently interrupt the processing of
+ // subsequent tasks. The higher level `asap` function ensures that if an
+ // exception is thrown by a task, that the task queue will continue flushing as
+ // soon as possible, but if you use `rawAsap` directly, you are responsible to
+ // either ensure that no exceptions are thrown from your task, or to manually
+ // call `rawAsap.requestFlush` if an exception is thrown.
+ raw = rawAsap;
+ function rawAsap(task) {
+ if (!queue.length) {
+ requestFlush();
+ flushing = true;
+ }
+ // Avoids a function call
+ queue[queue.length] = task;
+ }
+
+ var queue = [];
+ // Once a flush has been requested, no further calls to `requestFlush` are
+ // necessary until the next `flush` completes.
+ var flushing = false;
+ // The position of the next task to execute in the task queue. This is
+ // preserved between calls to `flush` so that it can be resumed if
+ // a task throws an exception.
+ var index = 0;
+ // If a task schedules additional tasks recursively, the task queue can grow
+ // unbounded. To prevent memory excaustion, the task queue will periodically
+ // truncate already-completed tasks.
+ var capacity = 1024;
+
+ // The flush function processes all tasks that have been scheduled with
+ // `rawAsap` unless and until one of those tasks throws an exception.
+ // If a task throws an exception, `flush` ensures that its state will remain
+ // consistent and will resume where it left off when called again.
+ // However, `flush` does not make any arrangements to be called again if an
+ // exception is thrown.
+ function flush() {
+ while (index < queue.length) {
+ var currentIndex = index;
+ // Advance the index before calling the task. This ensures that we will
+ // begin flushing on the next task the task throws an error.
+ index = index + 1;
+ queue[currentIndex].call();
+ // Prevent leaking memory for long chains of recursive calls to `asap`.
+ // If we call `asap` within tasks scheduled by `asap`, the queue will
+ // grow, but to avoid an O(n) walk for every task we execute, we don't
+ // shift tasks off the queue after they have been executed.
+ // Instead, we periodically shift 1024 tasks off the queue.
+ if (index > capacity) {
+ // Manually shift all values starting at the index back to the
+ // beginning of the queue.
+ for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
+ queue[scan] = queue[scan + index];
+ }
+ queue.length -= index;
+ index = 0;
+ }
+ }
+ queue.length = 0;
+ index = 0;
+ flushing = false;
+ }
+
+ rawAsap.requestFlush = requestFlush;
+ function requestFlush() {
+ // Ensure flushing is not bound to any domain.
+ // It is not sufficient to exit the domain, because domains exist on a stack.
+ // To execute code outside of any domain, the following dance is necessary.
+ var parentDomain = process.domain;
+ if (parentDomain) {
+ if (!domain) {
+ // Lazy execute the domain module.
+ // Only employed if the user elects to use domains.
+ domain = domain$2;
+ }
+ domain.active = process.domain = null;
+ }
+
+ // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
+ // cannot handle recursion.
+ // `requestFlush` will only be called recursively from `asap.js`, to resume
+ // flushing after an error is thrown into a domain.
+ // Conveniently, `setImmediate` was introduced in the same version
+ // `process.nextTick` started throwing recursion errors.
+ if (flushing && hasSetImmediate) {
+ setImmediate(flush);
+ } else {
+ process.nextTick(flush);
+ }
+
+ if (parentDomain) {
+ domain.active = process.domain = parentDomain;
+ }
+ }
+ return raw;
+}
+
+var asap_1;
+var hasRequiredAsap;
+
+function requireAsap () {
+ if (hasRequiredAsap) return asap_1;
+ hasRequiredAsap = 1;
+
+ var rawAsap = requireRaw();
+ var freeTasks = [];
+
+ /**
+ * Calls a task as soon as possible after returning, in its own event, with
+ * priority over IO events. An exception thrown in a task can be handled by
+ * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
+ * crash the process. If the error is handled, all subsequent tasks will
+ * resume.
+ *
+ * @param {{call}} task A callable object, typically a function that takes no
+ * arguments.
+ */
+ asap_1 = asap;
+ function asap(task) {
+ var rawTask;
+ if (freeTasks.length) {
+ rawTask = freeTasks.pop();
+ } else {
+ rawTask = new RawTask();
+ }
+ rawTask.task = task;
+ rawTask.domain = process.domain;
+ rawAsap(rawTask);
+ }
+
+ function RawTask() {
+ this.task = null;
+ this.domain = null;
+ }
+
+ RawTask.prototype.call = function () {
+ if (this.domain) {
+ this.domain.enter();
+ }
+ var threw = true;
+ try {
+ this.task.call();
+ threw = false;
+ // If the task throws an exception (presumably) Node.js restores the
+ // domain stack for the next event.
+ if (this.domain) {
+ this.domain.exit();
+ }
+ } finally {
+ // We use try/finally and a threw flag to avoid messing up stack traces
+ // when we catch and release errors.
+ if (threw) {
+ // In Node.js, uncaught exceptions are considered fatal errors.
+ // Re-throw them to interrupt flushing!
+ // Ensure that flushing continues if an uncaught exception is
+ // suppressed listening process.on("uncaughtException") or
+ // domain.on("error").
+ rawAsap.requestFlush();
+ }
+ // If the task threw an error, we do not want to exit the domain here.
+ // Exiting the domain would prevent the domain from catching the error.
+ this.task = null;
+ this.domain = null;
+ freeTasks.push(this);
+ }
+ };
+ return asap_1;
+}
+
+var dezalgo_1;
+var hasRequiredDezalgo;
+
+function requireDezalgo () {
+ if (hasRequiredDezalgo) return dezalgo_1;
+ hasRequiredDezalgo = 1;
+ var wrappy = wrappy_1;
+ dezalgo_1 = wrappy(dezalgo);
+
+ var asap = requireAsap();
+
+ function dezalgo (cb) {
+ var sync = true;
+ asap(function () {
+ sync = false;
+ });
+
+ return function zalgoSafe() {
+ var args = arguments;
+ var me = this;
+ if (sync)
+ asap(function() {
+ cb.apply(me, args);
+ });
+ else
+ cb.apply(me, args);
+ }
+ }
+ return dezalgo_1;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var Dummy;
+var hasRequiredDummy;
+
+function requireDummy () {
+ if (hasRequiredDummy) return Dummy;
+ hasRequiredDummy = 1;
+
+ const { Transform } = Stream$2;
+
+ class DummyParser extends Transform {
+ constructor(incomingForm, options = {}) {
+ super();
+ this.globalOptions = { ...options };
+ this.incomingForm = incomingForm;
+ }
+
+ _flush(callback) {
+ this.incomingForm.ended = true;
+ this.incomingForm._maybeEnd();
+ callback();
+ }
+ }
+
+ Dummy = DummyParser;
+ return Dummy;
+}
+
+var MultipartExports = {};
+var Multipart = {
+ get exports(){ return MultipartExports; },
+ set exports(v){ MultipartExports = v; },
+};
+
+/* eslint-disable no-plusplus */
+
+var FormidableError_1;
+var hasRequiredFormidableError;
+
+function requireFormidableError () {
+ if (hasRequiredFormidableError) return FormidableError_1;
+ hasRequiredFormidableError = 1;
+ const missingPlugin = 1000;
+ const pluginFunction = 1001;
+ const aborted = 1002;
+ const noParser = 1003;
+ const uninitializedParser = 1004;
+ const filenameNotString = 1005;
+ const maxFieldsSizeExceeded = 1006;
+ const maxFieldsExceeded = 1007;
+ const smallerThanMinFileSize = 1008;
+ const biggerThanMaxFileSize = 1009;
+ const noEmptyFiles = 1010;
+ const missingContentType = 1011;
+ const malformedMultipart = 1012;
+ const missingMultipartBoundary = 1013;
+ const unknownTransferEncoding = 1014;
+
+ const FormidableError = class extends Error {
+ constructor(message, internalCode, httpCode = 500) {
+ super(message);
+ this.code = internalCode;
+ this.httpCode = httpCode;
+ }
+ };
+
+ FormidableError_1 = {
+ missingPlugin,
+ pluginFunction,
+ aborted,
+ noParser,
+ uninitializedParser,
+ filenameNotString,
+ maxFieldsSizeExceeded,
+ maxFieldsExceeded,
+ smallerThanMinFileSize,
+ biggerThanMaxFileSize,
+ noEmptyFiles,
+ missingContentType,
+ malformedMultipart,
+ missingMultipartBoundary,
+ unknownTransferEncoding,
+
+ FormidableError,
+ };
+ return FormidableError_1;
+}
+
+/* eslint-disable no-fallthrough */
+
+var hasRequiredMultipart$1;
+
+function requireMultipart$1 () {
+ if (hasRequiredMultipart$1) return MultipartExports;
+ hasRequiredMultipart$1 = 1;
+ (function (module, exports) {
+
+ const { Transform } = Stream$2;
+ const errors = requireFormidableError();
+
+ const { FormidableError } = errors;
+
+ let s = 0;
+ const STATE = {
+ PARSER_UNINITIALIZED: s++,
+ START: s++,
+ START_BOUNDARY: s++,
+ HEADER_FIELD_START: s++,
+ HEADER_FIELD: s++,
+ HEADER_VALUE_START: s++,
+ HEADER_VALUE: s++,
+ HEADER_VALUE_ALMOST_DONE: s++,
+ HEADERS_ALMOST_DONE: s++,
+ PART_DATA_START: s++,
+ PART_DATA: s++,
+ PART_END: s++,
+ END: s++,
+ };
+
+ let f = 1;
+ const FBOUNDARY = { PART_BOUNDARY: f, LAST_BOUNDARY: (f *= 2) };
+
+ const LF = 10;
+ const CR = 13;
+ const SPACE = 32;
+ const HYPHEN = 45;
+ const COLON = 58;
+ const A = 97;
+ const Z = 122;
+
+ function lower(c) {
+ return c | 0x20;
+ }
+
+ exports.STATES = {};
+
+ Object.keys(STATE).forEach((stateName) => {
+ exports.STATES[stateName] = STATE[stateName];
+ });
+
+ class MultipartParser extends Transform {
+ constructor(options = {}) {
+ super({ readableObjectMode: true });
+ this.boundary = null;
+ this.boundaryChars = null;
+ this.lookbehind = null;
+ this.bufferLength = 0;
+ this.state = STATE.PARSER_UNINITIALIZED;
+
+ this.globalOptions = { ...options };
+ this.index = null;
+ this.flags = 0;
+ }
+
+ _flush(done) {
+ if (
+ (this.state === STATE.HEADER_FIELD_START && this.index === 0) ||
+ (this.state === STATE.PART_DATA && this.index === this.boundary.length)
+ ) {
+ this._handleCallback('partEnd');
+ this._handleCallback('end');
+ done();
+ } else if (this.state !== STATE.END) {
+ done(
+ new FormidableError(
+ `MultipartParser.end(): stream ended unexpectedly: ${this.explain()}`,
+ errors.malformedMultipart,
+ 400,
+ ),
+ );
+ }
+ }
+
+ initWithBoundary(str) {
+ this.boundary = Buffer.from(`\r\n--${str}`);
+ this.lookbehind = Buffer.alloc(this.boundary.length + 8);
+ this.state = STATE.START;
+ this.boundaryChars = {};
+
+ for (let i = 0; i < this.boundary.length; i++) {
+ this.boundaryChars[this.boundary[i]] = true;
+ }
+ }
+
+ // eslint-disable-next-line max-params
+ _handleCallback(name, buf, start, end) {
+ if (start !== undefined && start === end) {
+ return;
+ }
+ this.push({ name, buffer: buf, start, end });
+ }
+
+ // eslint-disable-next-line max-statements
+ _transform(buffer, _, done) {
+ let i = 0;
+ let prevIndex = this.index;
+ let { index, state, flags } = this;
+ const { lookbehind, boundary, boundaryChars } = this;
+ const boundaryLength = boundary.length;
+ const boundaryEnd = boundaryLength - 1;
+ this.bufferLength = buffer.length;
+ let c = null;
+ let cl = null;
+
+ const setMark = (name, idx) => {
+ this[`${name}Mark`] = typeof idx === 'number' ? idx : i;
+ };
+
+ const clearMarkSymbol = (name) => {
+ delete this[`${name}Mark`];
+ };
+
+ const dataCallback = (name, shouldClear) => {
+ const markSymbol = `${name}Mark`;
+ if (!(markSymbol in this)) {
+ return;
+ }
+
+ if (!shouldClear) {
+ this._handleCallback(name, buffer, this[markSymbol], buffer.length);
+ setMark(name, 0);
+ } else {
+ this._handleCallback(name, buffer, this[markSymbol], i);
+ clearMarkSymbol(name);
+ }
+ };
+
+ for (i = 0; i < this.bufferLength; i++) {
+ c = buffer[i];
+ switch (state) {
+ case STATE.PARSER_UNINITIALIZED:
+ return i;
+ case STATE.START:
+ index = 0;
+ state = STATE.START_BOUNDARY;
+ case STATE.START_BOUNDARY:
+ if (index === boundary.length - 2) {
+ if (c === HYPHEN) {
+ flags |= FBOUNDARY.LAST_BOUNDARY;
+ } else if (c !== CR) {
+ return i;
+ }
+ index++;
+ break;
+ } else if (index - 1 === boundary.length - 2) {
+ if (flags & FBOUNDARY.LAST_BOUNDARY && c === HYPHEN) {
+ this._handleCallback('end');
+ state = STATE.END;
+ flags = 0;
+ } else if (!(flags & FBOUNDARY.LAST_BOUNDARY) && c === LF) {
+ index = 0;
+ this._handleCallback('partBegin');
+ state = STATE.HEADER_FIELD_START;
+ } else {
+ return i;
+ }
+ break;
+ }
+
+ if (c !== boundary[index + 2]) {
+ index = -2;
+ }
+ if (c === boundary[index + 2]) {
+ index++;
+ }
+ break;
+ case STATE.HEADER_FIELD_START:
+ state = STATE.HEADER_FIELD;
+ setMark('headerField');
+ index = 0;
+ case STATE.HEADER_FIELD:
+ if (c === CR) {
+ clearMarkSymbol('headerField');
+ state = STATE.HEADERS_ALMOST_DONE;
+ break;
+ }
+
+ index++;
+ if (c === HYPHEN) {
+ break;
+ }
+
+ if (c === COLON) {
+ if (index === 1) {
+ // empty header field
+ return i;
+ }
+ dataCallback('headerField', true);
+ state = STATE.HEADER_VALUE_START;
+ break;
+ }
+
+ cl = lower(c);
+ if (cl < A || cl > Z) {
+ return i;
+ }
+ break;
+ case STATE.HEADER_VALUE_START:
+ if (c === SPACE) {
+ break;
+ }
+
+ setMark('headerValue');
+ state = STATE.HEADER_VALUE;
+ case STATE.HEADER_VALUE:
+ if (c === CR) {
+ dataCallback('headerValue', true);
+ this._handleCallback('headerEnd');
+ state = STATE.HEADER_VALUE_ALMOST_DONE;
+ }
+ break;
+ case STATE.HEADER_VALUE_ALMOST_DONE:
+ if (c !== LF) {
+ return i;
+ }
+ state = STATE.HEADER_FIELD_START;
+ break;
+ case STATE.HEADERS_ALMOST_DONE:
+ if (c !== LF) {
+ return i;
+ }
+
+ this._handleCallback('headersEnd');
+ state = STATE.PART_DATA_START;
+ break;
+ case STATE.PART_DATA_START:
+ state = STATE.PART_DATA;
+ setMark('partData');
+ case STATE.PART_DATA:
+ prevIndex = index;
+
+ if (index === 0) {
+ // boyer-moore derrived algorithm to safely skip non-boundary data
+ i += boundaryEnd;
+ while (i < this.bufferLength && !(buffer[i] in boundaryChars)) {
+ i += boundaryLength;
+ }
+ i -= boundaryEnd;
+ c = buffer[i];
+ }
+
+ if (index < boundary.length) {
+ if (boundary[index] === c) {
+ if (index === 0) {
+ dataCallback('partData', true);
+ }
+ index++;
+ } else {
+ index = 0;
+ }
+ } else if (index === boundary.length) {
+ index++;
+ if (c === CR) {
+ // CR = part boundary
+ flags |= FBOUNDARY.PART_BOUNDARY;
+ } else if (c === HYPHEN) {
+ // HYPHEN = end boundary
+ flags |= FBOUNDARY.LAST_BOUNDARY;
+ } else {
+ index = 0;
+ }
+ } else if (index - 1 === boundary.length) {
+ if (flags & FBOUNDARY.PART_BOUNDARY) {
+ index = 0;
+ if (c === LF) {
+ // unset the PART_BOUNDARY flag
+ flags &= ~FBOUNDARY.PART_BOUNDARY;
+ this._handleCallback('partEnd');
+ this._handleCallback('partBegin');
+ state = STATE.HEADER_FIELD_START;
+ break;
+ }
+ } else if (flags & FBOUNDARY.LAST_BOUNDARY) {
+ if (c === HYPHEN) {
+ this._handleCallback('partEnd');
+ this._handleCallback('end');
+ state = STATE.END;
+ flags = 0;
+ } else {
+ index = 0;
+ }
+ } else {
+ index = 0;
+ }
+ }
+
+ if (index > 0) {
+ // when matching a possible boundary, keep a lookbehind reference
+ // in case it turns out to be a false lead
+ lookbehind[index - 1] = c;
+ } else if (prevIndex > 0) {
+ // if our boundary turned out to be rubbish, the captured lookbehind
+ // belongs to partData
+ this._handleCallback('partData', lookbehind, 0, prevIndex);
+ prevIndex = 0;
+ setMark('partData');
+
+ // reconsider the current character even so it interrupted the sequence
+ // it could be the beginning of a new sequence
+ i--;
+ }
+
+ break;
+ case STATE.END:
+ break;
+ default:
+ return i;
+ }
+ }
+
+ dataCallback('headerField');
+ dataCallback('headerValue');
+ dataCallback('partData');
+
+ this.index = index;
+ this.state = state;
+ this.flags = flags;
+
+ done();
+ return this.bufferLength;
+ }
+
+ explain() {
+ return `state = ${MultipartParser.stateToString(this.state)}`;
+ }
+ }
+
+ // eslint-disable-next-line consistent-return
+ MultipartParser.stateToString = (stateNumber) => {
+ // eslint-disable-next-line no-restricted-syntax, guard-for-in
+ for (const stateName in STATE) {
+ const number = STATE[stateName];
+ if (number === stateNumber) return stateName;
+ }
+ };
+
+ module.exports = Object.assign(MultipartParser, { STATES: exports.STATES });
+} (Multipart, MultipartExports));
+ return MultipartExports;
+}
+
+/* eslint-disable class-methods-use-this */
+
+var Formidable;
+var hasRequiredFormidable;
+
+function requireFormidable () {
+ if (hasRequiredFormidable) return Formidable;
+ hasRequiredFormidable = 1;
+
+ const os = require$$0$h;
+ const path = require$$0$c;
+ const hexoid = require$$2$1;
+ const once = onceExports;
+ const dezalgo = requireDezalgo();
+ const { EventEmitter } = require$$0$f;
+ const { StringDecoder } = require$$1$8;
+ const qs = lib$2;
+
+ const toHexoId = hexoid(25);
+ const DEFAULT_OPTIONS = {
+ maxFields: 1000,
+ maxFieldsSize: 20 * 1024 * 1024,
+ maxFileSize: 200 * 1024 * 1024,
+ minFileSize: 1,
+ allowEmptyFiles: true,
+ keepExtensions: false,
+ encoding: 'utf-8',
+ hashAlgorithm: false,
+ uploadDir: os.tmpdir(),
+ multiples: false,
+ enabledPlugins: ['octetstream', 'querystring', 'multipart', 'json'],
+ fileWriteStreamHandler: null,
+ defaultInvalidName: 'invalid-name',
+ filter: function () {
+ return true;
+ },
+ };
+
+ const PersistentFile = requirePersistentFile();
+ const VolatileFile = requireVolatileFile();
+ const DummyParser = requireDummy();
+ const MultipartParser = requireMultipart$1();
+ const errors = requireFormidableError();
+
+ const { FormidableError } = errors;
+
+ function hasOwnProp(obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key);
+ }
+
+ class IncomingForm extends EventEmitter {
+ constructor(options = {}) {
+ super();
+
+ this.options = { ...DEFAULT_OPTIONS, ...options };
+
+ const dir = path.resolve(
+ this.options.uploadDir || this.options.uploaddir || os.tmpdir(),
+ );
+
+ this.uploaddir = dir;
+ this.uploadDir = dir;
+
+ // initialize with null
+ [
+ 'error',
+ 'headers',
+ 'type',
+ 'bytesExpected',
+ 'bytesReceived',
+ '_parser',
+ ].forEach((key) => {
+ this[key] = null;
+ });
+
+ this._setUpRename();
+
+ this._flushing = 0;
+ this._fieldsSize = 0;
+ this._fileSize = 0;
+ this._plugins = [];
+ this.openedFiles = [];
+
+ this.options.enabledPlugins = []
+ .concat(this.options.enabledPlugins)
+ .filter(Boolean);
+
+ if (this.options.enabledPlugins.length === 0) {
+ throw new FormidableError(
+ 'expect at least 1 enabled builtin plugin, see options.enabledPlugins',
+ errors.missingPlugin,
+ );
+ }
+
+ this.options.enabledPlugins.forEach((pluginName) => {
+ const plgName = pluginName.toLowerCase();
+ // eslint-disable-next-line import/no-dynamic-require, global-require
+ this.use(commonjsRequire(path.join(__dirname, 'plugins', `${plgName}.js`)));
+ });
+
+ this._setUpMaxFields();
+ }
+
+ use(plugin) {
+ if (typeof plugin !== 'function') {
+ throw new FormidableError(
+ '.use: expect `plugin` to be a function',
+ errors.pluginFunction,
+ );
+ }
+ this._plugins.push(plugin.bind(this));
+ return this;
+ }
+
+ parse(req, cb) {
+ this.pause = () => {
+ try {
+ req.pause();
+ } catch (err) {
+ // the stream was destroyed
+ if (!this.ended) {
+ // before it was completed, crash & burn
+ this._error(err);
+ }
+ return false;
+ }
+ return true;
+ };
+
+ this.resume = () => {
+ try {
+ req.resume();
+ } catch (err) {
+ // the stream was destroyed
+ if (!this.ended) {
+ // before it was completed, crash & burn
+ this._error(err);
+ }
+ return false;
+ }
+
+ return true;
+ };
+
+ // Setup callback first, so we don't miss anything from data events emitted immediately.
+ if (cb) {
+ const callback = once(dezalgo(cb));
+ const fields = {};
+ let mockFields = '';
+ const files = {};
+
+ this.on('field', (name, value) => {
+ if (
+ this.options.multiples &&
+ (this.type === 'multipart' || this.type === 'urlencoded')
+ ) {
+ const mObj = { [name]: value };
+ mockFields = mockFields
+ ? `${mockFields}&${qs.stringify(mObj)}`
+ : `${qs.stringify(mObj)}`;
+ } else {
+ fields[name] = value;
+ }
+ });
+ this.on('file', (name, file) => {
+ // TODO: too much nesting
+ if (this.options.multiples) {
+ if (hasOwnProp(files, name)) {
+ if (!Array.isArray(files[name])) {
+ files[name] = [files[name]];
+ }
+ files[name].push(file);
+ } else {
+ files[name] = file;
+ }
+ } else {
+ files[name] = file;
+ }
+ });
+ this.on('error', (err) => {
+ callback(err, fields, files);
+ });
+ this.on('end', () => {
+ if (this.options.multiples) {
+ Object.assign(fields, qs.parse(mockFields));
+ }
+ callback(null, fields, files);
+ });
+ }
+
+ // Parse headers and setup the parser, ready to start listening for data.
+ this.writeHeaders(req.headers);
+
+ // Start listening for data.
+ req
+ .on('error', (err) => {
+ this._error(err);
+ })
+ .on('aborted', () => {
+ this.emit('aborted');
+ this._error(new FormidableError('Request aborted', errors.aborted));
+ })
+ .on('data', (buffer) => {
+ try {
+ this.write(buffer);
+ } catch (err) {
+ this._error(err);
+ }
+ })
+ .on('end', () => {
+ if (this.error) {
+ return;
+ }
+ if (this._parser) {
+ this._parser.end();
+ }
+ this._maybeEnd();
+ });
+
+ return this;
+ }
+
+ writeHeaders(headers) {
+ this.headers = headers;
+ this._parseContentLength();
+ this._parseContentType();
+
+ if (!this._parser) {
+ this._error(
+ new FormidableError(
+ 'no parser found',
+ errors.noParser,
+ 415, // Unsupported Media Type
+ ),
+ );
+ return;
+ }
+
+ this._parser.once('error', (error) => {
+ this._error(error);
+ });
+ }
+
+ write(buffer) {
+ if (this.error) {
+ return null;
+ }
+ if (!this._parser) {
+ this._error(
+ new FormidableError('uninitialized parser', errors.uninitializedParser),
+ );
+ return null;
+ }
+
+ this.bytesReceived += buffer.length;
+ this.emit('progress', this.bytesReceived, this.bytesExpected);
+
+ this._parser.write(buffer);
+
+ return this.bytesReceived;
+ }
+
+ pause() {
+ // this does nothing, unless overwritten in IncomingForm.parse
+ return false;
+ }
+
+ resume() {
+ // this does nothing, unless overwritten in IncomingForm.parse
+ return false;
+ }
+
+ onPart(part) {
+ // this method can be overwritten by the user
+ this._handlePart(part);
+ }
+
+ _handlePart(part) {
+ if (part.originalFilename && typeof part.originalFilename !== 'string') {
+ this._error(
+ new FormidableError(
+ `the part.originalFilename should be string when it exists`,
+ errors.filenameNotString,
+ ),
+ );
+ return;
+ }
+
+ // This MUST check exactly for undefined. You can not change it to !part.originalFilename.
+
+ // todo: uncomment when switch tests to Jest
+ // console.log(part);
+
+ // ? NOTE(@tunnckocore): no it can be any falsey value, it most probably depends on what's returned
+ // from somewhere else. Where recently I changed the return statements
+ // and such thing because code style
+ // ? NOTE(@tunnckocore): or even better, if there is no mimetype, then it's for sure a field
+ // ? NOTE(@tunnckocore): originalFilename is an empty string when a field?
+ if (!part.mimetype) {
+ let value = '';
+ const decoder = new StringDecoder(
+ part.transferEncoding || this.options.encoding,
+ );
+
+ part.on('data', (buffer) => {
+ this._fieldsSize += buffer.length;
+ if (this._fieldsSize > this.options.maxFieldsSize) {
+ this._error(
+ new FormidableError(
+ `options.maxFieldsSize (${this.options.maxFieldsSize} bytes) exceeded, received ${this._fieldsSize} bytes of field data`,
+ errors.maxFieldsSizeExceeded,
+ 413, // Payload Too Large
+ ),
+ );
+ return;
+ }
+ value += decoder.write(buffer);
+ });
+
+ part.on('end', () => {
+ this.emit('field', part.name, value);
+ });
+ return;
+ }
+
+ if (!this.options.filter(part)) {
+ return;
+ }
+
+ this._flushing += 1;
+
+ const newFilename = this._getNewName(part);
+ const filepath = this._joinDirectoryName(newFilename);
+ const file = this._newFile({
+ newFilename,
+ filepath,
+ originalFilename: part.originalFilename,
+ mimetype: part.mimetype,
+ });
+ file.on('error', (err) => {
+ this._error(err);
+ });
+ this.emit('fileBegin', part.name, file);
+
+ file.open();
+ this.openedFiles.push(file);
+
+ part.on('data', (buffer) => {
+ this._fileSize += buffer.length;
+ if (this._fileSize < this.options.minFileSize) {
+ this._error(
+ new FormidableError(
+ `options.minFileSize (${this.options.minFileSize} bytes) inferior, received ${this._fileSize} bytes of file data`,
+ errors.smallerThanMinFileSize,
+ 400,
+ ),
+ );
+ return;
+ }
+ if (this._fileSize > this.options.maxFileSize) {
+ this._error(
+ new FormidableError(
+ `options.maxFileSize (${this.options.maxFileSize} bytes) exceeded, received ${this._fileSize} bytes of file data`,
+ errors.biggerThanMaxFileSize,
+ 413,
+ ),
+ );
+ return;
+ }
+ if (buffer.length === 0) {
+ return;
+ }
+ this.pause();
+ file.write(buffer, () => {
+ this.resume();
+ });
+ });
+
+ part.on('end', () => {
+ if (!this.options.allowEmptyFiles && this._fileSize === 0) {
+ this._error(
+ new FormidableError(
+ `options.allowEmptyFiles is false, file size should be greather than 0`,
+ errors.noEmptyFiles,
+ 400,
+ ),
+ );
+ return;
+ }
+
+ file.end(() => {
+ this._flushing -= 1;
+ this.emit('file', part.name, file);
+ this._maybeEnd();
+ });
+ });
+ }
+
+ // eslint-disable-next-line max-statements
+ _parseContentType() {
+ if (this.bytesExpected === 0) {
+ this._parser = new DummyParser(this, this.options);
+ return;
+ }
+
+ if (!this.headers['content-type']) {
+ this._error(
+ new FormidableError(
+ 'bad content-type header, no content-type',
+ errors.missingContentType,
+ 400,
+ ),
+ );
+ return;
+ }
+
+ const results = [];
+ new DummyParser(this, this.options);
+
+ // eslint-disable-next-line no-plusplus
+ for (let idx = 0; idx < this._plugins.length; idx++) {
+ const plugin = this._plugins[idx];
+
+ let pluginReturn = null;
+
+ try {
+ pluginReturn = plugin(this, this.options) || this;
+ } catch (err) {
+ // directly throw from the `form.parse` method;
+ // there is no other better way, except a handle through options
+ const error = new FormidableError(
+ `plugin on index ${idx} failed with: ${err.message}`,
+ errors.pluginFailed,
+ 500,
+ );
+ error.idx = idx;
+ throw error;
+ }
+
+ Object.assign(this, pluginReturn);
+
+ // todo: use Set/Map and pass plugin name instead of the `idx` index
+ this.emit('plugin', idx, pluginReturn);
+ results.push(pluginReturn);
+ }
+
+ this.emit('pluginsResults', results);
+
+ // NOTE: probably not needed, because we check options.enabledPlugins in the constructor
+ // if (results.length === 0 /* && results.length !== this._plugins.length */) {
+ // this._error(
+ // new Error(
+ // `bad content-type header, unknown content-type: ${this.headers['content-type']}`,
+ // ),
+ // );
+ // }
+ }
+
+ _error(err, eventName = 'error') {
+ // if (!err && this.error) {
+ // this.emit('error', this.error);
+ // return;
+ // }
+ if (this.error || this.ended) {
+ return;
+ }
+
+ this.error = err;
+ this.emit(eventName, err);
+
+ if (Array.isArray(this.openedFiles)) {
+ this.openedFiles.forEach((file) => {
+ file.destroy();
+ });
+ }
+ }
+
+ _parseContentLength() {
+ this.bytesReceived = 0;
+ if (this.headers['content-length']) {
+ this.bytesExpected = parseInt(this.headers['content-length'], 10);
+ } else if (this.headers['transfer-encoding'] === undefined) {
+ this.bytesExpected = 0;
+ }
+
+ if (this.bytesExpected !== null) {
+ this.emit('progress', this.bytesReceived, this.bytesExpected);
+ }
+ }
+
+ _newParser() {
+ return new MultipartParser(this.options);
+ }
+
+ _newFile({ filepath, originalFilename, mimetype, newFilename }) {
+ return this.options.fileWriteStreamHandler
+ ? new VolatileFile({
+ newFilename,
+ filepath,
+ originalFilename,
+ mimetype,
+ createFileWriteStream: this.options.fileWriteStreamHandler,
+ hashAlgorithm: this.options.hashAlgorithm,
+ })
+ : new PersistentFile({
+ newFilename,
+ filepath,
+ originalFilename,
+ mimetype,
+ hashAlgorithm: this.options.hashAlgorithm,
+ });
+ }
+
+ _getFileName(headerValue) {
+ // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
+ const m = headerValue.match(
+ /\bfilename=("(.*?)"|([^()<>{}[\]@,;:"?=\s/\t]+))($|;\s)/i,
+ );
+ if (!m) return null;
+
+ const match = m[2] || m[3] || '';
+ let originalFilename = match.substr(match.lastIndexOf('\\') + 1);
+ originalFilename = originalFilename.replace(/%22/g, '"');
+ originalFilename = originalFilename.replace(/([\d]{4});/g, (_, code) =>
+ String.fromCharCode(code),
+ );
+
+ return originalFilename;
+ }
+
+ _getExtension(str) {
+ if (!str) {
+ return '';
+ }
+
+ const basename = path.basename(str);
+ const firstDot = basename.indexOf('.');
+ const lastDot = basename.lastIndexOf('.');
+ const extname = path.extname(basename).replace(/(\.[a-z0-9]+).*/i, '$1');
+
+ if (firstDot === lastDot) {
+ return extname;
+ }
+
+ return basename.slice(firstDot, lastDot) + extname;
+ }
+
+
+
+ _joinDirectoryName(name) {
+ const newPath = path.join(this.uploadDir, name);
+
+ // prevent directory traversal attacks
+ if (!newPath.startsWith(this.uploadDir)) {
+ return path.join(this.uploadDir, this.options.defaultInvalidName);
+ }
+
+ return newPath;
+ }
+
+ _setUpRename() {
+ const hasRename = typeof this.options.filename === 'function';
+ if (hasRename) {
+ this._getNewName = (part) => {
+ let ext = '';
+ let name = this.options.defaultInvalidName;
+ if (part.originalFilename) {
+ // can be null
+ ({ ext, name } = path.parse(part.originalFilename));
+ if (this.options.keepExtensions !== true) {
+ ext = '';
+ }
+ }
+ return this.options.filename.call(this, name, ext, part, this);
+ };
+ } else {
+ this._getNewName = (part) => {
+ const name = toHexoId();
+
+ if (part && this.options.keepExtensions) {
+ const originalFilename = typeof part === 'string' ? part : part.originalFilename;
+ return `${name}${this._getExtension(originalFilename)}`;
+ }
+
+ return name;
+ };
+ }
+ }
+
+ _setUpMaxFields() {
+ if (this.options.maxFields !== 0) {
+ let fieldsCount = 0;
+ this.on('field', () => {
+ fieldsCount += 1;
+ if (fieldsCount > this.options.maxFields) {
+ this._error(
+ new FormidableError(
+ `options.maxFields (${this.options.maxFields}) exceeded`,
+ errors.maxFieldsExceeded,
+ 413,
+ ),
+ );
+ }
+ });
+ }
+ }
+
+ _maybeEnd() {
+ // console.log('ended', this.ended);
+ // console.log('_flushing', this._flushing);
+ // console.log('error', this.error);
+ if (!this.ended || this._flushing || this.error) {
+ return;
+ }
+
+ this.emit('end');
+ }
+ }
+
+ IncomingForm.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
+ Formidable = IncomingForm;
+ return Formidable;
+}
+
+var plugins = {};
+
+var OctetStream;
+var hasRequiredOctetStream;
+
+function requireOctetStream () {
+ if (hasRequiredOctetStream) return OctetStream;
+ hasRequiredOctetStream = 1;
+
+ const { PassThrough } = Stream$2;
+
+ class OctetStreamParser extends PassThrough {
+ constructor(options = {}) {
+ super();
+ this.globalOptions = { ...options };
+ }
+ }
+
+ OctetStream = OctetStreamParser;
+ return OctetStream;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var octetstream;
+var hasRequiredOctetstream;
+
+function requireOctetstream () {
+ if (hasRequiredOctetstream) return octetstream;
+ hasRequiredOctetstream = 1;
+
+ const OctetStreamParser = requireOctetStream();
+
+ // the `options` is also available through the `options` / `formidable.options`
+ octetstream = function plugin(formidable, options) {
+ // the `this` context is always formidable, as the first argument of a plugin
+ // but this allows us to customize/test each plugin
+
+ /* istanbul ignore next */
+ const self = this || formidable;
+
+ if (/octet-stream/i.test(self.headers['content-type'])) {
+ init.call(self, self, options);
+ }
+
+ return self;
+ };
+
+ // Note that it's a good practice (but it's up to you) to use the `this.options` instead
+ // of the passed `options` (second) param, because when you decide
+ // to test the plugin you can pass custom `this` context to it (and so `this.options`)
+ function init(_self, _opts) {
+ this.type = 'octet-stream';
+ const originalFilename = this.headers['x-file-name'];
+ const mimetype = this.headers['content-type'];
+
+ const thisPart = {
+ originalFilename,
+ mimetype,
+ };
+ const newFilename = this._getNewName(thisPart);
+ const filepath = this._joinDirectoryName(newFilename);
+ const file = this._newFile({
+ newFilename,
+ filepath,
+ originalFilename,
+ mimetype,
+ });
+
+ this.emit('fileBegin', originalFilename, file);
+ file.open();
+ this.openedFiles.push(file);
+ this._flushing += 1;
+
+ this._parser = new OctetStreamParser(this.options);
+
+ // Keep track of writes that haven't finished so we don't emit the file before it's done being written
+ let outstandingWrites = 0;
+
+ this._parser.on('data', (buffer) => {
+ this.pause();
+ outstandingWrites += 1;
+
+ file.write(buffer, () => {
+ outstandingWrites -= 1;
+ this.resume();
+
+ if (this.ended) {
+ this._parser.emit('doneWritingFile');
+ }
+ });
+ });
+
+ this._parser.on('end', () => {
+ this._flushing -= 1;
+ this.ended = true;
+
+ const done = () => {
+ file.end(() => {
+ this.emit('file', 'file', file);
+ this._maybeEnd();
+ });
+ };
+
+ if (outstandingWrites === 0) {
+ done();
+ } else {
+ this._parser.once('doneWritingFile', done);
+ }
+ });
+
+ return this;
+ }
+ return octetstream;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var Querystring;
+var hasRequiredQuerystring$1;
+
+function requireQuerystring$1 () {
+ if (hasRequiredQuerystring$1) return Querystring;
+ hasRequiredQuerystring$1 = 1;
+
+ const { Transform } = Stream$2;
+ const querystring = require$$8$1;
+
+ // This is a buffering parser, not quite as nice as the multipart one.
+ // If I find time I'll rewrite this to be fully streaming as well
+ class QuerystringParser extends Transform {
+ constructor(options = {}) {
+ super({ readableObjectMode: true });
+ this.globalOptions = { ...options };
+ this.buffer = '';
+ this.bufferLength = 0;
+ }
+
+ _transform(buffer, encoding, callback) {
+ this.buffer += buffer.toString('ascii');
+ this.bufferLength = this.buffer.length;
+ callback();
+ }
+
+ _flush(callback) {
+ const fields = querystring.parse(this.buffer, '&', '=');
+ // eslint-disable-next-line no-restricted-syntax, guard-for-in
+ for (const key in fields) {
+ this.push({
+ key,
+ value: fields[key],
+ });
+ }
+ this.buffer = '';
+ callback();
+ }
+ }
+
+ Querystring = QuerystringParser;
+ return Querystring;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var querystring$2;
+var hasRequiredQuerystring;
+
+function requireQuerystring () {
+ if (hasRequiredQuerystring) return querystring$2;
+ hasRequiredQuerystring = 1;
+
+ const QuerystringParser = requireQuerystring$1();
+
+ // the `options` is also available through the `this.options` / `formidable.options`
+ querystring$2 = function plugin(formidable, options) {
+ // the `this` context is always formidable, as the first argument of a plugin
+ // but this allows us to customize/test each plugin
+
+ /* istanbul ignore next */
+ const self = this || formidable;
+
+ if (/urlencoded/i.test(self.headers['content-type'])) {
+ init.call(self, self, options);
+ }
+
+ return self;
+ };
+
+ // Note that it's a good practice (but it's up to you) to use the `this.options` instead
+ // of the passed `options` (second) param, because when you decide
+ // to test the plugin you can pass custom `this` context to it (and so `this.options`)
+ function init(_self, _opts) {
+ this.type = 'urlencoded';
+
+ const parser = new QuerystringParser(this.options);
+
+ parser.on('data', ({ key, value }) => {
+ this.emit('field', key, value);
+ });
+
+ parser.once('end', () => {
+ this.ended = true;
+ this._maybeEnd();
+ });
+
+ this._parser = parser;
+
+ return this;
+ }
+ return querystring$2;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var multipart;
+var hasRequiredMultipart;
+
+function requireMultipart () {
+ if (hasRequiredMultipart) return multipart;
+ hasRequiredMultipart = 1;
+
+ const { Stream } = Stream$2;
+ const MultipartParser = requireMultipart$1();
+ const errors = requireFormidableError();
+
+ const { FormidableError } = errors;
+
+ // the `options` is also available through the `options` / `formidable.options`
+ multipart = function plugin(formidable, options) {
+ // the `this` context is always formidable, as the first argument of a plugin
+ // but this allows us to customize/test each plugin
+
+ /* istanbul ignore next */
+ const self = this || formidable;
+
+ // NOTE: we (currently) support both multipart/form-data and multipart/related
+ const multipart = /multipart/i.test(self.headers['content-type']);
+
+ if (multipart) {
+ const m = self.headers['content-type'].match(
+ /boundary=(?:"([^"]+)"|([^;]+))/i,
+ );
+ if (m) {
+ const initMultipart = createInitMultipart(m[1] || m[2]);
+ initMultipart.call(self, self, options); // lgtm [js/superfluous-trailing-arguments]
+ } else {
+ const err = new FormidableError(
+ 'bad content-type header, no multipart boundary',
+ errors.missingMultipartBoundary,
+ 400,
+ );
+ self._error(err);
+ }
+ }
+ };
+
+ // Note that it's a good practice (but it's up to you) to use the `this.options` instead
+ // of the passed `options` (second) param, because when you decide
+ // to test the plugin you can pass custom `this` context to it (and so `this.options`)
+ function createInitMultipart(boundary) {
+ return function initMultipart() {
+ this.type = 'multipart';
+
+ const parser = new MultipartParser(this.options);
+ let headerField;
+ let headerValue;
+ let part;
+
+ parser.initWithBoundary(boundary);
+
+ // eslint-disable-next-line max-statements, consistent-return
+ parser.on('data', ({ name, buffer, start, end }) => {
+ if (name === 'partBegin') {
+ part = new Stream();
+ part.readable = true;
+ part.headers = {};
+ part.name = null;
+ part.originalFilename = null;
+ part.mimetype = null;
+
+ part.transferEncoding = this.options.encoding;
+ part.transferBuffer = '';
+
+ headerField = '';
+ headerValue = '';
+ } else if (name === 'headerField') {
+ headerField += buffer.toString(this.options.encoding, start, end);
+ } else if (name === 'headerValue') {
+ headerValue += buffer.toString(this.options.encoding, start, end);
+ } else if (name === 'headerEnd') {
+ headerField = headerField.toLowerCase();
+ part.headers[headerField] = headerValue;
+
+ // matches either a quoted-string or a token (RFC 2616 section 19.5.1)
+ const m = headerValue.match(
+ // eslint-disable-next-line no-useless-escape
+ /\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i,
+ );
+ if (headerField === 'content-disposition') {
+ if (m) {
+ part.name = m[2] || m[3] || '';
+ }
+
+ part.originalFilename = this._getFileName(headerValue);
+ } else if (headerField === 'content-type') {
+ part.mimetype = headerValue;
+ } else if (headerField === 'content-transfer-encoding') {
+ part.transferEncoding = headerValue.toLowerCase();
+ }
+
+ headerField = '';
+ headerValue = '';
+ } else if (name === 'headersEnd') {
+ switch (part.transferEncoding) {
+ case 'binary':
+ case '7bit':
+ case '8bit':
+ case 'utf-8': {
+ const dataPropagation = (ctx) => {
+ if (ctx.name === 'partData') {
+ part.emit('data', ctx.buffer.slice(ctx.start, ctx.end));
+ }
+ };
+ const dataStopPropagation = (ctx) => {
+ if (ctx.name === 'partEnd') {
+ part.emit('end');
+ parser.off('data', dataPropagation);
+ parser.off('data', dataStopPropagation);
+ }
+ };
+ parser.on('data', dataPropagation);
+ parser.on('data', dataStopPropagation);
+ break;
+ }
+ case 'base64': {
+ const dataPropagation = (ctx) => {
+ if (ctx.name === 'partData') {
+ part.transferBuffer += ctx.buffer
+ .slice(ctx.start, ctx.end)
+ .toString('ascii');
+
+ /*
+ four bytes (chars) in base64 converts to three bytes in binary
+ encoding. So we should always work with a number of bytes that
+ can be divided by 4, it will result in a number of buytes that
+ can be divided vy 3.
+ */
+ const offset = parseInt(part.transferBuffer.length / 4, 10) * 4;
+ part.emit(
+ 'data',
+ Buffer.from(
+ part.transferBuffer.substring(0, offset),
+ 'base64',
+ ),
+ );
+ part.transferBuffer = part.transferBuffer.substring(offset);
+ }
+ };
+ const dataStopPropagation = (ctx) => {
+ if (ctx.name === 'partEnd') {
+ part.emit('data', Buffer.from(part.transferBuffer, 'base64'));
+ part.emit('end');
+ parser.off('data', dataPropagation);
+ parser.off('data', dataStopPropagation);
+ }
+ };
+ parser.on('data', dataPropagation);
+ parser.on('data', dataStopPropagation);
+ break;
+ }
+ default:
+ return this._error(
+ new FormidableError(
+ 'unknown transfer-encoding',
+ errors.unknownTransferEncoding,
+ 501,
+ ),
+ );
+ }
+
+ this.onPart(part);
+ } else if (name === 'end') {
+ this.ended = true;
+ this._maybeEnd();
+ }
+ });
+
+ this._parser = parser;
+ };
+ }
+ return multipart;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var _JSON;
+var hasRequired_JSON;
+
+function require_JSON () {
+ if (hasRequired_JSON) return _JSON;
+ hasRequired_JSON = 1;
+
+ const { Transform } = Stream$2;
+
+ class JSONParser extends Transform {
+ constructor(options = {}) {
+ super({ readableObjectMode: true });
+ this.chunks = [];
+ this.globalOptions = { ...options };
+ }
+
+ _transform(chunk, encoding, callback) {
+ this.chunks.push(String(chunk)); // todo consider using a string decoder
+ callback();
+ }
+
+ _flush(callback) {
+ try {
+ const fields = JSON.parse(this.chunks.join(''));
+ Object.keys(fields).forEach((key) => {
+ const value = fields[key];
+ this.push({ key, value });
+ });
+ } catch (e) {
+ callback(e);
+ return;
+ }
+ this.chunks = null;
+ callback();
+ }
+ }
+
+ _JSON = JSONParser;
+ return _JSON;
+}
+
+/* eslint-disable no-underscore-dangle */
+
+var json$2;
+var hasRequiredJson$1;
+
+function requireJson$1 () {
+ if (hasRequiredJson$1) return json$2;
+ hasRequiredJson$1 = 1;
+
+ const JSONParser = require_JSON();
+
+ // the `options` is also available through the `this.options` / `formidable.options`
+ json$2 = function plugin(formidable, options) {
+ // the `this` context is always formidable, as the first argument of a plugin
+ // but this allows us to customize/test each plugin
+
+ /* istanbul ignore next */
+ const self = this || formidable;
+
+ if (/json/i.test(self.headers['content-type'])) {
+ init.call(self, self, options);
+ }
+ };
+
+ // Note that it's a good practice (but it's up to you) to use the `this.options` instead
+ // of the passed `options` (second) param, because when you decide
+ // to test the plugin you can pass custom `this` context to it (and so `this.options`)
+ function init(_self, _opts) {
+ this.type = 'json';
+
+ const parser = new JSONParser(this.options);
+
+ parser.on('data', ({ key, value }) => {
+ this.emit('field', key, value);
+ });
+
+ parser.once('end', () => {
+ this.ended = true;
+ this._maybeEnd();
+ });
+
+ this._parser = parser;
+ }
+ return json$2;
+}
+
+var hasRequiredPlugins;
+
+function requirePlugins () {
+ if (hasRequiredPlugins) return plugins;
+ hasRequiredPlugins = 1;
+ (function (exports) {
+
+ const octetstream = requireOctetstream();
+ const querystring = requireQuerystring();
+ const multipart = requireMultipart();
+ const json = requireJson$1();
+
+ Object.assign(exports, {
+ octetstream,
+ querystring,
+ multipart,
+ json,
+ });
+} (plugins));
+ return plugins;
+}
+
+var parsers$1 = {};
+
+var hasRequiredParsers$1;
+
+function requireParsers$1 () {
+ if (hasRequiredParsers$1) return parsers$1;
+ hasRequiredParsers$1 = 1;
+ (function (exports) {
+
+ const JSONParser = require_JSON();
+ const DummyParser = requireDummy();
+ const MultipartParser = requireMultipart$1();
+ const OctetStreamParser = requireOctetStream();
+ const QueryStringParser = requireQuerystring$1();
+
+ Object.assign(exports, {
+ JSONParser,
+ DummyParser,
+ MultipartParser,
+ OctetStreamParser,
+ OctetstreamParser: OctetStreamParser,
+ QueryStringParser,
+ QuerystringParser: QueryStringParser,
+ });
+} (parsers$1));
+ return parsers$1;
+}
+
+var src$1;
+var hasRequiredSrc;
+
+function requireSrc () {
+ if (hasRequiredSrc) return src$1;
+ hasRequiredSrc = 1;
+
+ const PersistentFile = requirePersistentFile();
+ const VolatileFile = requireVolatileFile();
+ const Formidable = requireFormidable();
+ const FormidableError = requireFormidableError();
+
+ const plugins = requirePlugins();
+ const parsers = requireParsers$1();
+
+ // make it available without requiring the `new` keyword
+ // if you want it access `const formidable.IncomingForm` as v1
+ const formidable = (...args) => new Formidable(...args);
+
+ src$1 = Object.assign(formidable, {
+ errors: FormidableError,
+ File: PersistentFile,
+ PersistentFile,
+ VolatileFile,
+ Formidable,
+ formidable,
+
+ // alias
+ IncomingForm: Formidable,
+
+ // parsers
+ ...parsers,
+ parsers,
+
+ // misc
+ defaultOptions: Formidable.DEFAULT_OPTIONS,
+ enabledPlugins: Formidable.DEFAULT_OPTIONS.enabledPlugins,
+
+ // plugins
+ plugins: {
+ ...plugins,
+ },
+ });
+ return src$1;
+}
+
+var cookiejar = {};
+
+/* jshint node: true */
+
+var hasRequiredCookiejar;
+
+function requireCookiejar () {
+ if (hasRequiredCookiejar) return cookiejar;
+ hasRequiredCookiejar = 1;
+ (function () {
+
+ function CookieAccessInfo(domain, path, secure, script) {
+ if (this instanceof CookieAccessInfo) {
+ this.domain = domain || undefined;
+ this.path = path || "/";
+ this.secure = !!secure;
+ this.script = !!script;
+ return this;
+ }
+ return new CookieAccessInfo(domain, path, secure, script);
+ }
+ CookieAccessInfo.All = Object.freeze(Object.create(null));
+ cookiejar.CookieAccessInfo = CookieAccessInfo;
+
+ function Cookie(cookiestr, request_domain, request_path) {
+ if (cookiestr instanceof Cookie) {
+ return cookiestr;
+ }
+ if (this instanceof Cookie) {
+ this.name = null;
+ this.value = null;
+ this.expiration_date = Infinity;
+ this.path = String(request_path || "/");
+ this.explicit_path = false;
+ this.domain = request_domain || null;
+ this.explicit_domain = false;
+ this.secure = false; //how to define default?
+ this.noscript = false; //httponly
+ if (cookiestr) {
+ this.parse(cookiestr, request_domain, request_path);
+ }
+ return this;
+ }
+ return new Cookie(cookiestr, request_domain, request_path);
+ }
+ cookiejar.Cookie = Cookie;
+
+ Cookie.prototype.toString = function toString() {
+ var str = [this.name + "=" + this.value];
+ if (this.expiration_date !== Infinity) {
+ str.push("expires=" + (new Date(this.expiration_date)).toGMTString());
+ }
+ if (this.domain) {
+ str.push("domain=" + this.domain);
+ }
+ if (this.path) {
+ str.push("path=" + this.path);
+ }
+ if (this.secure) {
+ str.push("secure");
+ }
+ if (this.noscript) {
+ str.push("httponly");
+ }
+ return str.join("; ");
+ };
+
+ Cookie.prototype.toValueString = function toValueString() {
+ return this.name + "=" + this.value;
+ };
+
+ var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g;
+ Cookie.prototype.parse = function parse(str, request_domain, request_path) {
+ if (this instanceof Cookie) {
+ if ( str.length > 32768 ) {
+ console.warn("Cookie too long for parsing (>32768 characters)");
+ return;
+ }
+
+ var parts = str.split(";").filter(function (value) {
+ return !!value;
+ });
+ var i;
+
+ var pair = parts[0].match(/([^=]+)=([\s\S]*)/);
+ if (!pair) {
+ console.warn("Invalid cookie header encountered. Header: '"+str+"'");
+ return;
+ }
+
+ var key = pair[1];
+ var value = pair[2];
+ if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) {
+ console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'");
+ return;
+ }
+
+ this.name = key;
+ this.value = value;
+
+ for (i = 1; i < parts.length; i += 1) {
+ pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/);
+ key = pair[1].trim().toLowerCase();
+ value = pair[2];
+ switch (key) {
+ case "httponly":
+ this.noscript = true;
+ break;
+ case "expires":
+ this.expiration_date = value ?
+ Number(Date.parse(value)) :
+ Infinity;
+ break;
+ case "path":
+ this.path = value ?
+ value.trim() :
+ "";
+ this.explicit_path = true;
+ break;
+ case "domain":
+ this.domain = value ?
+ value.trim() :
+ "";
+ this.explicit_domain = !!this.domain;
+ break;
+ case "secure":
+ this.secure = true;
+ break;
+ }
+ }
+
+ if (!this.explicit_path) {
+ this.path = request_path || "/";
+ }
+ if (!this.explicit_domain) {
+ this.domain = request_domain;
+ }
+
+ return this;
+ }
+ return new Cookie().parse(str, request_domain, request_path);
+ };
+
+ Cookie.prototype.matches = function matches(access_info) {
+ if (access_info === CookieAccessInfo.All) {
+ return true;
+ }
+ if (this.noscript && access_info.script ||
+ this.secure && !access_info.secure ||
+ !this.collidesWith(access_info)) {
+ return false;
+ }
+ return true;
+ };
+
+ Cookie.prototype.collidesWith = function collidesWith(access_info) {
+ if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) {
+ return false;
+ }
+ if (this.path && access_info.path.indexOf(this.path) !== 0) {
+ return false;
+ }
+ if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) {
+ return false;
+ }
+ var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,'');
+ var cookie_domain = this.domain && this.domain.replace(/^[\.]/,'');
+ if (cookie_domain === access_domain) {
+ return true;
+ }
+ if (cookie_domain) {
+ if (!this.explicit_domain) {
+ return false; // we already checked if the domains were exactly the same
+ }
+ var wildcard = access_domain.indexOf(cookie_domain);
+ if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) {
+ return false;
+ }
+ return true;
+ }
+ return true;
+ };
+
+ function CookieJar() {
+ var cookies, cookies_list, collidable_cookie;
+ if (this instanceof CookieJar) {
+ cookies = Object.create(null); //name: [Cookie]
+
+ this.setCookie = function setCookie(cookie, request_domain, request_path) {
+ var remove, i;
+ cookie = new Cookie(cookie, request_domain, request_path);
+ //Delete the cookie if the set is past the current time
+ remove = cookie.expiration_date <= Date.now();
+ if (cookies[cookie.name] !== undefined) {
+ cookies_list = cookies[cookie.name];
+ for (i = 0; i < cookies_list.length; i += 1) {
+ collidable_cookie = cookies_list[i];
+ if (collidable_cookie.collidesWith(cookie)) {
+ if (remove) {
+ cookies_list.splice(i, 1);
+ if (cookies_list.length === 0) {
+ delete cookies[cookie.name];
+ }
+ return false;
+ }
+ cookies_list[i] = cookie;
+ return cookie;
+ }
+ }
+ if (remove) {
+ return false;
+ }
+ cookies_list.push(cookie);
+ return cookie;
+ }
+ if (remove) {
+ return false;
+ }
+ cookies[cookie.name] = [cookie];
+ return cookies[cookie.name];
+ };
+ //returns a cookie
+ this.getCookie = function getCookie(cookie_name, access_info) {
+ var cookie, i;
+ cookies_list = cookies[cookie_name];
+ if (!cookies_list) {
+ return;
+ }
+ for (i = 0; i < cookies_list.length; i += 1) {
+ cookie = cookies_list[i];
+ if (cookie.expiration_date <= Date.now()) {
+ if (cookies_list.length === 0) {
+ delete cookies[cookie.name];
+ }
+ continue;
+ }
+
+ if (cookie.matches(access_info)) {
+ return cookie;
+ }
+ }
+ };
+ //returns a list of cookies
+ this.getCookies = function getCookies(access_info) {
+ var matches = [], cookie_name, cookie;
+ for (cookie_name in cookies) {
+ cookie = this.getCookie(cookie_name, access_info);
+ if (cookie) {
+ matches.push(cookie);
+ }
+ }
+ matches.toString = function toString() {
+ return matches.join(":");
+ };
+ matches.toValueString = function toValueString() {
+ return matches.map(function (c) {
+ return c.toValueString();
+ }).join('; ');
+ };
+ return matches;
+ };
+
+ return this;
+ }
+ return new CookieJar();
+ }
+ cookiejar.CookieJar = CookieJar;
+
+ //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned.
+ CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) {
+ cookies = Array.isArray(cookies) ?
+ cookies :
+ cookies.split(cookie_str_splitter);
+ var successful = [],
+ i,
+ cookie;
+ cookies = cookies.map(function(item){
+ return new Cookie(item, request_domain, request_path);
+ });
+ for (i = 0; i < cookies.length; i += 1) {
+ cookie = cookies[i];
+ if (this.setCookie(cookie, request_domain, request_path)) {
+ successful.push(cookie);
+ }
+ }
+ return successful;
+ };
+ }());
+ return cookiejar;
+}
+
+var debug_1;
+var hasRequiredDebug;
+
+function requireDebug () {
+ if (hasRequiredDebug) return debug_1;
+ hasRequiredDebug = 1;
+ const debug = (
+ typeof process === 'object' &&
+ process.env &&
+ process.env.NODE_DEBUG &&
+ /\bsemver\b/i.test(process.env.NODE_DEBUG)
+ ) ? (...args) => console.error('SEMVER', ...args)
+ : () => {};
+
+ debug_1 = debug;
+ return debug_1;
+}
+
+var constants$3;
+var hasRequiredConstants;
+
+function requireConstants () {
+ if (hasRequiredConstants) return constants$3;
+ hasRequiredConstants = 1;
+ // Note: this is the semver.org version of the spec that it implements
+ // Not necessarily the package version of this code.
+ const SEMVER_SPEC_VERSION = '2.0.0';
+
+ const MAX_LENGTH = 256;
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
+ /* istanbul ignore next */ 9007199254740991;
+
+ // Max safe segment length for coercion.
+ const MAX_SAFE_COMPONENT_LENGTH = 16;
+
+ constants$3 = {
+ SEMVER_SPEC_VERSION,
+ MAX_LENGTH,
+ MAX_SAFE_INTEGER,
+ MAX_SAFE_COMPONENT_LENGTH,
+ };
+ return constants$3;
+}
+
+var reExports = {};
+var re = {
+ get exports(){ return reExports; },
+ set exports(v){ reExports = v; },
+};
+
+var hasRequiredRe;
+
+function requireRe () {
+ if (hasRequiredRe) return reExports;
+ hasRequiredRe = 1;
+ (function (module, exports) {
+ const { MAX_SAFE_COMPONENT_LENGTH } = requireConstants();
+ const debug = requireDebug();
+ exports = module.exports = {};
+
+ // The actual regexps go on exports.re
+ const re = exports.re = [];
+ const src = exports.src = [];
+ const t = exports.t = {};
+ let R = 0;
+
+ const createToken = (name, value, isGlobal) => {
+ const index = R++;
+ debug(name, index, value);
+ t[name] = index;
+ src[index] = value;
+ re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
+ };
+
+ // The following Regular Expressions can be used for tokenizing,
+ // validating, and parsing SemVer version strings.
+
+ // ## Numeric Identifier
+ // A single `0`, or a non-zero digit followed by zero or more digits.
+
+ createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
+ createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+');
+
+ // ## Non-numeric Identifier
+ // Zero or more digits, followed by a letter or hyphen, and then zero or
+ // more letters, digits, or hyphens.
+
+ createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*');
+
+ // ## Main Version
+ // Three dot-separated numeric identifiers.
+
+ createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
+ `(${src[t.NUMERICIDENTIFIER]})\\.` +
+ `(${src[t.NUMERICIDENTIFIER]})`);
+
+ createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
+
+ // ## Pre-release Version Identifier
+ // A numeric identifier, or a non-numeric identifier.
+
+ createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
+ }|${src[t.NONNUMERICIDENTIFIER]})`);
+
+ createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
+ }|${src[t.NONNUMERICIDENTIFIER]})`);
+
+ // ## Pre-release Version
+ // Hyphen, followed by one or more dot-separated pre-release version
+ // identifiers.
+
+ createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
+ }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
+
+ createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
+ }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
+
+ // ## Build Metadata Identifier
+ // Any combination of digits, letters, or hyphens.
+
+ createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+');
+
+ // ## Build Metadata
+ // Plus sign, followed by one or more period-separated build metadata
+ // identifiers.
+
+ createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
+ }(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
+
+ // ## Full Version String
+ // A main version, followed optionally by a pre-release version and
+ // build metadata.
+
+ // Note that the only major, minor, patch, and pre-release sections of
+ // the version string are capturing groups. The build metadata is not a
+ // capturing group, because it should not ever be used in version
+ // comparison.
+
+ createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
+ }${src[t.PRERELEASE]}?${
+ src[t.BUILD]}?`);
+
+ createToken('FULL', `^${src[t.FULLPLAIN]}$`);
+
+ // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
+ // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
+ // common in the npm registry.
+ createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
+ }${src[t.PRERELEASELOOSE]}?${
+ src[t.BUILD]}?`);
+
+ createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
+
+ createToken('GTLT', '((?:<|>)?=?)');
+
+ // Something like "2.*" or "1.2.x".
+ // Note that "x.x" is a valid xRange identifer, meaning "any version"
+ // Only the first item is strictly required.
+ createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
+ createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
+
+ createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
+ `(?:${src[t.PRERELEASE]})?${
+ src[t.BUILD]}?` +
+ `)?)?`);
+
+ createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+ `(?:${src[t.PRERELEASELOOSE]})?${
+ src[t.BUILD]}?` +
+ `)?)?`);
+
+ createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
+ createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
+
+ // Coercion.
+ // Extract anything that could conceivably be a part of a valid semver
+ createToken('COERCE', `${'(^|[^\\d])' +
+ '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
+ `(?:$|[^\\d])`);
+ createToken('COERCERTL', src[t.COERCE], true);
+
+ // Tilde ranges.
+ // Meaning is "reasonably at or greater than"
+ createToken('LONETILDE', '(?:~>?)');
+
+ createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
+ exports.tildeTrimReplace = '$1~';
+
+ createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
+ createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
+
+ // Caret ranges.
+ // Meaning is "at least and backwards compatible with"
+ createToken('LONECARET', '(?:\\^)');
+
+ createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
+ exports.caretTrimReplace = '$1^';
+
+ createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
+ createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
+
+ // A simple gt/lt/eq thing, or just "" to indicate "any version"
+ createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
+ createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
+
+ // An expression to strip any whitespace between the gtlt and the thing
+ // it modifies, so that `> 1.2.3` ==> `>1.2.3`
+ createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
+ }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
+ exports.comparatorTrimReplace = '$1$2$3';
+
+ // Something like `1.2.3 - 1.2.4`
+ // Note that these all use the loose form, because they'll be
+ // checked against either the strict or loose comparator form
+ // later.
+ createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
+ `\\s+-\\s+` +
+ `(${src[t.XRANGEPLAIN]})` +
+ `\\s*$`);
+
+ createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
+ `\\s+-\\s+` +
+ `(${src[t.XRANGEPLAINLOOSE]})` +
+ `\\s*$`);
+
+ // Star ranges basically just allow anything at all.
+ createToken('STAR', '(<|>)?=?\\s*\\*');
+ // >=0.0.0 is like a star
+ createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$');
+ createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$');
+} (re, reExports));
+ return reExports;
+}
+
+var parseOptions_1;
+var hasRequiredParseOptions;
+
+function requireParseOptions () {
+ if (hasRequiredParseOptions) return parseOptions_1;
+ hasRequiredParseOptions = 1;
+ // parse out just the options we care about so we always get a consistent
+ // obj with keys in a consistent order.
+ const opts = ['includePrerelease', 'loose', 'rtl'];
+ const parseOptions = options =>
+ !options ? {}
+ : typeof options !== 'object' ? { loose: true }
+ : opts.filter(k => options[k]).reduce((o, k) => {
+ o[k] = true;
+ return o
+ }, {});
+ parseOptions_1 = parseOptions;
+ return parseOptions_1;
+}
+
+var identifiers;
+var hasRequiredIdentifiers;
+
+function requireIdentifiers () {
+ if (hasRequiredIdentifiers) return identifiers;
+ hasRequiredIdentifiers = 1;
+ const numeric = /^[0-9]+$/;
+ const compareIdentifiers = (a, b) => {
+ const anum = numeric.test(a);
+ const bnum = numeric.test(b);
+
+ if (anum && bnum) {
+ a = +a;
+ b = +b;
+ }
+
+ return a === b ? 0
+ : (anum && !bnum) ? -1
+ : (bnum && !anum) ? 1
+ : a < b ? -1
+ : 1
+ };
+
+ const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
+
+ identifiers = {
+ compareIdentifiers,
+ rcompareIdentifiers,
+ };
+ return identifiers;
+}
+
+var semver$1;
+var hasRequiredSemver$1;
+
+function requireSemver$1 () {
+ if (hasRequiredSemver$1) return semver$1;
+ hasRequiredSemver$1 = 1;
+ const debug = requireDebug();
+ const { MAX_LENGTH, MAX_SAFE_INTEGER } = requireConstants();
+ const { re, t } = requireRe();
+
+ const parseOptions = requireParseOptions();
+ const { compareIdentifiers } = requireIdentifiers();
+ class SemVer {
+ constructor (version, options) {
+ options = parseOptions(options);
+
+ if (version instanceof SemVer) {
+ if (version.loose === !!options.loose &&
+ version.includePrerelease === !!options.includePrerelease) {
+ return version
+ } else {
+ version = version.version;
+ }
+ } else if (typeof version !== 'string') {
+ throw new TypeError(`Invalid Version: ${version}`)
+ }
+
+ if (version.length > MAX_LENGTH) {
+ throw new TypeError(
+ `version is longer than ${MAX_LENGTH} characters`
+ )
+ }
+
+ debug('SemVer', version, options);
+ this.options = options;
+ this.loose = !!options.loose;
+ // this isn't actually relevant for versions, but keep it so that we
+ // don't run into trouble passing this.options around.
+ this.includePrerelease = !!options.includePrerelease;
+
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
+
+ if (!m) {
+ throw new TypeError(`Invalid Version: ${version}`)
+ }
+
+ this.raw = version;
+
+ // these are actually numbers
+ this.major = +m[1];
+ this.minor = +m[2];
+ this.patch = +m[3];
+
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+ throw new TypeError('Invalid major version')
+ }
+
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+ throw new TypeError('Invalid minor version')
+ }
+
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
+ throw new TypeError('Invalid patch version')
+ }
+
+ // numberify any prerelease numeric ids
+ if (!m[4]) {
+ this.prerelease = [];
+ } else {
+ this.prerelease = m[4].split('.').map((id) => {
+ if (/^[0-9]+$/.test(id)) {
+ const num = +id;
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
+ return num
+ }
+ }
+ return id
+ });
+ }
+
+ this.build = m[5] ? m[5].split('.') : [];
+ this.format();
+ }
+
+ format () {
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
+ if (this.prerelease.length) {
+ this.version += `-${this.prerelease.join('.')}`;
+ }
+ return this.version
+ }
+
+ toString () {
+ return this.version
+ }
+
+ compare (other) {
+ debug('SemVer.compare', this.version, this.options, other);
+ if (!(other instanceof SemVer)) {
+ if (typeof other === 'string' && other === this.version) {
+ return 0
+ }
+ other = new SemVer(other, this.options);
+ }
+
+ if (other.version === this.version) {
+ return 0
+ }
+
+ return this.compareMain(other) || this.comparePre(other)
+ }
+
+ compareMain (other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options);
+ }
+
+ return (
+ compareIdentifiers(this.major, other.major) ||
+ compareIdentifiers(this.minor, other.minor) ||
+ compareIdentifiers(this.patch, other.patch)
+ )
+ }
+
+ comparePre (other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options);
+ }
+
+ // NOT having a prerelease is > having one
+ if (this.prerelease.length && !other.prerelease.length) {
+ return -1
+ } else if (!this.prerelease.length && other.prerelease.length) {
+ return 1
+ } else if (!this.prerelease.length && !other.prerelease.length) {
+ return 0
+ }
+
+ let i = 0;
+ do {
+ const a = this.prerelease[i];
+ const b = other.prerelease[i];
+ debug('prerelease compare', i, a, b);
+ if (a === undefined && b === undefined) {
+ return 0
+ } else if (b === undefined) {
+ return 1
+ } else if (a === undefined) {
+ return -1
+ } else if (a === b) {
+ continue
+ } else {
+ return compareIdentifiers(a, b)
+ }
+ } while (++i)
+ }
+
+ compareBuild (other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options);
+ }
+
+ let i = 0;
+ do {
+ const a = this.build[i];
+ const b = other.build[i];
+ debug('prerelease compare', i, a, b);
+ if (a === undefined && b === undefined) {
+ return 0
+ } else if (b === undefined) {
+ return 1
+ } else if (a === undefined) {
+ return -1
+ } else if (a === b) {
+ continue
+ } else {
+ return compareIdentifiers(a, b)
+ }
+ } while (++i)
+ }
+
+ // preminor will bump the version up to the next minor release, and immediately
+ // down to pre-release. premajor and prepatch work the same way.
+ inc (release, identifier) {
+ switch (release) {
+ case 'premajor':
+ this.prerelease.length = 0;
+ this.patch = 0;
+ this.minor = 0;
+ this.major++;
+ this.inc('pre', identifier);
+ break
+ case 'preminor':
+ this.prerelease.length = 0;
+ this.patch = 0;
+ this.minor++;
+ this.inc('pre', identifier);
+ break
+ case 'prepatch':
+ // If this is already a prerelease, it will bump to the next version
+ // drop any prereleases that might already exist, since they are not
+ // relevant at this point.
+ this.prerelease.length = 0;
+ this.inc('patch', identifier);
+ this.inc('pre', identifier);
+ break
+ // If the input is a non-prerelease version, this acts the same as
+ // prepatch.
+ case 'prerelease':
+ if (this.prerelease.length === 0) {
+ this.inc('patch', identifier);
+ }
+ this.inc('pre', identifier);
+ break
+
+ case 'major':
+ // If this is a pre-major version, bump up to the same major version.
+ // Otherwise increment major.
+ // 1.0.0-5 bumps to 1.0.0
+ // 1.1.0 bumps to 2.0.0
+ if (
+ this.minor !== 0 ||
+ this.patch !== 0 ||
+ this.prerelease.length === 0
+ ) {
+ this.major++;
+ }
+ this.minor = 0;
+ this.patch = 0;
+ this.prerelease = [];
+ break
+ case 'minor':
+ // If this is a pre-minor version, bump up to the same minor version.
+ // Otherwise increment minor.
+ // 1.2.0-5 bumps to 1.2.0
+ // 1.2.1 bumps to 1.3.0
+ if (this.patch !== 0 || this.prerelease.length === 0) {
+ this.minor++;
+ }
+ this.patch = 0;
+ this.prerelease = [];
+ break
+ case 'patch':
+ // If this is not a pre-release version, it will increment the patch.
+ // If it is a pre-release it will bump up to the same patch version.
+ // 1.2.0-5 patches to 1.2.0
+ // 1.2.0 patches to 1.2.1
+ if (this.prerelease.length === 0) {
+ this.patch++;
+ }
+ this.prerelease = [];
+ break
+ // This probably shouldn't be used publicly.
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
+ case 'pre':
+ if (this.prerelease.length === 0) {
+ this.prerelease = [0];
+ } else {
+ let i = this.prerelease.length;
+ while (--i >= 0) {
+ if (typeof this.prerelease[i] === 'number') {
+ this.prerelease[i]++;
+ i = -2;
+ }
+ }
+ if (i === -1) {
+ // didn't increment anything
+ this.prerelease.push(0);
+ }
+ }
+ if (identifier) {
+ // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
+ // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
+ if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
+ if (isNaN(this.prerelease[1])) {
+ this.prerelease = [identifier, 0];
+ }
+ } else {
+ this.prerelease = [identifier, 0];
+ }
+ }
+ break
+
+ default:
+ throw new Error(`invalid increment argument: ${release}`)
+ }
+ this.format();
+ this.raw = this.version;
+ return this
+ }
+ }
+
+ semver$1 = SemVer;
+ return semver$1;
+}
+
+var compare_1;
+var hasRequiredCompare;
+
+function requireCompare () {
+ if (hasRequiredCompare) return compare_1;
+ hasRequiredCompare = 1;
+ const SemVer = requireSemver$1();
+ const compare = (a, b, loose) =>
+ new SemVer(a, loose).compare(new SemVer(b, loose));
+
+ compare_1 = compare;
+ return compare_1;
+}
+
+var gte_1;
+var hasRequiredGte;
+
+function requireGte () {
+ if (hasRequiredGte) return gte_1;
+ hasRequiredGte = 1;
+ const compare = requireCompare();
+ const gte = (a, b, loose) => compare(a, b, loose) >= 0;
+ gte_1 = gte;
+ return gte_1;
+}
+
+var utils$2 = {};
+
+var hasRequiredUtils;
+
+function requireUtils () {
+ if (hasRequiredUtils) return utils$2;
+ hasRequiredUtils = 1;
+ (function (exports) {
+
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
+
+ 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 _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; }
+
+ /**
+ * Return the mime type for the given `str`.
+ *
+ * @param {String} str
+ * @return {String}
+ * @api private
+ */
+ exports.type = function (string_) {
+ return string_.split(/ *; */).shift();
+ };
+ /**
+ * Return header field parameters.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
+ */
+
+
+ exports.params = function (value) {
+ var object = {};
+
+ var _iterator = _createForOfIteratorHelper(value.split(/ *; */)),
+ _step;
+
+ try {
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ var string_ = _step.value;
+ var parts = string_.split(/ *= */);
+ var key = parts.shift();
+
+ var _value = parts.shift();
+
+ if (key && _value) object[key] = _value;
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+
+ return object;
+ };
+ /**
+ * Parse Link header fields.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
+ */
+
+
+ exports.parseLinks = function (value) {
+ var object = {};
+
+ var _iterator2 = _createForOfIteratorHelper(value.split(/ *, */)),
+ _step2;
+
+ try {
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
+ var string_ = _step2.value;
+ var parts = string_.split(/ *; */);
+ var url = parts[0].slice(1, -1);
+ var rel = parts[1].split(/ *= */)[1].slice(1, -1);
+ object[rel] = url;
+ }
+ } catch (err) {
+ _iterator2.e(err);
+ } finally {
+ _iterator2.f();
+ }
+
+ return object;
+ };
+ /**
+ * Strip content related fields from `header`.
+ *
+ * @param {Object} header
+ * @return {Object} header
+ * @api private
+ */
+
+
+ exports.cleanHeader = function (header, changesOrigin) {
+ delete header['content-type'];
+ delete header['content-length'];
+ delete header['transfer-encoding'];
+ delete header.host; // secuirty
+
+ if (changesOrigin) {
+ delete header.authorization;
+ delete header.cookie;
+ }
+
+ return header;
+ };
+ /**
+ * Check if `obj` is an object.
+ *
+ * @param {Object} object
+ * @return {Boolean}
+ * @api private
+ */
+
+
+ exports.isObject = function (object) {
+ return object !== null && _typeof(object) === 'object';
+ };
+ /**
+ * Object.hasOwn fallback/polyfill.
+ *
+ * @type {(object: object, property: string) => boolean} object
+ * @api private
+ */
+
+
+ exports.hasOwn = Object.hasOwn || function (object, property) {
+ if (object == null) {
+ throw new TypeError('Cannot convert undefined or null to object');
+ }
+
+ return Object.prototype.hasOwnProperty.call(new Object(object), property);
+ };
+
+ exports.mixin = function (target, source) {
+ for (var key in source) {
+ if (exports.hasOwn(source, key)) {
+ target[key] = source[key];
+ }
+ }
+ };
+
+} (utils$2));
+ return utils$2;
+}
+
+var parse_1;
+var hasRequiredParse;
+
+function requireParse () {
+ if (hasRequiredParse) return parse_1;
+ hasRequiredParse = 1;
+ const { MAX_LENGTH } = requireConstants();
+ const { re, t } = requireRe();
+ const SemVer = requireSemver$1();
+
+ const parseOptions = requireParseOptions();
+ const parse = (version, options) => {
+ options = parseOptions(options);
+
+ if (version instanceof SemVer) {
+ return version
+ }
+
+ if (typeof version !== 'string') {
+ return null
+ }
+
+ if (version.length > MAX_LENGTH) {
+ return null
+ }
+
+ const r = options.loose ? re[t.LOOSE] : re[t.FULL];
+ if (!r.test(version)) {
+ return null
+ }
+
+ try {
+ return new SemVer(version, options)
+ } catch (er) {
+ return null
+ }
+ };
+
+ parse_1 = parse;
+ return parse_1;
+}
+
+var valid_1;
+var hasRequiredValid$1;
+
+function requireValid$1 () {
+ if (hasRequiredValid$1) return valid_1;
+ hasRequiredValid$1 = 1;
+ const parse = requireParse();
+ const valid = (version, options) => {
+ const v = parse(version, options);
+ return v ? v.version : null
+ };
+ valid_1 = valid;
+ return valid_1;
+}
+
+var clean_1;
+var hasRequiredClean;
+
+function requireClean () {
+ if (hasRequiredClean) return clean_1;
+ hasRequiredClean = 1;
+ const parse = requireParse();
+ const clean = (version, options) => {
+ const s = parse(version.trim().replace(/^[=v]+/, ''), options);
+ return s ? s.version : null
+ };
+ clean_1 = clean;
+ return clean_1;
+}
+
+var inc_1;
+var hasRequiredInc;
+
+function requireInc () {
+ if (hasRequiredInc) return inc_1;
+ hasRequiredInc = 1;
+ const SemVer = requireSemver$1();
+
+ const inc = (version, release, options, identifier) => {
+ if (typeof (options) === 'string') {
+ identifier = options;
+ options = undefined;
+ }
+
+ try {
+ return new SemVer(
+ version instanceof SemVer ? version.version : version,
+ options
+ ).inc(release, identifier).version
+ } catch (er) {
+ return null
+ }
+ };
+ inc_1 = inc;
+ return inc_1;
+}
+
+var eq_1;
+var hasRequiredEq;
+
+function requireEq () {
+ if (hasRequiredEq) return eq_1;
+ hasRequiredEq = 1;
+ const compare = requireCompare();
+ const eq = (a, b, loose) => compare(a, b, loose) === 0;
+ eq_1 = eq;
+ return eq_1;
+}
+
+var diff_1;
+var hasRequiredDiff;
+
+function requireDiff () {
+ if (hasRequiredDiff) return diff_1;
+ hasRequiredDiff = 1;
+ const parse = requireParse();
+ const eq = requireEq();
+
+ const diff = (version1, version2) => {
+ if (eq(version1, version2)) {
+ return null
+ } else {
+ const v1 = parse(version1);
+ const v2 = parse(version2);
+ const hasPre = v1.prerelease.length || v2.prerelease.length;
+ const prefix = hasPre ? 'pre' : '';
+ const defaultResult = hasPre ? 'prerelease' : '';
+ for (const key in v1) {
+ if (key === 'major' || key === 'minor' || key === 'patch') {
+ if (v1[key] !== v2[key]) {
+ return prefix + key
+ }
+ }
+ }
+ return defaultResult // may be undefined
+ }
+ };
+ diff_1 = diff;
+ return diff_1;
+}
+
+var major_1;
+var hasRequiredMajor;
+
+function requireMajor () {
+ if (hasRequiredMajor) return major_1;
+ hasRequiredMajor = 1;
+ const SemVer = requireSemver$1();
+ const major = (a, loose) => new SemVer(a, loose).major;
+ major_1 = major;
+ return major_1;
+}
+
+var minor_1;
+var hasRequiredMinor;
+
+function requireMinor () {
+ if (hasRequiredMinor) return minor_1;
+ hasRequiredMinor = 1;
+ const SemVer = requireSemver$1();
+ const minor = (a, loose) => new SemVer(a, loose).minor;
+ minor_1 = minor;
+ return minor_1;
+}
+
+var patch_1;
+var hasRequiredPatch;
+
+function requirePatch () {
+ if (hasRequiredPatch) return patch_1;
+ hasRequiredPatch = 1;
+ const SemVer = requireSemver$1();
+ const patch = (a, loose) => new SemVer(a, loose).patch;
+ patch_1 = patch;
+ return patch_1;
+}
+
+var prerelease_1;
+var hasRequiredPrerelease;
+
+function requirePrerelease () {
+ if (hasRequiredPrerelease) return prerelease_1;
+ hasRequiredPrerelease = 1;
+ const parse = requireParse();
+ const prerelease = (version, options) => {
+ const parsed = parse(version, options);
+ return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
+ };
+ prerelease_1 = prerelease;
+ return prerelease_1;
+}
+
+var rcompare_1;
+var hasRequiredRcompare;
+
+function requireRcompare () {
+ if (hasRequiredRcompare) return rcompare_1;
+ hasRequiredRcompare = 1;
+ const compare = requireCompare();
+ const rcompare = (a, b, loose) => compare(b, a, loose);
+ rcompare_1 = rcompare;
+ return rcompare_1;
+}
+
+var compareLoose_1;
+var hasRequiredCompareLoose;
+
+function requireCompareLoose () {
+ if (hasRequiredCompareLoose) return compareLoose_1;
+ hasRequiredCompareLoose = 1;
+ const compare = requireCompare();
+ const compareLoose = (a, b) => compare(a, b, true);
+ compareLoose_1 = compareLoose;
+ return compareLoose_1;
+}
+
+var compareBuild_1;
+var hasRequiredCompareBuild;
+
+function requireCompareBuild () {
+ if (hasRequiredCompareBuild) return compareBuild_1;
+ hasRequiredCompareBuild = 1;
+ const SemVer = requireSemver$1();
+ const compareBuild = (a, b, loose) => {
+ const versionA = new SemVer(a, loose);
+ const versionB = new SemVer(b, loose);
+ return versionA.compare(versionB) || versionA.compareBuild(versionB)
+ };
+ compareBuild_1 = compareBuild;
+ return compareBuild_1;
+}
+
+var sort_1;
+var hasRequiredSort;
+
+function requireSort () {
+ if (hasRequiredSort) return sort_1;
+ hasRequiredSort = 1;
+ const compareBuild = requireCompareBuild();
+ const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
+ sort_1 = sort;
+ return sort_1;
+}
+
+var rsort_1;
+var hasRequiredRsort;
+
+function requireRsort () {
+ if (hasRequiredRsort) return rsort_1;
+ hasRequiredRsort = 1;
+ const compareBuild = requireCompareBuild();
+ const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
+ rsort_1 = rsort;
+ return rsort_1;
+}
+
+var gt_1;
+var hasRequiredGt;
+
+function requireGt () {
+ if (hasRequiredGt) return gt_1;
+ hasRequiredGt = 1;
+ const compare = requireCompare();
+ const gt = (a, b, loose) => compare(a, b, loose) > 0;
+ gt_1 = gt;
+ return gt_1;
+}
+
+var lt_1;
+var hasRequiredLt;
+
+function requireLt () {
+ if (hasRequiredLt) return lt_1;
+ hasRequiredLt = 1;
+ const compare = requireCompare();
+ const lt = (a, b, loose) => compare(a, b, loose) < 0;
+ lt_1 = lt;
+ return lt_1;
+}
+
+var neq_1;
+var hasRequiredNeq;
+
+function requireNeq () {
+ if (hasRequiredNeq) return neq_1;
+ hasRequiredNeq = 1;
+ const compare = requireCompare();
+ const neq = (a, b, loose) => compare(a, b, loose) !== 0;
+ neq_1 = neq;
+ return neq_1;
+}
+
+var lte_1;
+var hasRequiredLte;
+
+function requireLte () {
+ if (hasRequiredLte) return lte_1;
+ hasRequiredLte = 1;
+ const compare = requireCompare();
+ const lte = (a, b, loose) => compare(a, b, loose) <= 0;
+ lte_1 = lte;
+ return lte_1;
+}
+
+var cmp_1;
+var hasRequiredCmp;
+
+function requireCmp () {
+ if (hasRequiredCmp) return cmp_1;
+ hasRequiredCmp = 1;
+ const eq = requireEq();
+ const neq = requireNeq();
+ const gt = requireGt();
+ const gte = requireGte();
+ const lt = requireLt();
+ const lte = requireLte();
+
+ const cmp = (a, op, b, loose) => {
+ switch (op) {
+ case '===':
+ if (typeof a === 'object') {
+ a = a.version;
+ }
+ if (typeof b === 'object') {
+ b = b.version;
+ }
+ return a === b
+
+ case '!==':
+ if (typeof a === 'object') {
+ a = a.version;
+ }
+ if (typeof b === 'object') {
+ b = b.version;
+ }
+ return a !== b
+
+ case '':
+ case '=':
+ case '==':
+ return eq(a, b, loose)
+
+ case '!=':
+ return neq(a, b, loose)
+
+ case '>':
+ return gt(a, b, loose)
+
+ case '>=':
+ return gte(a, b, loose)
+
+ case '<':
+ return lt(a, b, loose)
+
+ case '<=':
+ return lte(a, b, loose)
+
+ default:
+ throw new TypeError(`Invalid operator: ${op}`)
+ }
+ };
+ cmp_1 = cmp;
+ return cmp_1;
+}
+
+var coerce_1;
+var hasRequiredCoerce;
+
+function requireCoerce () {
+ if (hasRequiredCoerce) return coerce_1;
+ hasRequiredCoerce = 1;
+ const SemVer = requireSemver$1();
+ const parse = requireParse();
+ const { re, t } = requireRe();
+
+ const coerce = (version, options) => {
+ if (version instanceof SemVer) {
+ return version
+ }
+
+ if (typeof version === 'number') {
+ version = String(version);
+ }
+
+ if (typeof version !== 'string') {
+ return null
+ }
+
+ options = options || {};
+
+ let match = null;
+ if (!options.rtl) {
+ match = version.match(re[t.COERCE]);
+ } else {
+ // Find the right-most coercible string that does not share
+ // a terminus with a more left-ward coercible string.
+ // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
+ //
+ // Walk through the string checking with a /g regexp
+ // Manually set the index so as to pick up overlapping matches.
+ // Stop when we get a match that ends at the string end, since no
+ // coercible string can be more right-ward without the same terminus.
+ let next;
+ while ((next = re[t.COERCERTL].exec(version)) &&
+ (!match || match.index + match[0].length !== version.length)
+ ) {
+ if (!match ||
+ next.index + next[0].length !== match.index + match[0].length) {
+ match = next;
+ }
+ re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
+ }
+ // leave it in a clean state
+ re[t.COERCERTL].lastIndex = -1;
+ }
+
+ if (match === null) {
+ return null
+ }
+
+ return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
+ };
+ coerce_1 = coerce;
+ return coerce_1;
+}
+
+var iterator;
+var hasRequiredIterator;
+
+function requireIterator () {
+ if (hasRequiredIterator) return iterator;
+ hasRequiredIterator = 1;
+ iterator = function (Yallist) {
+ Yallist.prototype[Symbol.iterator] = function* () {
+ for (let walker = this.head; walker; walker = walker.next) {
+ yield walker.value;
+ }
+ };
+ };
+ return iterator;
+}
+
+var yallist;
+var hasRequiredYallist;
+
+function requireYallist () {
+ if (hasRequiredYallist) return yallist;
+ hasRequiredYallist = 1;
+ yallist = Yallist;
+
+ Yallist.Node = Node;
+ Yallist.create = Yallist;
+
+ function Yallist (list) {
+ var self = this;
+ if (!(self instanceof Yallist)) {
+ self = new Yallist();
+ }
+
+ self.tail = null;
+ self.head = null;
+ self.length = 0;
+
+ if (list && typeof list.forEach === 'function') {
+ list.forEach(function (item) {
+ self.push(item);
+ });
+ } else if (arguments.length > 0) {
+ for (var i = 0, l = arguments.length; i < l; i++) {
+ self.push(arguments[i]);
+ }
+ }
+
+ return self
+ }
+
+ Yallist.prototype.removeNode = function (node) {
+ if (node.list !== this) {
+ throw new Error('removing node which does not belong to this list')
+ }
+
+ var next = node.next;
+ var prev = node.prev;
+
+ if (next) {
+ next.prev = prev;
+ }
+
+ if (prev) {
+ prev.next = next;
+ }
+
+ if (node === this.head) {
+ this.head = next;
+ }
+ if (node === this.tail) {
+ this.tail = prev;
+ }
+
+ node.list.length--;
+ node.next = null;
+ node.prev = null;
+ node.list = null;
+
+ return next
+ };
+
+ Yallist.prototype.unshiftNode = function (node) {
+ if (node === this.head) {
+ return
+ }
+
+ if (node.list) {
+ node.list.removeNode(node);
+ }
+
+ var head = this.head;
+ node.list = this;
+ node.next = head;
+ if (head) {
+ head.prev = node;
+ }
+
+ this.head = node;
+ if (!this.tail) {
+ this.tail = node;
+ }
+ this.length++;
+ };
+
+ Yallist.prototype.pushNode = function (node) {
+ if (node === this.tail) {
+ return
+ }
+
+ if (node.list) {
+ node.list.removeNode(node);
+ }
+
+ var tail = this.tail;
+ node.list = this;
+ node.prev = tail;
+ if (tail) {
+ tail.next = node;
+ }
+
+ this.tail = node;
+ if (!this.head) {
+ this.head = node;
+ }
+ this.length++;
+ };
+
+ Yallist.prototype.push = function () {
+ for (var i = 0, l = arguments.length; i < l; i++) {
+ push(this, arguments[i]);
+ }
+ return this.length
+ };
+
+ Yallist.prototype.unshift = function () {
+ for (var i = 0, l = arguments.length; i < l; i++) {
+ unshift(this, arguments[i]);
+ }
+ return this.length
+ };
+
+ Yallist.prototype.pop = function () {
+ if (!this.tail) {
+ return undefined
+ }
+
+ var res = this.tail.value;
+ this.tail = this.tail.prev;
+ if (this.tail) {
+ this.tail.next = null;
+ } else {
+ this.head = null;
+ }
+ this.length--;
+ return res
+ };
+
+ Yallist.prototype.shift = function () {
+ if (!this.head) {
+ return undefined
+ }
+
+ var res = this.head.value;
+ this.head = this.head.next;
+ if (this.head) {
+ this.head.prev = null;
+ } else {
+ this.tail = null;
+ }
+ this.length--;
+ return res
+ };
+
+ Yallist.prototype.forEach = function (fn, thisp) {
+ thisp = thisp || this;
+ for (var walker = this.head, i = 0; walker !== null; i++) {
+ fn.call(thisp, walker.value, i, this);
+ walker = walker.next;
+ }
+ };
+
+ Yallist.prototype.forEachReverse = function (fn, thisp) {
+ thisp = thisp || this;
+ for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
+ fn.call(thisp, walker.value, i, this);
+ walker = walker.prev;
+ }
+ };
+
+ Yallist.prototype.get = function (n) {
+ for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
+ // abort out of the list early if we hit a cycle
+ walker = walker.next;
+ }
+ if (i === n && walker !== null) {
+ return walker.value
+ }
+ };
+
+ Yallist.prototype.getReverse = function (n) {
+ for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
+ // abort out of the list early if we hit a cycle
+ walker = walker.prev;
+ }
+ if (i === n && walker !== null) {
+ return walker.value
+ }
+ };
+
+ Yallist.prototype.map = function (fn, thisp) {
+ thisp = thisp || this;
+ var res = new Yallist();
+ for (var walker = this.head; walker !== null;) {
+ res.push(fn.call(thisp, walker.value, this));
+ walker = walker.next;
+ }
+ return res
+ };
+
+ Yallist.prototype.mapReverse = function (fn, thisp) {
+ thisp = thisp || this;
+ var res = new Yallist();
+ for (var walker = this.tail; walker !== null;) {
+ res.push(fn.call(thisp, walker.value, this));
+ walker = walker.prev;
+ }
+ return res
+ };
+
+ Yallist.prototype.reduce = function (fn, initial) {
+ var acc;
+ var walker = this.head;
+ if (arguments.length > 1) {
+ acc = initial;
+ } else if (this.head) {
+ walker = this.head.next;
+ acc = this.head.value;
+ } else {
+ throw new TypeError('Reduce of empty list with no initial value')
+ }
+
+ for (var i = 0; walker !== null; i++) {
+ acc = fn(acc, walker.value, i);
+ walker = walker.next;
+ }
+
+ return acc
+ };
+
+ Yallist.prototype.reduceReverse = function (fn, initial) {
+ var acc;
+ var walker = this.tail;
+ if (arguments.length > 1) {
+ acc = initial;
+ } else if (this.tail) {
+ walker = this.tail.prev;
+ acc = this.tail.value;
+ } else {
+ throw new TypeError('Reduce of empty list with no initial value')
+ }
+
+ for (var i = this.length - 1; walker !== null; i--) {
+ acc = fn(acc, walker.value, i);
+ walker = walker.prev;
+ }
+
+ return acc
+ };
+
+ Yallist.prototype.toArray = function () {
+ var arr = new Array(this.length);
+ for (var i = 0, walker = this.head; walker !== null; i++) {
+ arr[i] = walker.value;
+ walker = walker.next;
+ }
+ return arr
+ };
+
+ Yallist.prototype.toArrayReverse = function () {
+ var arr = new Array(this.length);
+ for (var i = 0, walker = this.tail; walker !== null; i++) {
+ arr[i] = walker.value;
+ walker = walker.prev;
+ }
+ return arr
+ };
+
+ Yallist.prototype.slice = function (from, to) {
+ to = to || this.length;
+ if (to < 0) {
+ to += this.length;
+ }
+ from = from || 0;
+ if (from < 0) {
+ from += this.length;
+ }
+ var ret = new Yallist();
+ if (to < from || to < 0) {
+ return ret
+ }
+ if (from < 0) {
+ from = 0;
+ }
+ if (to > this.length) {
+ to = this.length;
+ }
+ for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
+ walker = walker.next;
+ }
+ for (; walker !== null && i < to; i++, walker = walker.next) {
+ ret.push(walker.value);
+ }
+ return ret
+ };
+
+ Yallist.prototype.sliceReverse = function (from, to) {
+ to = to || this.length;
+ if (to < 0) {
+ to += this.length;
+ }
+ from = from || 0;
+ if (from < 0) {
+ from += this.length;
+ }
+ var ret = new Yallist();
+ if (to < from || to < 0) {
+ return ret
+ }
+ if (from < 0) {
+ from = 0;
+ }
+ if (to > this.length) {
+ to = this.length;
+ }
+ for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
+ walker = walker.prev;
+ }
+ for (; walker !== null && i > from; i--, walker = walker.prev) {
+ ret.push(walker.value);
+ }
+ return ret
+ };
+
+ Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
+ if (start > this.length) {
+ start = this.length - 1;
+ }
+ if (start < 0) {
+ start = this.length + start;
+ }
+
+ for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
+ walker = walker.next;
+ }
+
+ var ret = [];
+ for (var i = 0; walker && i < deleteCount; i++) {
+ ret.push(walker.value);
+ walker = this.removeNode(walker);
+ }
+ if (walker === null) {
+ walker = this.tail;
+ }
+
+ if (walker !== this.head && walker !== this.tail) {
+ walker = walker.prev;
+ }
+
+ for (var i = 0; i < nodes.length; i++) {
+ walker = insert(this, walker, nodes[i]);
+ }
+ return ret;
+ };
+
+ Yallist.prototype.reverse = function () {
+ var head = this.head;
+ var tail = this.tail;
+ for (var walker = head; walker !== null; walker = walker.prev) {
+ var p = walker.prev;
+ walker.prev = walker.next;
+ walker.next = p;
+ }
+ this.head = tail;
+ this.tail = head;
+ return this
+ };
+
+ function insert (self, node, value) {
+ var inserted = node === self.head ?
+ new Node(value, null, node, self) :
+ new Node(value, node, node.next, self);
+
+ if (inserted.next === null) {
+ self.tail = inserted;
+ }
+ if (inserted.prev === null) {
+ self.head = inserted;
+ }
+
+ self.length++;
+
+ return inserted
+ }
+
+ function push (self, item) {
+ self.tail = new Node(item, self.tail, null, self);
+ if (!self.head) {
+ self.head = self.tail;
+ }
+ self.length++;
+ }
+
+ function unshift (self, item) {
+ self.head = new Node(item, null, self.head, self);
+ if (!self.tail) {
+ self.tail = self.head;
+ }
+ self.length++;
+ }
+
+ function Node (value, prev, next, list) {
+ if (!(this instanceof Node)) {
+ return new Node(value, prev, next, list)
+ }
+
+ this.list = list;
+ this.value = value;
+
+ if (prev) {
+ prev.next = this;
+ this.prev = prev;
+ } else {
+ this.prev = null;
+ }
+
+ if (next) {
+ next.prev = this;
+ this.next = next;
+ } else {
+ this.next = null;
+ }
+ }
+
+ try {
+ // add if support for Symbol.iterator is present
+ requireIterator()(Yallist);
+ } catch (er) {}
+ return yallist;
+}
+
+var lruCache;
+var hasRequiredLruCache;
+
+function requireLruCache () {
+ if (hasRequiredLruCache) return lruCache;
+ hasRequiredLruCache = 1;
+
+ // A linked list to keep track of recently-used-ness
+ const Yallist = requireYallist();
+
+ const MAX = Symbol('max');
+ const LENGTH = Symbol('length');
+ const LENGTH_CALCULATOR = Symbol('lengthCalculator');
+ const ALLOW_STALE = Symbol('allowStale');
+ const MAX_AGE = Symbol('maxAge');
+ const DISPOSE = Symbol('dispose');
+ const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');
+ const LRU_LIST = Symbol('lruList');
+ const CACHE = Symbol('cache');
+ const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');
+
+ const naiveLength = () => 1;
+
+ // lruList is a yallist where the head is the youngest
+ // item, and the tail is the oldest. the list contains the Hit
+ // objects as the entries.
+ // Each Hit object has a reference to its Yallist.Node. This
+ // never changes.
+ //
+ // cache is a Map (or PseudoMap) that matches the keys to
+ // the Yallist.Node object.
+ class LRUCache {
+ constructor (options) {
+ if (typeof options === 'number')
+ options = { max: options };
+
+ if (!options)
+ options = {};
+
+ if (options.max && (typeof options.max !== 'number' || options.max < 0))
+ throw new TypeError('max must be a non-negative number')
+ // Kind of weird to have a default max of Infinity, but oh well.
+ this[MAX] = options.max || Infinity;
+
+ const lc = options.length || naiveLength;
+ this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc;
+ this[ALLOW_STALE] = options.stale || false;
+ if (options.maxAge && typeof options.maxAge !== 'number')
+ throw new TypeError('maxAge must be a number')
+ this[MAX_AGE] = options.maxAge || 0;
+ this[DISPOSE] = options.dispose;
+ this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
+ this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
+ this.reset();
+ }
+
+ // resize the cache when the max changes.
+ set max (mL) {
+ if (typeof mL !== 'number' || mL < 0)
+ throw new TypeError('max must be a non-negative number')
+
+ this[MAX] = mL || Infinity;
+ trim(this);
+ }
+ get max () {
+ return this[MAX]
+ }
+
+ set allowStale (allowStale) {
+ this[ALLOW_STALE] = !!allowStale;
+ }
+ get allowStale () {
+ return this[ALLOW_STALE]
+ }
+
+ set maxAge (mA) {
+ if (typeof mA !== 'number')
+ throw new TypeError('maxAge must be a non-negative number')
+
+ this[MAX_AGE] = mA;
+ trim(this);
+ }
+ get maxAge () {
+ return this[MAX_AGE]
+ }
+
+ // resize the cache when the lengthCalculator changes.
+ set lengthCalculator (lC) {
+ if (typeof lC !== 'function')
+ lC = naiveLength;
+
+ if (lC !== this[LENGTH_CALCULATOR]) {
+ this[LENGTH_CALCULATOR] = lC;
+ this[LENGTH] = 0;
+ this[LRU_LIST].forEach(hit => {
+ hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
+ this[LENGTH] += hit.length;
+ });
+ }
+ trim(this);
+ }
+ get lengthCalculator () { return this[LENGTH_CALCULATOR] }
+
+ get length () { return this[LENGTH] }
+ get itemCount () { return this[LRU_LIST].length }
+
+ rforEach (fn, thisp) {
+ thisp = thisp || this;
+ for (let walker = this[LRU_LIST].tail; walker !== null;) {
+ const prev = walker.prev;
+ forEachStep(this, fn, walker, thisp);
+ walker = prev;
+ }
+ }
+
+ forEach (fn, thisp) {
+ thisp = thisp || this;
+ for (let walker = this[LRU_LIST].head; walker !== null;) {
+ const next = walker.next;
+ forEachStep(this, fn, walker, thisp);
+ walker = next;
+ }
+ }
+
+ keys () {
+ return this[LRU_LIST].toArray().map(k => k.key)
+ }
+
+ values () {
+ return this[LRU_LIST].toArray().map(k => k.value)
+ }
+
+ reset () {
+ if (this[DISPOSE] &&
+ this[LRU_LIST] &&
+ this[LRU_LIST].length) {
+ this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));
+ }
+
+ this[CACHE] = new Map(); // hash of items by key
+ this[LRU_LIST] = new Yallist(); // list of items in order of use recency
+ this[LENGTH] = 0; // length of items in the list
+ }
+
+ dump () {
+ return this[LRU_LIST].map(hit =>
+ isStale(this, hit) ? false : {
+ k: hit.key,
+ v: hit.value,
+ e: hit.now + (hit.maxAge || 0)
+ }).toArray().filter(h => h)
+ }
+
+ dumpLru () {
+ return this[LRU_LIST]
+ }
+
+ set (key, value, maxAge) {
+ maxAge = maxAge || this[MAX_AGE];
+
+ if (maxAge && typeof maxAge !== 'number')
+ throw new TypeError('maxAge must be a number')
+
+ const now = maxAge ? Date.now() : 0;
+ const len = this[LENGTH_CALCULATOR](value, key);
+
+ if (this[CACHE].has(key)) {
+ if (len > this[MAX]) {
+ del(this, this[CACHE].get(key));
+ return false
+ }
+
+ const node = this[CACHE].get(key);
+ const item = node.value;
+
+ // dispose of the old one before overwriting
+ // split out into 2 ifs for better coverage tracking
+ if (this[DISPOSE]) {
+ if (!this[NO_DISPOSE_ON_SET])
+ this[DISPOSE](key, item.value);
+ }
+
+ item.now = now;
+ item.maxAge = maxAge;
+ item.value = value;
+ this[LENGTH] += len - item.length;
+ item.length = len;
+ this.get(key);
+ trim(this);
+ return true
+ }
+
+ const hit = new Entry(key, value, len, now, maxAge);
+
+ // oversized objects fall out of cache automatically.
+ if (hit.length > this[MAX]) {
+ if (this[DISPOSE])
+ this[DISPOSE](key, value);
+
+ return false
+ }
+
+ this[LENGTH] += hit.length;
+ this[LRU_LIST].unshift(hit);
+ this[CACHE].set(key, this[LRU_LIST].head);
+ trim(this);
+ return true
+ }
+
+ has (key) {
+ if (!this[CACHE].has(key)) return false
+ const hit = this[CACHE].get(key).value;
+ return !isStale(this, hit)
+ }
+
+ get (key) {
+ return get(this, key, true)
+ }
+
+ peek (key) {
+ return get(this, key, false)
+ }
+
+ pop () {
+ const node = this[LRU_LIST].tail;
+ if (!node)
+ return null
+
+ del(this, node);
+ return node.value
+ }
+
+ del (key) {
+ del(this, this[CACHE].get(key));
+ }
+
+ load (arr) {
+ // reset the cache
+ this.reset();
+
+ const now = Date.now();
+ // A previous serialized cache has the most recent items first
+ for (let l = arr.length - 1; l >= 0; l--) {
+ const hit = arr[l];
+ const expiresAt = hit.e || 0;
+ if (expiresAt === 0)
+ // the item was created without expiration in a non aged cache
+ this.set(hit.k, hit.v);
+ else {
+ const maxAge = expiresAt - now;
+ // dont add already expired items
+ if (maxAge > 0) {
+ this.set(hit.k, hit.v, maxAge);
+ }
+ }
+ }
+ }
+
+ prune () {
+ this[CACHE].forEach((value, key) => get(this, key, false));
+ }
+ }
+
+ const get = (self, key, doUse) => {
+ const node = self[CACHE].get(key);
+ if (node) {
+ const hit = node.value;
+ if (isStale(self, hit)) {
+ del(self, node);
+ if (!self[ALLOW_STALE])
+ return undefined
+ } else {
+ if (doUse) {
+ if (self[UPDATE_AGE_ON_GET])
+ node.value.now = Date.now();
+ self[LRU_LIST].unshiftNode(node);
+ }
+ }
+ return hit.value
+ }
+ };
+
+ const isStale = (self, hit) => {
+ if (!hit || (!hit.maxAge && !self[MAX_AGE]))
+ return false
+
+ const diff = Date.now() - hit.now;
+ return hit.maxAge ? diff > hit.maxAge
+ : self[MAX_AGE] && (diff > self[MAX_AGE])
+ };
+
+ const trim = self => {
+ if (self[LENGTH] > self[MAX]) {
+ for (let walker = self[LRU_LIST].tail;
+ self[LENGTH] > self[MAX] && walker !== null;) {
+ // We know that we're about to delete this one, and also
+ // what the next least recently used key will be, so just
+ // go ahead and set it now.
+ const prev = walker.prev;
+ del(self, walker);
+ walker = prev;
+ }
+ }
+ };
+
+ const del = (self, node) => {
+ if (node) {
+ const hit = node.value;
+ if (self[DISPOSE])
+ self[DISPOSE](hit.key, hit.value);
+
+ self[LENGTH] -= hit.length;
+ self[CACHE].delete(hit.key);
+ self[LRU_LIST].removeNode(node);
+ }
+ };
+
+ class Entry {
+ constructor (key, value, length, now, maxAge) {
+ this.key = key;
+ this.value = value;
+ this.length = length;
+ this.now = now;
+ this.maxAge = maxAge || 0;
+ }
+ }
+
+ const forEachStep = (self, fn, node, thisp) => {
+ let hit = node.value;
+ if (isStale(self, hit)) {
+ del(self, node);
+ if (!self[ALLOW_STALE])
+ hit = undefined;
+ }
+ if (hit)
+ fn.call(thisp, hit.value, hit.key, self);
+ };
+
+ lruCache = LRUCache;
+ return lruCache;
+}
+
+var range$2;
+var hasRequiredRange;
+
+function requireRange () {
+ if (hasRequiredRange) return range$2;
+ hasRequiredRange = 1;
+ // hoisted class for cyclic dependency
+ class Range {
+ constructor (range, options) {
+ options = parseOptions(options);
+
+ if (range instanceof Range) {
+ if (
+ range.loose === !!options.loose &&
+ range.includePrerelease === !!options.includePrerelease
+ ) {
+ return range
+ } else {
+ return new Range(range.raw, options)
+ }
+ }
+
+ if (range instanceof Comparator) {
+ // just put it in the set and return
+ this.raw = range.value;
+ this.set = [[range]];
+ this.format();
+ return this
+ }
+
+ this.options = options;
+ this.loose = !!options.loose;
+ this.includePrerelease = !!options.includePrerelease;
+
+ // First, split based on boolean or ||
+ this.raw = range;
+ this.set = range
+ .split('||')
+ // map the range to a 2d array of comparators
+ .map(r => this.parseRange(r.trim()))
+ // throw out any comparator lists that are empty
+ // this generally means that it was not a valid range, which is allowed
+ // in loose mode, but will still throw if the WHOLE range is invalid.
+ .filter(c => c.length);
+
+ if (!this.set.length) {
+ throw new TypeError(`Invalid SemVer Range: ${range}`)
+ }
+
+ // if we have any that are not the null set, throw out null sets.
+ if (this.set.length > 1) {
+ // keep the first one, in case they're all null sets
+ const first = this.set[0];
+ this.set = this.set.filter(c => !isNullSet(c[0]));
+ if (this.set.length === 0) {
+ this.set = [first];
+ } else if (this.set.length > 1) {
+ // if we have any that are *, then the range is just *
+ for (const c of this.set) {
+ if (c.length === 1 && isAny(c[0])) {
+ this.set = [c];
+ break
+ }
+ }
+ }
+ }
+
+ this.format();
+ }
+
+ format () {
+ this.range = this.set
+ .map((comps) => {
+ return comps.join(' ').trim()
+ })
+ .join('||')
+ .trim();
+ return this.range
+ }
+
+ toString () {
+ return this.range
+ }
+
+ parseRange (range) {
+ range = range.trim();
+
+ // memoize range parsing for performance.
+ // this is a very hot path, and fully deterministic.
+ const memoOpts = Object.keys(this.options).join(',');
+ const memoKey = `parseRange:${memoOpts}:${range}`;
+ const cached = cache.get(memoKey);
+ if (cached) {
+ return cached
+ }
+
+ const loose = this.options.loose;
+ // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
+ debug('hyphen replace', range);
+ // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
+ debug('comparator trim', range);
+
+ // `~ 1.2.3` => `~1.2.3`
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
+
+ // `^ 1.2.3` => `^1.2.3`
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);
+
+ // normalize spaces
+ range = range.split(/\s+/).join(' ');
+
+ // At this point, the range is completely trimmed and
+ // ready to be split into comparators.
+
+ let rangeList = range
+ .split(' ')
+ .map(comp => parseComparator(comp, this.options))
+ .join(' ')
+ .split(/\s+/)
+ // >=0.0.0 is equivalent to *
+ .map(comp => replaceGTE0(comp, this.options));
+
+ if (loose) {
+ // in loose mode, throw out any that are not valid comparators
+ rangeList = rangeList.filter(comp => {
+ debug('loose invalid filter', comp, this.options);
+ return !!comp.match(re[t.COMPARATORLOOSE])
+ });
+ }
+ debug('range list', rangeList);
+
+ // if any comparators are the null set, then replace with JUST null set
+ // if more than one comparator, remove any * comparators
+ // also, don't include the same comparator more than once
+ const rangeMap = new Map();
+ const comparators = rangeList.map(comp => new Comparator(comp, this.options));
+ for (const comp of comparators) {
+ if (isNullSet(comp)) {
+ return [comp]
+ }
+ rangeMap.set(comp.value, comp);
+ }
+ if (rangeMap.size > 1 && rangeMap.has('')) {
+ rangeMap.delete('');
+ }
+
+ const result = [...rangeMap.values()];
+ cache.set(memoKey, result);
+ return result
+ }
+
+ intersects (range, options) {
+ if (!(range instanceof Range)) {
+ throw new TypeError('a Range is required')
+ }
+
+ return this.set.some((thisComparators) => {
+ return (
+ isSatisfiable(thisComparators, options) &&
+ range.set.some((rangeComparators) => {
+ return (
+ isSatisfiable(rangeComparators, options) &&
+ thisComparators.every((thisComparator) => {
+ return rangeComparators.every((rangeComparator) => {
+ return thisComparator.intersects(rangeComparator, options)
+ })
+ })
+ )
+ })
+ )
+ })
+ }
+
+ // if ANY of the sets match ALL of its comparators, then pass
+ test (version) {
+ if (!version) {
+ return false
+ }
+
+ if (typeof version === 'string') {
+ try {
+ version = new SemVer(version, this.options);
+ } catch (er) {
+ return false
+ }
+ }
+
+ for (let i = 0; i < this.set.length; i++) {
+ if (testSet(this.set[i], version, this.options)) {
+ return true
+ }
+ }
+ return false
+ }
+ }
+ range$2 = Range;
+
+ const LRU = requireLruCache();
+ const cache = new LRU({ max: 1000 });
+
+ const parseOptions = requireParseOptions();
+ const Comparator = requireComparator();
+ const debug = requireDebug();
+ const SemVer = requireSemver$1();
+ const {
+ re,
+ t,
+ comparatorTrimReplace,
+ tildeTrimReplace,
+ caretTrimReplace,
+ } = requireRe();
+
+ const isNullSet = c => c.value === '<0.0.0-0';
+ const isAny = c => c.value === '';
+
+ // take a set of comparators and determine whether there
+ // exists a version which can satisfy it
+ const isSatisfiable = (comparators, options) => {
+ let result = true;
+ const remainingComparators = comparators.slice();
+ let testComparator = remainingComparators.pop();
+
+ while (result && remainingComparators.length) {
+ result = remainingComparators.every((otherComparator) => {
+ return testComparator.intersects(otherComparator, options)
+ });
+
+ testComparator = remainingComparators.pop();
+ }
+
+ return result
+ };
+
+ // comprised of xranges, tildes, stars, and gtlt's at this point.
+ // already replaced the hyphen ranges
+ // turn into a set of JUST comparators.
+ const parseComparator = (comp, options) => {
+ debug('comp', comp, options);
+ comp = replaceCarets(comp, options);
+ debug('caret', comp);
+ comp = replaceTildes(comp, options);
+ debug('tildes', comp);
+ comp = replaceXRanges(comp, options);
+ debug('xrange', comp);
+ comp = replaceStars(comp, options);
+ debug('stars', comp);
+ return comp
+ };
+
+ const isX = id => !id || id.toLowerCase() === 'x' || id === '*';
+
+ // ~, ~> --> * (any, kinda silly)
+ // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
+ // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
+ // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
+ // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
+ // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
+ // ~0.0.1 --> >=0.0.1 <0.1.0-0
+ const replaceTildes = (comp, options) =>
+ comp.trim().split(/\s+/).map((c) => {
+ return replaceTilde(c, options)
+ }).join(' ');
+
+ const replaceTilde = (comp, options) => {
+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
+ return comp.replace(r, (_, M, m, p, pr) => {
+ debug('tilde', comp, _, M, m, p, pr);
+ let ret;
+
+ if (isX(M)) {
+ ret = '';
+ } else if (isX(m)) {
+ ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
+ } else if (isX(p)) {
+ // ~1.2 == >=1.2.0 <1.3.0-0
+ ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
+ } else if (pr) {
+ debug('replaceTilde pr', pr);
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${M}.${+m + 1}.0-0`;
+ } else {
+ // ~1.2.3 == >=1.2.3 <1.3.0-0
+ ret = `>=${M}.${m}.${p
+ } <${M}.${+m + 1}.0-0`;
+ }
+
+ debug('tilde return', ret);
+ return ret
+ })
+ };
+
+ // ^ --> * (any, kinda silly)
+ // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
+ // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
+ // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
+ // ^1.2.3 --> >=1.2.3 <2.0.0-0
+ // ^1.2.0 --> >=1.2.0 <2.0.0-0
+ // ^0.0.1 --> >=0.0.1 <0.0.2-0
+ // ^0.1.0 --> >=0.1.0 <0.2.0-0
+ const replaceCarets = (comp, options) =>
+ comp.trim().split(/\s+/).map((c) => {
+ return replaceCaret(c, options)
+ }).join(' ');
+
+ const replaceCaret = (comp, options) => {
+ debug('caret', comp, options);
+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
+ const z = options.includePrerelease ? '-0' : '';
+ return comp.replace(r, (_, M, m, p, pr) => {
+ debug('caret', comp, _, M, m, p, pr);
+ let ret;
+
+ if (isX(M)) {
+ ret = '';
+ } else if (isX(m)) {
+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
+ } else if (isX(p)) {
+ if (M === '0') {
+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
+ } else {
+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
+ }
+ } else if (pr) {
+ debug('replaceCaret pr', pr);
+ if (M === '0') {
+ if (m === '0') {
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${M}.${m}.${+p + 1}-0`;
+ } else {
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${M}.${+m + 1}.0-0`;
+ }
+ } else {
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${+M + 1}.0.0-0`;
+ }
+ } else {
+ debug('no pr');
+ if (M === '0') {
+ if (m === '0') {
+ ret = `>=${M}.${m}.${p
+ }${z} <${M}.${m}.${+p + 1}-0`;
+ } else {
+ ret = `>=${M}.${m}.${p
+ }${z} <${M}.${+m + 1}.0-0`;
+ }
+ } else {
+ ret = `>=${M}.${m}.${p
+ } <${+M + 1}.0.0-0`;
+ }
+ }
+
+ debug('caret return', ret);
+ return ret
+ })
+ };
+
+ const replaceXRanges = (comp, options) => {
+ debug('replaceXRanges', comp, options);
+ return comp.split(/\s+/).map((c) => {
+ return replaceXRange(c, options)
+ }).join(' ')
+ };
+
+ const replaceXRange = (comp, options) => {
+ comp = comp.trim();
+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
+ debug('xRange', comp, ret, gtlt, M, m, p, pr);
+ const xM = isX(M);
+ const xm = xM || isX(m);
+ const xp = xm || isX(p);
+ const anyX = xp;
+
+ if (gtlt === '=' && anyX) {
+ gtlt = '';
+ }
+
+ // if we're including prereleases in the match, then we need
+ // to fix this to -0, the lowest possible prerelease value
+ pr = options.includePrerelease ? '-0' : '';
+
+ if (xM) {
+ if (gtlt === '>' || gtlt === '<') {
+ // nothing is allowed
+ ret = '<0.0.0-0';
+ } else {
+ // nothing is forbidden
+ ret = '*';
+ }
+ } else if (gtlt && anyX) {
+ // we know patch is an x, because we have any x at all.
+ // replace X with 0
+ if (xm) {
+ m = 0;
+ }
+ p = 0;
+
+ if (gtlt === '>') {
+ // >1 => >=2.0.0
+ // >1.2 => >=1.3.0
+ gtlt = '>=';
+ if (xm) {
+ M = +M + 1;
+ m = 0;
+ p = 0;
+ } else {
+ m = +m + 1;
+ p = 0;
+ }
+ } else if (gtlt === '<=') {
+ // <=0.7.x is actually <0.8.0, since any 0.7.x should
+ // pass. Similarly, <=7.x is actually <8.0.0, etc.
+ gtlt = '<';
+ if (xm) {
+ M = +M + 1;
+ } else {
+ m = +m + 1;
+ }
+ }
+
+ if (gtlt === '<') {
+ pr = '-0';
+ }
+
+ ret = `${gtlt + M}.${m}.${p}${pr}`;
+ } else if (xm) {
+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
+ } else if (xp) {
+ ret = `>=${M}.${m}.0${pr
+ } <${M}.${+m + 1}.0-0`;
+ }
+
+ debug('xRange return', ret);
+
+ return ret
+ })
+ };
+
+ // Because * is AND-ed with everything else in the comparator,
+ // and '' means "any version", just remove the *s entirely.
+ const replaceStars = (comp, options) => {
+ debug('replaceStars', comp, options);
+ // Looseness is ignored here. star is always as loose as it gets!
+ return comp.trim().replace(re[t.STAR], '')
+ };
+
+ const replaceGTE0 = (comp, options) => {
+ debug('replaceGTE0', comp, options);
+ return comp.trim()
+ .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
+ };
+
+ // This function is passed to string.replace(re[t.HYPHENRANGE])
+ // M, m, patch, prerelease, build
+ // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
+ // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
+ // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
+ const hyphenReplace = incPr => ($0,
+ from, fM, fm, fp, fpr, fb,
+ to, tM, tm, tp, tpr, tb) => {
+ if (isX(fM)) {
+ from = '';
+ } else if (isX(fm)) {
+ from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
+ } else if (isX(fp)) {
+ from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
+ } else if (fpr) {
+ from = `>=${from}`;
+ } else {
+ from = `>=${from}${incPr ? '-0' : ''}`;
+ }
+
+ if (isX(tM)) {
+ to = '';
+ } else if (isX(tm)) {
+ to = `<${+tM + 1}.0.0-0`;
+ } else if (isX(tp)) {
+ to = `<${tM}.${+tm + 1}.0-0`;
+ } else if (tpr) {
+ to = `<=${tM}.${tm}.${tp}-${tpr}`;
+ } else if (incPr) {
+ to = `<${tM}.${tm}.${+tp + 1}-0`;
+ } else {
+ to = `<=${to}`;
+ }
+
+ return (`${from} ${to}`).trim()
+ };
+
+ const testSet = (set, version, options) => {
+ for (let i = 0; i < set.length; i++) {
+ if (!set[i].test(version)) {
+ return false
+ }
+ }
+
+ if (version.prerelease.length && !options.includePrerelease) {
+ // Find the set of versions that are allowed to have prereleases
+ // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
+ // That should allow `1.2.3-pr.2` to pass.
+ // However, `1.2.4-alpha.notready` should NOT be allowed,
+ // even though it's within the range set by the comparators.
+ for (let i = 0; i < set.length; i++) {
+ debug(set[i].semver);
+ if (set[i].semver === Comparator.ANY) {
+ continue
+ }
+
+ if (set[i].semver.prerelease.length > 0) {
+ const allowed = set[i].semver;
+ if (allowed.major === version.major &&
+ allowed.minor === version.minor &&
+ allowed.patch === version.patch) {
+ return true
+ }
+ }
+ }
+
+ // Version has a -pre, but it's not one of the ones we like.
+ return false
+ }
+
+ return true
+ };
+ return range$2;
+}
+
+var comparator;
+var hasRequiredComparator;
+
+function requireComparator () {
+ if (hasRequiredComparator) return comparator;
+ hasRequiredComparator = 1;
+ const ANY = Symbol('SemVer ANY');
+ // hoisted class for cyclic dependency
+ class Comparator {
+ static get ANY () {
+ return ANY
+ }
+
+ constructor (comp, options) {
+ options = parseOptions(options);
+
+ if (comp instanceof Comparator) {
+ if (comp.loose === !!options.loose) {
+ return comp
+ } else {
+ comp = comp.value;
+ }
+ }
+
+ debug('comparator', comp, options);
+ this.options = options;
+ this.loose = !!options.loose;
+ this.parse(comp);
+
+ if (this.semver === ANY) {
+ this.value = '';
+ } else {
+ this.value = this.operator + this.semver.version;
+ }
+
+ debug('comp', this);
+ }
+
+ parse (comp) {
+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
+ const m = comp.match(r);
+
+ if (!m) {
+ throw new TypeError(`Invalid comparator: ${comp}`)
+ }
+
+ this.operator = m[1] !== undefined ? m[1] : '';
+ if (this.operator === '=') {
+ this.operator = '';
+ }
+
+ // if it literally is just '>' or '' then allow anything.
+ if (!m[2]) {
+ this.semver = ANY;
+ } else {
+ this.semver = new SemVer(m[2], this.options.loose);
+ }
+ }
+
+ toString () {
+ return this.value
+ }
+
+ test (version) {
+ debug('Comparator.test', version, this.options.loose);
+
+ if (this.semver === ANY || version === ANY) {
+ return true
+ }
+
+ if (typeof version === 'string') {
+ try {
+ version = new SemVer(version, this.options);
+ } catch (er) {
+ return false
+ }
+ }
+
+ return cmp(version, this.operator, this.semver, this.options)
+ }
+
+ intersects (comp, options) {
+ if (!(comp instanceof Comparator)) {
+ throw new TypeError('a Comparator is required')
+ }
+
+ if (!options || typeof options !== 'object') {
+ options = {
+ loose: !!options,
+ includePrerelease: false,
+ };
+ }
+
+ if (this.operator === '') {
+ if (this.value === '') {
+ return true
+ }
+ return new Range(comp.value, options).test(this.value)
+ } else if (comp.operator === '') {
+ if (comp.value === '') {
+ return true
+ }
+ return new Range(this.value, options).test(comp.semver)
+ }
+
+ const sameDirectionIncreasing =
+ (this.operator === '>=' || this.operator === '>') &&
+ (comp.operator === '>=' || comp.operator === '>');
+ const sameDirectionDecreasing =
+ (this.operator === '<=' || this.operator === '<') &&
+ (comp.operator === '<=' || comp.operator === '<');
+ const sameSemVer = this.semver.version === comp.semver.version;
+ const differentDirectionsInclusive =
+ (this.operator === '>=' || this.operator === '<=') &&
+ (comp.operator === '>=' || comp.operator === '<=');
+ const oppositeDirectionsLessThan =
+ cmp(this.semver, '<', comp.semver, options) &&
+ (this.operator === '>=' || this.operator === '>') &&
+ (comp.operator === '<=' || comp.operator === '<');
+ const oppositeDirectionsGreaterThan =
+ cmp(this.semver, '>', comp.semver, options) &&
+ (this.operator === '<=' || this.operator === '<') &&
+ (comp.operator === '>=' || comp.operator === '>');
+
+ return (
+ sameDirectionIncreasing ||
+ sameDirectionDecreasing ||
+ (sameSemVer && differentDirectionsInclusive) ||
+ oppositeDirectionsLessThan ||
+ oppositeDirectionsGreaterThan
+ )
+ }
+ }
+
+ comparator = Comparator;
+
+ const parseOptions = requireParseOptions();
+ const { re, t } = requireRe();
+ const cmp = requireCmp();
+ const debug = requireDebug();
+ const SemVer = requireSemver$1();
+ const Range = requireRange();
+ return comparator;
+}
+
+var satisfies_1;
+var hasRequiredSatisfies;
+
+function requireSatisfies () {
+ if (hasRequiredSatisfies) return satisfies_1;
+ hasRequiredSatisfies = 1;
+ const Range = requireRange();
+ const satisfies = (version, range, options) => {
+ try {
+ range = new Range(range, options);
+ } catch (er) {
+ return false
+ }
+ return range.test(version)
+ };
+ satisfies_1 = satisfies;
+ return satisfies_1;
+}
+
+var toComparators_1;
+var hasRequiredToComparators;
+
+function requireToComparators () {
+ if (hasRequiredToComparators) return toComparators_1;
+ hasRequiredToComparators = 1;
+ const Range = requireRange();
+
+ // Mostly just for testing and legacy API reasons
+ const toComparators = (range, options) =>
+ new Range(range, options).set
+ .map(comp => comp.map(c => c.value).join(' ').trim().split(' '));
+
+ toComparators_1 = toComparators;
+ return toComparators_1;
+}
+
+var maxSatisfying_1;
+var hasRequiredMaxSatisfying;
+
+function requireMaxSatisfying () {
+ if (hasRequiredMaxSatisfying) return maxSatisfying_1;
+ hasRequiredMaxSatisfying = 1;
+ const SemVer = requireSemver$1();
+ const Range = requireRange();
+
+ const maxSatisfying = (versions, range, options) => {
+ let max = null;
+ let maxSV = null;
+ let rangeObj = null;
+ try {
+ rangeObj = new Range(range, options);
+ } catch (er) {
+ return null
+ }
+ versions.forEach((v) => {
+ if (rangeObj.test(v)) {
+ // satisfies(v, range, options)
+ if (!max || maxSV.compare(v) === -1) {
+ // compare(max, v, true)
+ max = v;
+ maxSV = new SemVer(max, options);
+ }
+ }
+ });
+ return max
+ };
+ maxSatisfying_1 = maxSatisfying;
+ return maxSatisfying_1;
+}
+
+var minSatisfying_1;
+var hasRequiredMinSatisfying;
+
+function requireMinSatisfying () {
+ if (hasRequiredMinSatisfying) return minSatisfying_1;
+ hasRequiredMinSatisfying = 1;
+ const SemVer = requireSemver$1();
+ const Range = requireRange();
+ const minSatisfying = (versions, range, options) => {
+ let min = null;
+ let minSV = null;
+ let rangeObj = null;
+ try {
+ rangeObj = new Range(range, options);
+ } catch (er) {
+ return null
+ }
+ versions.forEach((v) => {
+ if (rangeObj.test(v)) {
+ // satisfies(v, range, options)
+ if (!min || minSV.compare(v) === 1) {
+ // compare(min, v, true)
+ min = v;
+ minSV = new SemVer(min, options);
+ }
+ }
+ });
+ return min
+ };
+ minSatisfying_1 = minSatisfying;
+ return minSatisfying_1;
+}
+
+var minVersion_1;
+var hasRequiredMinVersion;
+
+function requireMinVersion () {
+ if (hasRequiredMinVersion) return minVersion_1;
+ hasRequiredMinVersion = 1;
+ const SemVer = requireSemver$1();
+ const Range = requireRange();
+ const gt = requireGt();
+
+ const minVersion = (range, loose) => {
+ range = new Range(range, loose);
+
+ let minver = new SemVer('0.0.0');
+ if (range.test(minver)) {
+ return minver
+ }
+
+ minver = new SemVer('0.0.0-0');
+ if (range.test(minver)) {
+ return minver
+ }
+
+ minver = null;
+ for (let i = 0; i < range.set.length; ++i) {
+ const comparators = range.set[i];
+
+ let setMin = null;
+ comparators.forEach((comparator) => {
+ // Clone to avoid manipulating the comparator's semver object.
+ const compver = new SemVer(comparator.semver.version);
+ switch (comparator.operator) {
+ case '>':
+ if (compver.prerelease.length === 0) {
+ compver.patch++;
+ } else {
+ compver.prerelease.push(0);
+ }
+ compver.raw = compver.format();
+ /* fallthrough */
+ case '':
+ case '>=':
+ if (!setMin || gt(compver, setMin)) {
+ setMin = compver;
+ }
+ break
+ case '<':
+ case '<=':
+ /* Ignore maximum versions */
+ break
+ /* istanbul ignore next */
+ default:
+ throw new Error(`Unexpected operation: ${comparator.operator}`)
+ }
+ });
+ if (setMin && (!minver || gt(minver, setMin))) {
+ minver = setMin;
+ }
+ }
+
+ if (minver && range.test(minver)) {
+ return minver
+ }
+
+ return null
+ };
+ minVersion_1 = minVersion;
+ return minVersion_1;
+}
+
+var valid;
+var hasRequiredValid;
+
+function requireValid () {
+ if (hasRequiredValid) return valid;
+ hasRequiredValid = 1;
+ const Range = requireRange();
+ const validRange = (range, options) => {
+ try {
+ // Return '*' instead of '' so that truthiness works.
+ // This will throw if it's invalid anyway
+ return new Range(range, options).range || '*'
+ } catch (er) {
+ return null
+ }
+ };
+ valid = validRange;
+ return valid;
+}
+
+var outside_1;
+var hasRequiredOutside;
+
+function requireOutside () {
+ if (hasRequiredOutside) return outside_1;
+ hasRequiredOutside = 1;
+ const SemVer = requireSemver$1();
+ const Comparator = requireComparator();
+ const { ANY } = Comparator;
+ const Range = requireRange();
+ const satisfies = requireSatisfies();
+ const gt = requireGt();
+ const lt = requireLt();
+ const lte = requireLte();
+ const gte = requireGte();
+
+ const outside = (version, range, hilo, options) => {
+ version = new SemVer(version, options);
+ range = new Range(range, options);
+
+ let gtfn, ltefn, ltfn, comp, ecomp;
+ switch (hilo) {
+ case '>':
+ gtfn = gt;
+ ltefn = lte;
+ ltfn = lt;
+ comp = '>';
+ ecomp = '>=';
+ break
+ case '<':
+ gtfn = lt;
+ ltefn = gte;
+ ltfn = gt;
+ comp = '<';
+ ecomp = '<=';
+ break
+ default:
+ throw new TypeError('Must provide a hilo val of "<" or ">"')
+ }
+
+ // If it satisfies the range it is not outside
+ if (satisfies(version, range, options)) {
+ return false
+ }
+
+ // From now on, variable terms are as if we're in "gtr" mode.
+ // but note that everything is flipped for the "ltr" function.
+
+ for (let i = 0; i < range.set.length; ++i) {
+ const comparators = range.set[i];
+
+ let high = null;
+ let low = null;
+
+ comparators.forEach((comparator) => {
+ if (comparator.semver === ANY) {
+ comparator = new Comparator('>=0.0.0');
+ }
+ high = high || comparator;
+ low = low || comparator;
+ if (gtfn(comparator.semver, high.semver, options)) {
+ high = comparator;
+ } else if (ltfn(comparator.semver, low.semver, options)) {
+ low = comparator;
+ }
+ });
+
+ // If the edge version comparator has a operator then our version
+ // isn't outside it
+ if (high.operator === comp || high.operator === ecomp) {
+ return false
+ }
+
+ // If the lowest version comparator has an operator and our version
+ // is less than it then it isn't higher than the range
+ if ((!low.operator || low.operator === comp) &&
+ ltefn(version, low.semver)) {
+ return false
+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {
+ return false
+ }
+ }
+ return true
+ };
+
+ outside_1 = outside;
+ return outside_1;
+}
+
+var gtr_1;
+var hasRequiredGtr;
+
+function requireGtr () {
+ if (hasRequiredGtr) return gtr_1;
+ hasRequiredGtr = 1;
+ // Determine if version is greater than all the versions possible in the range.
+ const outside = requireOutside();
+ const gtr = (version, range, options) => outside(version, range, '>', options);
+ gtr_1 = gtr;
+ return gtr_1;
+}
+
+var ltr_1;
+var hasRequiredLtr;
+
+function requireLtr () {
+ if (hasRequiredLtr) return ltr_1;
+ hasRequiredLtr = 1;
+ const outside = requireOutside();
+ // Determine if version is less than all the versions possible in the range
+ const ltr = (version, range, options) => outside(version, range, '<', options);
+ ltr_1 = ltr;
+ return ltr_1;
+}
+
+var intersects_1;
+var hasRequiredIntersects;
+
+function requireIntersects () {
+ if (hasRequiredIntersects) return intersects_1;
+ hasRequiredIntersects = 1;
+ const Range = requireRange();
+ const intersects = (r1, r2, options) => {
+ r1 = new Range(r1, options);
+ r2 = new Range(r2, options);
+ return r1.intersects(r2)
+ };
+ intersects_1 = intersects;
+ return intersects_1;
+}
+
+var simplify;
+var hasRequiredSimplify;
+
+function requireSimplify () {
+ if (hasRequiredSimplify) return simplify;
+ hasRequiredSimplify = 1;
+ // given a set of versions and a range, create a "simplified" range
+ // that includes the same versions that the original range does
+ // If the original range is shorter than the simplified one, return that.
+ const satisfies = requireSatisfies();
+ const compare = requireCompare();
+ simplify = (versions, range, options) => {
+ const set = [];
+ let first = null;
+ let prev = null;
+ const v = versions.sort((a, b) => compare(a, b, options));
+ for (const version of v) {
+ const included = satisfies(version, range, options);
+ if (included) {
+ prev = version;
+ if (!first) {
+ first = version;
+ }
+ } else {
+ if (prev) {
+ set.push([first, prev]);
+ }
+ prev = null;
+ first = null;
+ }
+ }
+ if (first) {
+ set.push([first, null]);
+ }
+
+ const ranges = [];
+ for (const [min, max] of set) {
+ if (min === max) {
+ ranges.push(min);
+ } else if (!max && min === v[0]) {
+ ranges.push('*');
+ } else if (!max) {
+ ranges.push(`>=${min}`);
+ } else if (min === v[0]) {
+ ranges.push(`<=${max}`);
+ } else {
+ ranges.push(`${min} - ${max}`);
+ }
+ }
+ const simplified = ranges.join(' || ');
+ const original = typeof range.raw === 'string' ? range.raw : String(range);
+ return simplified.length < original.length ? simplified : range
+ };
+ return simplify;
+}
+
+var subset_1;
+var hasRequiredSubset;
+
+function requireSubset () {
+ if (hasRequiredSubset) return subset_1;
+ hasRequiredSubset = 1;
+ const Range = requireRange();
+ const Comparator = requireComparator();
+ const { ANY } = Comparator;
+ const satisfies = requireSatisfies();
+ const compare = requireCompare();
+
+ // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
+ // - Every simple range `r1, r2, ...` is a null set, OR
+ // - Every simple range `r1, r2, ...` which is not a null set is a subset of
+ // some `R1, R2, ...`
+ //
+ // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
+ // - If c is only the ANY comparator
+ // - If C is only the ANY comparator, return true
+ // - Else if in prerelease mode, return false
+ // - else replace c with `[>=0.0.0]`
+ // - If C is only the ANY comparator
+ // - if in prerelease mode, return true
+ // - else replace C with `[>=0.0.0]`
+ // - Let EQ be the set of = comparators in c
+ // - If EQ is more than one, return true (null set)
+ // - Let GT be the highest > or >= comparator in c
+ // - Let LT be the lowest < or <= comparator in c
+ // - If GT and LT, and GT.semver > LT.semver, return true (null set)
+ // - If any C is a = range, and GT or LT are set, return false
+ // - If EQ
+ // - If GT, and EQ does not satisfy GT, return true (null set)
+ // - If LT, and EQ does not satisfy LT, return true (null set)
+ // - If EQ satisfies every C, return true
+ // - Else return false
+ // - If GT
+ // - If GT.semver is lower than any > or >= comp in C, return false
+ // - If GT is >=, and GT.semver does not satisfy every C, return false
+ // - If GT.semver has a prerelease, and not in prerelease mode
+ // - If no C has a prerelease and the GT.semver tuple, return false
+ // - If LT
+ // - If LT.semver is greater than any < or <= comp in C, return false
+ // - If LT is <=, and LT.semver does not satisfy every C, return false
+ // - If GT.semver has a prerelease, and not in prerelease mode
+ // - If no C has a prerelease and the LT.semver tuple, return false
+ // - Else return true
+
+ const subset = (sub, dom, options = {}) => {
+ if (sub === dom) {
+ return true
+ }
+
+ sub = new Range(sub, options);
+ dom = new Range(dom, options);
+ let sawNonNull = false;
+
+ OUTER: for (const simpleSub of sub.set) {
+ for (const simpleDom of dom.set) {
+ const isSub = simpleSubset(simpleSub, simpleDom, options);
+ sawNonNull = sawNonNull || isSub !== null;
+ if (isSub) {
+ continue OUTER
+ }
+ }
+ // the null set is a subset of everything, but null simple ranges in
+ // a complex range should be ignored. so if we saw a non-null range,
+ // then we know this isn't a subset, but if EVERY simple range was null,
+ // then it is a subset.
+ if (sawNonNull) {
+ return false
+ }
+ }
+ return true
+ };
+
+ const simpleSubset = (sub, dom, options) => {
+ if (sub === dom) {
+ return true
+ }
+
+ if (sub.length === 1 && sub[0].semver === ANY) {
+ if (dom.length === 1 && dom[0].semver === ANY) {
+ return true
+ } else if (options.includePrerelease) {
+ sub = [new Comparator('>=0.0.0-0')];
+ } else {
+ sub = [new Comparator('>=0.0.0')];
+ }
+ }
+
+ if (dom.length === 1 && dom[0].semver === ANY) {
+ if (options.includePrerelease) {
+ return true
+ } else {
+ dom = [new Comparator('>=0.0.0')];
+ }
+ }
+
+ const eqSet = new Set();
+ let gt, lt;
+ for (const c of sub) {
+ if (c.operator === '>' || c.operator === '>=') {
+ gt = higherGT(gt, c, options);
+ } else if (c.operator === '<' || c.operator === '<=') {
+ lt = lowerLT(lt, c, options);
+ } else {
+ eqSet.add(c.semver);
+ }
+ }
+
+ if (eqSet.size > 1) {
+ return null
+ }
+
+ let gtltComp;
+ if (gt && lt) {
+ gtltComp = compare(gt.semver, lt.semver, options);
+ if (gtltComp > 0) {
+ return null
+ } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
+ return null
+ }
+ }
+
+ // will iterate one or zero times
+ for (const eq of eqSet) {
+ if (gt && !satisfies(eq, String(gt), options)) {
+ return null
+ }
+
+ if (lt && !satisfies(eq, String(lt), options)) {
+ return null
+ }
+
+ for (const c of dom) {
+ if (!satisfies(eq, String(c), options)) {
+ return false
+ }
+ }
+
+ return true
+ }
+
+ let higher, lower;
+ let hasDomLT, hasDomGT;
+ // if the subset has a prerelease, we need a comparator in the superset
+ // with the same tuple and a prerelease, or it's not a subset
+ let needDomLTPre = lt &&
+ !options.includePrerelease &&
+ lt.semver.prerelease.length ? lt.semver : false;
+ let needDomGTPre = gt &&
+ !options.includePrerelease &&
+ gt.semver.prerelease.length ? gt.semver : false;
+ // exception: <1.2.3-0 is the same as <1.2.3
+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
+ lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
+ needDomLTPre = false;
+ }
+
+ for (const c of dom) {
+ hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';
+ hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';
+ if (gt) {
+ if (needDomGTPre) {
+ if (c.semver.prerelease && c.semver.prerelease.length &&
+ c.semver.major === needDomGTPre.major &&
+ c.semver.minor === needDomGTPre.minor &&
+ c.semver.patch === needDomGTPre.patch) {
+ needDomGTPre = false;
+ }
+ }
+ if (c.operator === '>' || c.operator === '>=') {
+ higher = higherGT(gt, c, options);
+ if (higher === c && higher !== gt) {
+ return false
+ }
+ } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
+ return false
+ }
+ }
+ if (lt) {
+ if (needDomLTPre) {
+ if (c.semver.prerelease && c.semver.prerelease.length &&
+ c.semver.major === needDomLTPre.major &&
+ c.semver.minor === needDomLTPre.minor &&
+ c.semver.patch === needDomLTPre.patch) {
+ needDomLTPre = false;
+ }
+ }
+ if (c.operator === '<' || c.operator === '<=') {
+ lower = lowerLT(lt, c, options);
+ if (lower === c && lower !== lt) {
+ return false
+ }
+ } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
+ return false
+ }
+ }
+ if (!c.operator && (lt || gt) && gtltComp !== 0) {
+ return false
+ }
+ }
+
+ // if there was a < or >, and nothing in the dom, then must be false
+ // UNLESS it was limited by another range in the other direction.
+ // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
+ if (gt && hasDomLT && !lt && gtltComp !== 0) {
+ return false
+ }
+
+ if (lt && hasDomGT && !gt && gtltComp !== 0) {
+ return false
+ }
+
+ // we needed a prerelease range in a specific tuple, but didn't get one
+ // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
+ // because it includes prereleases in the 1.2.3 tuple
+ if (needDomGTPre || needDomLTPre) {
+ return false
+ }
+
+ return true
+ };
+
+ // >=1.2.3 is lower than >1.2.3
+ const higherGT = (a, b, options) => {
+ if (!a) {
+ return b
+ }
+ const comp = compare(a.semver, b.semver, options);
+ return comp > 0 ? a
+ : comp < 0 ? b
+ : b.operator === '>' && a.operator === '>=' ? b
+ : a
+ };
+
+ // <=1.2.3 is higher than <1.2.3
+ const lowerLT = (a, b, options) => {
+ if (!a) {
+ return b
+ }
+ const comp = compare(a.semver, b.semver, options);
+ return comp < 0 ? a
+ : comp > 0 ? b
+ : b.operator === '<' && a.operator === '<=' ? b
+ : a
+ };
+
+ subset_1 = subset;
+ return subset_1;
+}
+
+var semver;
+var hasRequiredSemver;
+
+function requireSemver () {
+ if (hasRequiredSemver) return semver;
+ hasRequiredSemver = 1;
+ // just pre-load all the stuff that index.js lazily exports
+ const internalRe = requireRe();
+ const constants = requireConstants();
+ const SemVer = requireSemver$1();
+ const identifiers = requireIdentifiers();
+ const parse = requireParse();
+ const valid = requireValid$1();
+ const clean = requireClean();
+ const inc = requireInc();
+ const diff = requireDiff();
+ const major = requireMajor();
+ const minor = requireMinor();
+ const patch = requirePatch();
+ const prerelease = requirePrerelease();
+ const compare = requireCompare();
+ const rcompare = requireRcompare();
+ const compareLoose = requireCompareLoose();
+ const compareBuild = requireCompareBuild();
+ const sort = requireSort();
+ const rsort = requireRsort();
+ const gt = requireGt();
+ const lt = requireLt();
+ const eq = requireEq();
+ const neq = requireNeq();
+ const gte = requireGte();
+ const lte = requireLte();
+ const cmp = requireCmp();
+ const coerce = requireCoerce();
+ const Comparator = requireComparator();
+ const Range = requireRange();
+ const satisfies = requireSatisfies();
+ const toComparators = requireToComparators();
+ const maxSatisfying = requireMaxSatisfying();
+ const minSatisfying = requireMinSatisfying();
+ const minVersion = requireMinVersion();
+ const validRange = requireValid();
+ const outside = requireOutside();
+ const gtr = requireGtr();
+ const ltr = requireLtr();
+ const intersects = requireIntersects();
+ const simplifyRange = requireSimplify();
+ const subset = requireSubset();
+ semver = {
+ parse,
+ valid,
+ clean,
+ inc,
+ diff,
+ major,
+ minor,
+ patch,
+ prerelease,
+ compare,
+ rcompare,
+ compareLoose,
+ compareBuild,
+ sort,
+ rsort,
+ gt,
+ lt,
+ eq,
+ neq,
+ gte,
+ lte,
+ cmp,
+ coerce,
+ Comparator,
+ Range,
+ satisfies,
+ toComparators,
+ maxSatisfying,
+ minSatisfying,
+ minVersion,
+ validRange,
+ outside,
+ gtr,
+ ltr,
+ intersects,
+ simplifyRange,
+ subset,
+ SemVer,
+ re: internalRe.re,
+ src: internalRe.src,
+ tokens: internalRe.t,
+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
+ compareIdentifiers: identifiers.compareIdentifiers,
+ rcompareIdentifiers: identifiers.rcompareIdentifiers,
+ };
+ return semver;
+}
+
+var requestBase;
+var hasRequiredRequestBase;
+
+function requireRequestBase () {
+ if (hasRequiredRequestBase) return requestBase;
+ hasRequiredRequestBase = 1;
+
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+
+ var semver = requireSemver();
+ /**
+ * Module of mixed-in functions shared between node and client code
+ */
+
+
+ var _require = requireUtils(),
+ isObject = _require.isObject,
+ hasOwn = _require.hasOwn;
+ /**
+ * Expose `RequestBase`.
+ */
+
+
+ requestBase = RequestBase;
+ /**
+ * Initialize a new `RequestBase`.
+ *
+ * @api public
+ */
+
+ function RequestBase() {}
+ /**
+ * Clear previous timeout.
+ *
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.clearTimeout = function () {
+ clearTimeout(this._timer);
+ clearTimeout(this._responseTimeoutTimer);
+ clearTimeout(this._uploadTimeoutTimer);
+ delete this._timer;
+ delete this._responseTimeoutTimer;
+ delete this._uploadTimeoutTimer;
+ return this;
+ };
+ /**
+ * Override default response body parser
+ *
+ * This function will be called to convert incoming data into request.body
+ *
+ * @param {Function}
+ * @api public
+ */
+
+
+ RequestBase.prototype.parse = function (fn) {
+ this._parser = fn;
+ return this;
+ };
+ /**
+ * Set format of binary response body.
+ * In browser valid formats are 'blob' and 'arraybuffer',
+ * which return Blob and ArrayBuffer, respectively.
+ *
+ * In Node all values result in Buffer.
+ *
+ * Examples:
+ *
+ * req.get('/')
+ * .responseType('blob')
+ * .end(callback);
+ *
+ * @param {String} val
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.responseType = function (value) {
+ this._responseType = value;
+ return this;
+ };
+ /**
+ * Override default request body serializer
+ *
+ * This function will be called to convert data set via .send or .attach into payload to send
+ *
+ * @param {Function}
+ * @api public
+ */
+
+
+ RequestBase.prototype.serialize = function (fn) {
+ this._serializer = fn;
+ return this;
+ };
+ /**
+ * Set timeouts.
+ *
+ * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
+ * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
+ * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
+ *
+ * Value of 0 or false means no timeout.
+ *
+ * @param {Number|Object} ms or {response, deadline}
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.timeout = function (options) {
+ if (!options || _typeof(options) !== 'object') {
+ this._timeout = options;
+ this._responseTimeout = 0;
+ this._uploadTimeout = 0;
+ return this;
+ }
+
+ for (var option in options) {
+ if (hasOwn(options, option)) {
+ switch (option) {
+ case 'deadline':
+ this._timeout = options.deadline;
+ break;
+
+ case 'response':
+ this._responseTimeout = options.response;
+ break;
+
+ case 'upload':
+ this._uploadTimeout = options.upload;
+ break;
+
+ default:
+ console.warn('Unknown timeout option', option);
+ }
+ }
+ }
+
+ return this;
+ };
+ /**
+ * Set number of retry attempts on error.
+ *
+ * Failed requests will be retried 'count' times if timeout or err.code >= 500.
+ *
+ * @param {Number} count
+ * @param {Function} [fn]
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.retry = function (count, fn) {
+ // Default to 1 if no count passed or true
+ if (arguments.length === 0 || count === true) count = 1;
+ if (count <= 0) count = 0;
+ this._maxRetries = count;
+ this._retries = 0;
+ this._retryCallback = fn;
+ return this;
+ }; //
+ // NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package
+ //
+ //
+ // NOTE: we do not include EADDRINFO because it was removed from libuv in 2014
+ //
+ //
+ //
+ //
+ // TODO: expose these as configurable defaults
+ //
+
+
+ var ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']);
+ var STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST)
+ // const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']);
+
+ /**
+ * Determine if a request should be retried.
+ * (Inspired by https://github.com/sindresorhus/got#retry)
+ *
+ * @param {Error} err an error
+ * @param {Response} [res] response
+ * @returns {Boolean} if segment should be retried
+ */
+
+ RequestBase.prototype._shouldRetry = function (error, res) {
+ if (!this._maxRetries || this._retries++ >= this._maxRetries) {
+ return false;
+ }
+
+ if (this._retryCallback) {
+ try {
+ var override = this._retryCallback(error, res);
+
+ if (override === true) return true;
+ if (override === false) return false; // undefined falls back to defaults
+ } catch (err) {
+ console.error(err);
+ }
+ } // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST)
+
+ /*
+ if (
+ this.req &&
+ this.req.method &&
+ !METHODS.has(this.req.method.toUpperCase())
+ )
+ return false;
+ */
+
+
+ if (res && res.status && STATUS_CODES.has(res.status)) return true;
+
+ if (error) {
+ if (error.code && ERROR_CODES.has(error.code)) return true; // Superagent timeout
+
+ if (error.timeout && error.code === 'ECONNABORTED') return true;
+ if (error.crossDomain) return true;
+ }
+
+ return false;
+ };
+ /**
+ * Retry request
+ *
+ * @return {Request} for chaining
+ * @api private
+ */
+
+
+ RequestBase.prototype._retry = function () {
+ this.clearTimeout(); // node
+
+ if (this.req) {
+ this.req = null;
+ this.req = this.request();
+ }
+
+ this._aborted = false;
+ this.timedout = false;
+ this.timedoutError = null;
+ return this._end();
+ };
+ /**
+ * Promise support
+ *
+ * @param {Function} resolve
+ * @param {Function} [reject]
+ * @return {Request}
+ */
+
+
+ RequestBase.prototype.then = function (resolve, reject) {
+ var _this = this;
+
+ if (!this._fullfilledPromise) {
+ var self = this;
+
+ if (this._endCalled) {
+ console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
+ }
+
+ this._fullfilledPromise = new Promise(function (resolve, reject) {
+ self.on('abort', function () {
+ if (_this._maxRetries && _this._maxRetries > _this._retries) {
+ return;
+ }
+
+ if (_this.timedout && _this.timedoutError) {
+ reject(_this.timedoutError);
+ return;
+ }
+
+ var error = new Error('Aborted');
+ error.code = 'ABORTED';
+ error.status = _this.status;
+ error.method = _this.method;
+ error.url = _this.url;
+ reject(error);
+ });
+ self.end(function (error, res) {
+ if (error) reject(error);else resolve(res);
+ });
+ });
+ }
+
+ return this._fullfilledPromise.then(resolve, reject);
+ };
+
+ RequestBase.prototype.catch = function (callback) {
+ return this.then(undefined, callback);
+ };
+ /**
+ * Allow for extension
+ */
+
+
+ RequestBase.prototype.use = function (fn) {
+ fn(this);
+ return this;
+ };
+
+ RequestBase.prototype.ok = function (callback) {
+ if (typeof callback !== 'function') throw new Error('Callback required');
+ this._okCallback = callback;
+ return this;
+ };
+
+ RequestBase.prototype._isResponseOK = function (res) {
+ if (!res) {
+ return false;
+ }
+
+ if (this._okCallback) {
+ return this._okCallback(res);
+ }
+
+ return res.status >= 200 && res.status < 300;
+ };
+ /**
+ * Get request header `field`.
+ * Case-insensitive.
+ *
+ * @param {String} field
+ * @return {String}
+ * @api public
+ */
+
+
+ RequestBase.prototype.get = function (field) {
+ return this._header[field.toLowerCase()];
+ };
+ /**
+ * Get case-insensitive header `field` value.
+ * This is a deprecated internal API. Use `.get(field)` instead.
+ *
+ * (getHeader is no longer used internally by the superagent code base)
+ *
+ * @param {String} field
+ * @return {String}
+ * @api private
+ * @deprecated
+ */
+
+
+ RequestBase.prototype.getHeader = RequestBase.prototype.get;
+ /**
+ * Set header `field` to `val`, or multiple fields with one object.
+ * Case-insensitive.
+ *
+ * Examples:
+ *
+ * req.get('/')
+ * .set('Accept', 'application/json')
+ * .set('X-API-Key', 'foobar')
+ * .end(callback);
+ *
+ * req.get('/')
+ * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
+ * .end(callback);
+ *
+ * @param {String|Object} field
+ * @param {String} val
+ * @return {Request} for chaining
+ * @api public
+ */
+
+ RequestBase.prototype.set = function (field, value) {
+ if (isObject(field)) {
+ for (var key in field) {
+ if (hasOwn(field, key)) this.set(key, field[key]);
+ }
+
+ return this;
+ }
+
+ this._header[field.toLowerCase()] = value;
+ this.header[field] = value;
+ return this;
+ };
+ /**
+ * Remove header `field`.
+ * Case-insensitive.
+ *
+ * Example:
+ *
+ * req.get('/')
+ * .unset('User-Agent')
+ * .end(callback);
+ *
+ * @param {String} field field name
+ */
+
+
+ RequestBase.prototype.unset = function (field) {
+ delete this._header[field.toLowerCase()];
+ delete this.header[field];
+ return this;
+ };
+ /**
+ * Write the field `name` and `val`, or multiple fields with one object
+ * for "multipart/form-data" request bodies.
+ *
+ * ``` js
+ * request.post('/upload')
+ * .field('foo', 'bar')
+ * .end(callback);
+ *
+ * request.post('/upload')
+ * .field({ foo: 'bar', baz: 'qux' })
+ * .end(callback);
+ * ```
+ *
+ * @param {String|Object} name name of field
+ * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
+ * @param {String} options extra options, e.g. 'blob'
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.field = function (name, value, options) {
+ // name should be either a string or an object.
+ if (name === null || undefined === name) {
+ throw new Error('.field(name, val) name can not be empty');
+ }
+
+ if (this._data) {
+ throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
+ }
+
+ if (isObject(name)) {
+ for (var key in name) {
+ if (hasOwn(name, key)) this.field(key, name[key]);
+ }
+
+ return this;
+ }
+
+ if (Array.isArray(value)) {
+ for (var i in value) {
+ if (hasOwn(value, i)) this.field(name, value[i]);
+ }
+
+ return this;
+ } // val should be defined now
+
+
+ if (value === null || undefined === value) {
+ throw new Error('.field(name, val) val can not be empty');
+ }
+
+ if (typeof value === 'boolean') {
+ value = String(value);
+ } // fix https://github.com/visionmedia/superagent/issues/1680
+
+
+ if (options) this._getFormData().append(name, value, options);else this._getFormData().append(name, value);
+ return this;
+ };
+ /**
+ * Abort the request, and clear potential timeout.
+ *
+ * @return {Request} request
+ * @api public
+ */
+
+
+ RequestBase.prototype.abort = function () {
+ if (this._aborted) {
+ return this;
+ }
+
+ this._aborted = true;
+ if (this.xhr) this.xhr.abort(); // browser
+
+ if (this.req) {
+ // Node v13 has major differences in `abort()`
+ // https://github.com/nodejs/node/blob/v12.x/lib/internal/streams/end-of-stream.js
+ // https://github.com/nodejs/node/blob/v13.x/lib/internal/streams/end-of-stream.js
+ // https://github.com/nodejs/node/blob/v14.x/lib/internal/streams/end-of-stream.js
+ // (if you run a diff across these you will see the differences)
+ //
+ // References:
+ //
+ //
+ //
+ // Thanks to @shadowgate15 and @niftylettuce
+ if (semver.gte(process.version, 'v13.0.0') && semver.lt(process.version, 'v14.0.0')) {
+ // Note that the reason this doesn't work is because in v13 as compared to v14
+ // there is no `callback = nop` set in end-of-stream.js above
+ throw new Error('Superagent does not work in v13 properly with abort() due to Node.js core changes');
+ } else if (semver.gte(process.version, 'v14.0.0')) {
+ // We have to manually set `destroyed` to `true` in order for this to work
+ // (see core internals of end-of-stream.js above in v14 branch as compared to v12)
+ this.req.destroyed = true;
+ }
+
+ this.req.abort(); // node
+ }
+
+ this.clearTimeout();
+ this.emit('abort');
+ return this;
+ };
+
+ RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
+ switch (options.type) {
+ case 'basic':
+ this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
+ break;
+
+ case 'auto':
+ this.username = user;
+ this.password = pass;
+ break;
+
+ case 'bearer':
+ // usage would be .auth(accessToken, { type: 'bearer' })
+ this.set('Authorization', "Bearer ".concat(user));
+ break;
+ }
+
+ return this;
+ };
+ /**
+ * Enable transmission of cookies with x-domain requests.
+ *
+ * Note that for this to work the origin must not be
+ * using "Access-Control-Allow-Origin" with a wildcard,
+ * and also must set "Access-Control-Allow-Credentials"
+ * to "true".
+ *
+ * @api public
+ */
+
+
+ RequestBase.prototype.withCredentials = function (on) {
+ // This is browser-only functionality. Node side is no-op.
+ if (on === undefined) on = true;
+ this._withCredentials = on;
+ return this;
+ };
+ /**
+ * Set the max redirects to `n`. Does nothing in browser XHR implementation.
+ *
+ * @param {Number} n
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.redirects = function (n) {
+ this._maxRedirects = n;
+ return this;
+ };
+ /**
+ * Maximum size of buffered response body, in bytes. Counts uncompressed size.
+ * Default 200MB.
+ *
+ * @param {Number} n number of bytes
+ * @return {Request} for chaining
+ */
+
+
+ RequestBase.prototype.maxResponseSize = function (n) {
+ if (typeof n !== 'number') {
+ throw new TypeError('Invalid argument');
+ }
+
+ this._maxResponseSize = n;
+ return this;
+ };
+ /**
+ * Convert to a plain javascript object (not JSON string) of scalar properties.
+ * Note as this method is designed to return a useful non-this value,
+ * it cannot be chained.
+ *
+ * @return {Object} describing method, url, and data of this request
+ * @api public
+ */
+
+
+ RequestBase.prototype.toJSON = function () {
+ return {
+ method: this.method,
+ url: this.url,
+ data: this._data,
+ headers: this._header
+ };
+ };
+ /**
+ * Send `data` as the request body, defaulting the `.type()` to "json" when
+ * an object is given.
+ *
+ * Examples:
+ *
+ * // manual json
+ * request.post('/user')
+ * .type('json')
+ * .send('{"name":"tj"}')
+ * .end(callback)
+ *
+ * // auto json
+ * request.post('/user')
+ * .send({ name: 'tj' })
+ * .end(callback)
+ *
+ * // manual x-www-form-urlencoded
+ * request.post('/user')
+ * .type('form')
+ * .send('name=tj')
+ * .end(callback)
+ *
+ * // auto x-www-form-urlencoded
+ * request.post('/user')
+ * .type('form')
+ * .send({ name: 'tj' })
+ * .end(callback)
+ *
+ * // defaults to x-www-form-urlencoded
+ * request.post('/user')
+ * .send('name=tobi')
+ * .send('species=ferret')
+ * .end(callback)
+ *
+ * @param {String|Object} data
+ * @return {Request} for chaining
+ * @api public
+ */
+ // eslint-disable-next-line complexity
+
+
+ RequestBase.prototype.send = function (data) {
+ var isObject_ = isObject(data);
+ var type = this._header['content-type'];
+
+ if (this._formData) {
+ throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
+ }
+
+ if (isObject_ && !this._data) {
+ if (Array.isArray(data)) {
+ this._data = [];
+ } else if (!this._isHost(data)) {
+ this._data = {};
+ }
+ } else if (data && this._data && this._isHost(this._data)) {
+ throw new Error("Can't merge these send calls");
+ } // merge
+
+
+ if (isObject_ && isObject(this._data)) {
+ for (var key in data) {
+ if (hasOwn(data, key)) this._data[key] = data[key];
+ }
+ } else if (typeof data === 'string') {
+ // default to x-www-form-urlencoded
+ if (!type) this.type('form');
+ type = this._header['content-type'];
+ if (type) type = type.toLowerCase().trim();
+
+ if (type === 'application/x-www-form-urlencoded') {
+ this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
+ } else {
+ this._data = (this._data || '') + data;
+ }
+ } else {
+ this._data = data;
+ }
+
+ if (!isObject_ || this._isHost(data)) {
+ return this;
+ } // default to json
+
+
+ if (!type) this.type('json');
+ return this;
+ };
+ /**
+ * Sort `querystring` by the sort function
+ *
+ *
+ * Examples:
+ *
+ * // default order
+ * request.get('/user')
+ * .query('name=Nick')
+ * .query('search=Manny')
+ * .sortQuery()
+ * .end(callback)
+ *
+ * // customized sort function
+ * request.get('/user')
+ * .query('name=Nick')
+ * .query('search=Manny')
+ * .sortQuery(function(a, b){
+ * return a.length - b.length;
+ * })
+ * .end(callback)
+ *
+ *
+ * @param {Function} sort
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ RequestBase.prototype.sortQuery = function (sort) {
+ // _sort default to true but otherwise can be a function or boolean
+ this._sort = typeof sort === 'undefined' ? true : sort;
+ return this;
+ };
+ /**
+ * Compose querystring to append to req.url
+ *
+ * @api private
+ */
+
+
+ RequestBase.prototype._finalizeQueryString = function () {
+ var query = this._query.join('&');
+
+ if (query) {
+ this.url += (this.url.includes('?') ? '&' : '?') + query;
+ }
+
+ this._query.length = 0; // Makes the call idempotent
+
+ if (this._sort) {
+ var index = this.url.indexOf('?');
+
+ if (index >= 0) {
+ var queryArray = this.url.slice(index + 1).split('&');
+
+ if (typeof this._sort === 'function') {
+ queryArray.sort(this._sort);
+ } else {
+ queryArray.sort();
+ }
+
+ this.url = this.url.slice(0, index) + '?' + queryArray.join('&');
+ }
+ }
+ }; // For backwards compat only
+
+
+ RequestBase.prototype._appendQueryString = function () {
+ console.warn('Unsupported');
+ };
+ /**
+ * Invoke callback with timeout error.
+ *
+ * @api private
+ */
+
+
+ RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
+ if (this._aborted) {
+ return;
+ }
+
+ var error = new Error("".concat(reason + timeout, "ms exceeded"));
+ error.timeout = timeout;
+ error.code = 'ECONNABORTED';
+ error.errno = errno;
+ this.timedout = true;
+ this.timedoutError = error;
+ this.abort();
+ this.callback(error);
+ };
+
+ RequestBase.prototype._setTimeouts = function () {
+ var self = this; // deadline
+
+ if (this._timeout && !this._timer) {
+ this._timer = setTimeout(function () {
+ self._timeoutError('Timeout of ', self._timeout, 'ETIME');
+ }, this._timeout);
+ } // response timeout
+
+
+ if (this._responseTimeout && !this._responseTimeoutTimer) {
+ this._responseTimeoutTimer = setTimeout(function () {
+ self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
+ }, this._responseTimeout);
+ }
+ };
+
+ return requestBase;
+}
+
+var unzip = {};
+
+var hasRequiredUnzip;
+
+function requireUnzip () {
+ if (hasRequiredUnzip) return unzip;
+ hasRequiredUnzip = 1;
+
+ /**
+ * Module dependencies.
+ */
+ var _require = require$$1$8,
+ StringDecoder = _require.StringDecoder;
+
+ var Stream = Stream$2;
+
+ var zlib = zlib$2;
+ /**
+ * Buffers response data events and re-emits when they're unzipped.
+ *
+ * @param {Request} req
+ * @param {Response} res
+ * @api private
+ */
+
+
+ unzip.unzip = function (request, res) {
+ var unzip = zlib.createUnzip();
+ var stream = new Stream();
+ var decoder; // make node responseOnEnd() happy
+
+ stream.req = request;
+ unzip.on('error', function (error) {
+ if (error && error.code === 'Z_BUF_ERROR') {
+ // unexpected end of file is ignored by browsers and curl
+ stream.emit('end');
+ return;
+ }
+
+ stream.emit('error', error);
+ }); // pipe to unzip
+
+ res.pipe(unzip); // override `setEncoding` to capture encoding
+
+ res.setEncoding = function (type) {
+ decoder = new StringDecoder(type);
+ }; // decode upon decompressing with captured encoding
+
+
+ unzip.on('data', function (buf) {
+ if (decoder) {
+ var string_ = decoder.write(buf);
+ if (string_.length > 0) stream.emit('data', string_);
+ } else {
+ stream.emit('data', buf);
+ }
+ });
+ unzip.on('end', function () {
+ stream.emit('end');
+ }); // override `on` to capture data listeners
+
+ var _on = res.on;
+
+ res.on = function (type, fn) {
+ if (type === 'data' || type === 'end') {
+ stream.on(type, fn.bind(res));
+ } else if (type === 'error') {
+ stream.on(type, fn.bind(res));
+
+ _on.call(res, type, fn);
+ } else {
+ _on.call(res, type, fn);
+ }
+
+ return this;
+ };
+ };
+
+ return unzip;
+}
+
+var responseBase;
+var hasRequiredResponseBase;
+
+function requireResponseBase () {
+ if (hasRequiredResponseBase) return responseBase;
+ hasRequiredResponseBase = 1;
+
+ /**
+ * Module dependencies.
+ */
+ var utils = requireUtils();
+ /**
+ * Expose `ResponseBase`.
+ */
+
+
+ responseBase = ResponseBase;
+ /**
+ * Initialize a new `ResponseBase`.
+ *
+ * @api public
+ */
+
+ function ResponseBase() {}
+ /**
+ * Get case-insensitive `field` value.
+ *
+ * @param {String} field
+ * @return {String}
+ * @api public
+ */
+
+
+ ResponseBase.prototype.get = function (field) {
+ return this.header[field.toLowerCase()];
+ };
+ /**
+ * Set header related properties:
+ *
+ * - `.type` the content type without params
+ *
+ * A response of "Content-Type: text/plain; charset=utf-8"
+ * will provide you with a `.type` of "text/plain".
+ *
+ * @param {Object} header
+ * @api private
+ */
+
+
+ ResponseBase.prototype._setHeaderProperties = function (header) {
+ // TODO: moar!
+ // TODO: make this a util
+ // content-type
+ var ct = header['content-type'] || '';
+ this.type = utils.type(ct); // params
+
+ var parameters = utils.params(ct);
+
+ for (var key in parameters) {
+ if (Object.prototype.hasOwnProperty.call(parameters, key)) this[key] = parameters[key];
+ }
+
+ this.links = {}; // links
+
+ try {
+ if (header.link) {
+ this.links = utils.parseLinks(header.link);
+ }
+ } catch (_unused) {// ignore
+ }
+ };
+ /**
+ * Set flags such as `.ok` based on `status`.
+ *
+ * For example a 2xx response will give you a `.ok` of __true__
+ * whereas 5xx will be __false__ and `.error` will be __true__. The
+ * `.clientError` and `.serverError` are also available to be more
+ * specific, and `.statusType` is the class of error ranging from 1..5
+ * sometimes useful for mapping respond colors etc.
+ *
+ * "sugar" properties are also defined for common cases. Currently providing:
+ *
+ * - .noContent
+ * - .badRequest
+ * - .unauthorized
+ * - .notAcceptable
+ * - .notFound
+ *
+ * @param {Number} status
+ * @api private
+ */
+
+
+ ResponseBase.prototype._setStatusProperties = function (status) {
+ var type = Math.trunc(status / 100); // status / class
+
+ this.statusCode = status;
+ this.status = this.statusCode;
+ this.statusType = type; // basics
+
+ this.info = type === 1;
+ this.ok = type === 2;
+ this.redirect = type === 3;
+ this.clientError = type === 4;
+ this.serverError = type === 5;
+ this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
+
+ this.created = status === 201;
+ this.accepted = status === 202;
+ this.noContent = status === 204;
+ this.badRequest = status === 400;
+ this.unauthorized = status === 401;
+ this.notAcceptable = status === 406;
+ this.forbidden = status === 403;
+ this.notFound = status === 404;
+ this.unprocessableEntity = status === 422;
+ };
+
+ return responseBase;
+}
+
+var response;
+var hasRequiredResponse;
+
+function requireResponse () {
+ if (hasRequiredResponse) return response;
+ hasRequiredResponse = 1;
+
+ /**
+ * Module dependencies.
+ */
+ var util = require$$1$7;
+
+ var Stream = Stream$2;
+
+ var ResponseBase = requireResponseBase();
+
+ var _require = requireUtils(),
+ mixin = _require.mixin;
+ /**
+ * Expose `Response`.
+ */
+
+
+ response = Response;
+ /**
+ * Initialize a new `Response` with the given `xhr`.
+ *
+ * - set flags (.ok, .error, etc)
+ * - parse header
+ *
+ * @param {Request} req
+ * @param {Object} options
+ * @constructor
+ * @extends {Stream}
+ * @implements {ReadableStream}
+ * @api private
+ */
+
+ function Response(request) {
+ Stream.call(this);
+ this.res = request.res;
+ var res = this.res;
+ this.request = request;
+ this.req = request.req;
+ this.text = res.text;
+ this.files = res.files || {};
+ this.buffered = request._resBuffered;
+ this.headers = res.headers;
+ this.header = this.headers;
+
+ this._setStatusProperties(res.statusCode);
+
+ this._setHeaderProperties(this.header);
+
+ this.setEncoding = res.setEncoding.bind(res);
+ res.on('data', this.emit.bind(this, 'data'));
+ res.on('end', this.emit.bind(this, 'end'));
+ res.on('close', this.emit.bind(this, 'close'));
+ res.on('error', this.emit.bind(this, 'error'));
+ } // Lazy access res.body.
+ // https://github.com/nodejs/node/pull/39520#issuecomment-889697136
+
+
+ Object.defineProperty(Response.prototype, 'body', {
+ get: function get() {
+ return this._body !== undefined ? this._body : this.res.body !== undefined ? this.res.body : {};
+ },
+ set: function set(value) {
+ this._body = value;
+ }
+ });
+ /**
+ * Inherit from `Stream`.
+ */
+
+ util.inherits(Response, Stream);
+ mixin(Response.prototype, ResponseBase.prototype);
+ /**
+ * Implements methods of a `ReadableStream`
+ */
+
+ Response.prototype.destroy = function (error) {
+ this.res.destroy(error);
+ };
+ /**
+ * Pause.
+ */
+
+
+ Response.prototype.pause = function () {
+ this.res.pause();
+ };
+ /**
+ * Resume.
+ */
+
+
+ Response.prototype.resume = function () {
+ this.res.resume();
+ };
+ /**
+ * Return an `Error` representative of this response.
+ *
+ * @return {Error}
+ * @api public
+ */
+
+
+ Response.prototype.toError = function () {
+ var req = this.req;
+ var method = req.method;
+ var path = req.path;
+ var message = "cannot ".concat(method, " ").concat(path, " (").concat(this.status, ")");
+ var error = new Error(message);
+ error.status = this.status;
+ error.text = this.text;
+ error.method = method;
+ error.path = path;
+ return error;
+ };
+
+ Response.prototype.setStatusProperties = function (status) {
+ console.warn('In superagent 2.x setStatusProperties is a private method');
+ return this._setStatusProperties(status);
+ };
+ /**
+ * To json.
+ *
+ * @return {Object}
+ * @api public
+ */
+
+
+ Response.prototype.toJSON = function () {
+ return {
+ req: this.request.toJSON(),
+ header: this.header,
+ status: this.status,
+ text: this.text
+ };
+ };
+
+ return response;
+}
+
+var http2wrapper = {};
+
+var hasRequiredHttp2wrapper;
+
+function requireHttp2wrapper () {
+ if (hasRequiredHttp2wrapper) return http2wrapper;
+ hasRequiredHttp2wrapper = 1;
+
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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 Stream = Stream$2;
+
+ var util = require$$1$7;
+
+ var net = require$$4$2;
+
+ var tls = require$$1$9; // eslint-disable-next-line node/no-deprecated-api
+
+
+ var _require = Url$2,
+ parse = _require.parse;
+
+ var process = require$$5$3;
+
+ var semverGte = requireGte();
+
+ var http2;
+ if (semverGte(process.version, 'v10.10.0')) http2 = require$$7$1;else throw new Error('superagent: this version of Node.js does not support http2');
+ var _http2$constants = http2.constants,
+ HTTP2_HEADER_PATH = _http2$constants.HTTP2_HEADER_PATH,
+ HTTP2_HEADER_STATUS = _http2$constants.HTTP2_HEADER_STATUS,
+ HTTP2_HEADER_METHOD = _http2$constants.HTTP2_HEADER_METHOD,
+ HTTP2_HEADER_AUTHORITY = _http2$constants.HTTP2_HEADER_AUTHORITY,
+ HTTP2_HEADER_HOST = _http2$constants.HTTP2_HEADER_HOST,
+ HTTP2_HEADER_SET_COOKIE = _http2$constants.HTTP2_HEADER_SET_COOKIE,
+ NGHTTP2_CANCEL = _http2$constants.NGHTTP2_CANCEL;
+
+ function setProtocol(protocol) {
+ return {
+ request: function request(options) {
+ return new Request(protocol, options);
+ }
+ };
+ }
+
+ function Request(protocol, options) {
+ var _this = this;
+
+ Stream.call(this);
+ var defaultPort = protocol === 'https:' ? 443 : 80;
+ var defaultHost = 'localhost';
+ var port = options.port || defaultPort;
+ var host = options.host || defaultHost;
+ delete options.port;
+ delete options.host;
+ this.method = options.method;
+ this.path = options.path;
+ this.protocol = protocol;
+ this.host = host;
+ delete options.method;
+ delete options.path;
+
+ var sessionOptions = _objectSpread({}, options);
+
+ if (options.socketPath) {
+ sessionOptions.socketPath = options.socketPath;
+ sessionOptions.createConnection = this.createUnixConnection.bind(this);
+ }
+
+ this._headers = {};
+ var session = http2.connect("".concat(protocol, "//").concat(host, ":").concat(port), sessionOptions);
+ this.setHeader('host', "".concat(host, ":").concat(port));
+ session.on('error', function (error) {
+ return _this.emit('error', error);
+ });
+ this.session = session;
+ }
+ /**
+ * Inherit from `Stream` (which inherits from `EventEmitter`).
+ */
+
+
+ util.inherits(Request, Stream);
+
+ Request.prototype.createUnixConnection = function (authority, options) {
+ switch (this.protocol) {
+ case 'http:':
+ return net.connect(options.socketPath);
+
+ case 'https:':
+ options.ALPNProtocols = ['h2'];
+ options.servername = this.host;
+ options.allowHalfOpen = true;
+ return tls.connect(options.socketPath, options);
+
+ default:
+ throw new Error('Unsupported protocol', this.protocol);
+ }
+ }; // eslint-disable-next-line no-unused-vars
+
+
+ Request.prototype.setNoDelay = function (bool) {// We can not use setNoDelay with HTTP/2.
+ // Node 10 limits http2session.socket methods to ones safe to use with HTTP/2.
+ // See also https://nodejs.org/api/http2.html#http2_http2session_socket
+ };
+
+ Request.prototype.getFrame = function () {
+ var _method,
+ _this2 = this;
+
+ if (this.frame) {
+ return this.frame;
+ }
+
+ var method = (_method = {}, _defineProperty(_method, HTTP2_HEADER_PATH, this.path), _defineProperty(_method, HTTP2_HEADER_METHOD, this.method), _method);
+ var headers = this.mapToHttp2Header(this._headers);
+ headers = Object.assign(headers, method);
+ var frame = this.session.request(headers); // eslint-disable-next-line no-unused-vars
+
+ frame.once('response', function (headers, flags) {
+ headers = _this2.mapToHttpHeader(headers);
+ frame.headers = headers;
+ frame.statusCode = headers[HTTP2_HEADER_STATUS];
+ frame.status = frame.statusCode;
+
+ _this2.emit('response', frame);
+ });
+ this._headerSent = true;
+ frame.once('drain', function () {
+ return _this2.emit('drain');
+ });
+ frame.on('error', function (error) {
+ return _this2.emit('error', error);
+ });
+ frame.on('close', function () {
+ return _this2.session.close();
+ });
+ this.frame = frame;
+ return frame;
+ };
+
+ Request.prototype.mapToHttpHeader = function (headers) {
+ var keys = Object.keys(headers);
+ var http2Headers = {};
+
+ for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
+ var key = _keys[_i];
+ var value = headers[key];
+ key = key.toLowerCase();
+
+ switch (key) {
+ case HTTP2_HEADER_SET_COOKIE:
+ value = Array.isArray(value) ? value : [value];
+ break;
+ }
+
+ http2Headers[key] = value;
+ }
+
+ return http2Headers;
+ };
+
+ Request.prototype.mapToHttp2Header = function (headers) {
+ var keys = Object.keys(headers);
+ var http2Headers = {};
+
+ for (var _i2 = 0, _keys2 = keys; _i2 < _keys2.length; _i2++) {
+ var key = _keys2[_i2];
+ var value = headers[key];
+ key = key.toLowerCase();
+
+ switch (key) {
+ case HTTP2_HEADER_HOST:
+ key = HTTP2_HEADER_AUTHORITY;
+ value = /^http:\/\/|^https:\/\//.test(value) ? parse(value).host : value;
+ break;
+ }
+
+ http2Headers[key] = value;
+ }
+
+ return http2Headers;
+ };
+
+ Request.prototype.setHeader = function (name, value) {
+ this._headers[name.toLowerCase()] = value;
+ };
+
+ Request.prototype.getHeader = function (name) {
+ return this._headers[name.toLowerCase()];
+ };
+
+ Request.prototype.write = function (data, encoding) {
+ var frame = this.getFrame();
+ return frame.write(data, encoding);
+ };
+
+ Request.prototype.pipe = function (stream, options) {
+ var frame = this.getFrame();
+ return frame.pipe(stream, options);
+ };
+
+ Request.prototype.end = function (data) {
+ var frame = this.getFrame();
+ frame.end(data);
+ }; // eslint-disable-next-line no-unused-vars
+
+
+ Request.prototype.abort = function (data) {
+ var frame = this.getFrame();
+ frame.close(NGHTTP2_CANCEL);
+ this.session.destroy();
+ };
+
+ http2wrapper.setProtocol = setProtocol;
+
+ return http2wrapper;
+}
+
+var agentBase;
+var hasRequiredAgentBase;
+
+function requireAgentBase () {
+ if (hasRequiredAgentBase) return agentBase;
+ hasRequiredAgentBase = 1;
+
+ 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
+
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
+
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
+
+ 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 _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 Agent() {
+ this._defaults = [];
+ }
+
+ var _loop = function _loop() {
+ var fn = _arr[_i];
+
+ // Default setting for all requests from this agent
+ Agent.prototype[fn] = function () {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ this._defaults.push({
+ fn: fn,
+ args: args
+ });
+
+ return this;
+ };
+ };
+
+ for (var _i = 0, _arr = ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts']; _i < _arr.length; _i++) {
+ _loop();
+ }
+
+ Agent.prototype._setDefaults = function (request) {
+ var _iterator = _createForOfIteratorHelper(this._defaults),
+ _step;
+
+ try {
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ var def = _step.value;
+ request[def.fn].apply(request, _toConsumableArray(def.args));
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+ };
+
+ agentBase = Agent;
+
+ return agentBase;
+}
+
+var agent;
+var hasRequiredAgent;
+
+function requireAgent () {
+ if (hasRequiredAgent) return agent;
+ hasRequiredAgent = 1;
+
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
+
+ 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 _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; }
+
+ /**
+ * Module dependencies.
+ */
+ // eslint-disable-next-line node/no-deprecated-api
+ var _require = Url$2,
+ parse = _require.parse;
+
+ var _require2 = requireCookiejar(),
+ CookieJar = _require2.CookieJar;
+
+ var _require3 = requireCookiejar(),
+ CookieAccessInfo = _require3.CookieAccessInfo;
+
+ var methods = methods$2;
+
+ var request = requireNode();
+
+ var AgentBase = requireAgentBase();
+ /**
+ * Expose `Agent`.
+ */
+
+
+ agent = Agent;
+ /**
+ * Initialize a new `Agent`.
+ *
+ * @api public
+ */
+
+ function Agent(options) {
+ if (!(this instanceof Agent)) {
+ return new Agent(options);
+ }
+
+ AgentBase.call(this);
+ this.jar = new CookieJar();
+
+ if (options) {
+ if (options.ca) {
+ this.ca(options.ca);
+ }
+
+ if (options.key) {
+ this.key(options.key);
+ }
+
+ if (options.pfx) {
+ this.pfx(options.pfx);
+ }
+
+ if (options.cert) {
+ this.cert(options.cert);
+ }
+
+ if (options.rejectUnauthorized === false) {
+ this.disableTLSCerts();
+ }
+ }
+ }
+
+ Agent.prototype = Object.create(AgentBase.prototype);
+ /**
+ * Save the cookies in the given `res` to
+ * the agent's cookie jar for persistence.
+ *
+ * @param {Response} res
+ * @api private
+ */
+
+ Agent.prototype._saveCookies = function (res) {
+ var cookies = res.headers['set-cookie'];
+ if (cookies) this.jar.setCookies(cookies);
+ };
+ /**
+ * Attach cookies when available to the given `req`.
+ *
+ * @param {Request} req
+ * @api private
+ */
+
+
+ Agent.prototype._attachCookies = function (request_) {
+ var url = parse(request_.url);
+ var access = new CookieAccessInfo(url.hostname, url.pathname, url.protocol === 'https:');
+ var cookies = this.jar.getCookies(access).toValueString();
+ request_.cookies = cookies;
+ };
+
+ var _iterator = _createForOfIteratorHelper(methods),
+ _step;
+
+ try {
+ var _loop = function _loop() {
+ var name = _step.value;
+ var method = name.toUpperCase();
+
+ Agent.prototype[name] = function (url, fn) {
+ var request_ = new request.Request(method, url);
+ request_.on('response', this._saveCookies.bind(this));
+ request_.on('redirect', this._saveCookies.bind(this));
+ request_.on('redirect', this._attachCookies.bind(this, request_));
+
+ this._setDefaults(request_);
+
+ this._attachCookies(request_);
+
+ if (fn) {
+ request_.end(fn);
+ }
+
+ return request_;
+ };
+ };
+
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ _loop();
+ }
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+
+ Agent.prototype.del = Agent.prototype.delete;
+
+ return agent;
+}
+
+var parsers = {};
+
+var urlencoded;
+var hasRequiredUrlencoded;
+
+function requireUrlencoded () {
+ if (hasRequiredUrlencoded) return urlencoded;
+ hasRequiredUrlencoded = 1;
+
+ /**
+ * Module dependencies.
+ */
+ var qs = lib$2;
+
+ urlencoded = function (res, fn) {
+ res.text = '';
+ res.setEncoding('ascii');
+ res.on('data', function (chunk) {
+ res.text += chunk;
+ });
+ res.on('end', function () {
+ try {
+ fn(null, qs.parse(res.text));
+ } catch (err) {
+ fn(err);
+ }
+ });
+ };
+
+ return urlencoded;
+}
+
+var json$1;
+var hasRequiredJson;
+
+function requireJson () {
+ if (hasRequiredJson) return json$1;
+ hasRequiredJson = 1;
+
+ json$1 = function (res, fn) {
+ res.text = '';
+ res.setEncoding('utf8');
+ res.on('data', function (chunk) {
+ res.text += chunk;
+ });
+ res.on('end', function () {
+ var body;
+ var error;
+
+ try {
+ body = res.text && JSON.parse(res.text);
+ } catch (err) {
+ error = err; // issue #675: return the raw response if the response parsing fails
+
+ error.rawResponse = res.text || null; // issue #876: return the http status code if the response parsing fails
+
+ error.statusCode = res.statusCode;
+ } finally {
+ fn(error, body);
+ }
+ });
+ };
+
+ return json$1;
+}
+
+var text;
+var hasRequiredText;
+
+function requireText () {
+ if (hasRequiredText) return text;
+ hasRequiredText = 1;
+
+ text = function (res, fn) {
+ res.text = '';
+ res.setEncoding('utf8');
+ res.on('data', function (chunk) {
+ res.text += chunk;
+ });
+ res.on('end', fn);
+ };
+
+ return text;
+}
+
+var image;
+var hasRequiredImage;
+
+function requireImage () {
+ if (hasRequiredImage) return image;
+ hasRequiredImage = 1;
+
+ image = function (res, fn) {
+ var data = []; // Binary data needs binary storage
+
+ res.on('data', function (chunk) {
+ data.push(chunk);
+ });
+ res.on('end', function () {
+ fn(null, Buffer.concat(data));
+ });
+ };
+
+ return image;
+}
+
+var hasRequiredParsers;
+
+function requireParsers () {
+ if (hasRequiredParsers) return parsers;
+ hasRequiredParsers = 1;
+ (function (exports) {
+
+ exports['application/x-www-form-urlencoded'] = requireUrlencoded();
+ exports['application/json'] = requireJson();
+ exports.text = requireText();
+ exports['application/json-seq'] = exports.text;
+
+ var binary = requireImage();
+
+ exports['application/octet-stream'] = binary;
+ exports['application/pdf'] = binary;
+ exports.image = binary;
+
+} (parsers));
+ return parsers;
+}
+
+var hasRequiredNode;
+
+function requireNode () {
+ if (hasRequiredNode) return nodeExports;
+ hasRequiredNode = 1;
+ (function (module, exports) {
+
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
+
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
+
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
+
+ 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" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) 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 _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
+
+ /**
+ * Module dependencies.
+ */
+ // eslint-disable-next-line node/no-deprecated-api
+ var _require = Url$2,
+ parse = _require.parse,
+ format = _require.format,
+ resolve = _require.resolve;
+
+ var Stream = Stream$2;
+
+ var https = https$3;
+
+ var http = http$6;
+
+ var fs = require$$0$e;
+
+ var zlib = zlib$2;
+
+ var util = require$$1$7;
+
+ var qs = lib$2;
+
+ var mime = requireMime();
+
+ var methods = methods$2;
+
+ var FormData = requireForm_data();
+
+ var formidable = requireSrc();
+
+ var debug = srcExports$4('superagent');
+
+ var CookieJar = requireCookiejar();
+
+ var semverGte = requireGte();
+
+ var safeStringify = fastSafeStringify;
+
+ var utils = requireUtils();
+
+ var RequestBase = requireRequestBase();
+
+ var _require2 = requireUnzip(),
+ unzip = _require2.unzip;
+
+ var Response = requireResponse();
+
+ var mixin = utils.mixin,
+ hasOwn = utils.hasOwn;
+ var http2;
+ if (semverGte(process.version, 'v10.10.0')) http2 = requireHttp2wrapper();
+
+ function request(method, url) {
+ // callback
+ if (typeof url === 'function') {
+ return new exports.Request('GET', method).end(url);
+ } // url first
+
+
+ if (arguments.length === 1) {
+ return new exports.Request('GET', method);
+ }
+
+ return new exports.Request(method, url);
+ }
+
+ module.exports = request;
+ exports = module.exports;
+ /**
+ * Expose `Request`.
+ */
+
+ exports.Request = Request;
+ /**
+ * Expose the agent function
+ */
+
+ exports.agent = requireAgent();
+ /**
+ * Noop.
+ */
+
+ function noop() {}
+ /**
+ * Expose `Response`.
+ */
+
+
+ exports.Response = Response;
+ /**
+ * Define "form" mime type.
+ */
+
+ mime.define({
+ 'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data']
+ }, true);
+ /**
+ * Protocol map.
+ */
+
+ exports.protocols = {
+ 'http:': http,
+ 'https:': https,
+ 'http2:': http2
+ };
+ /**
+ * Default serialization map.
+ *
+ * superagent.serialize['application/xml'] = function(obj){
+ * return 'generated xml here';
+ * };
+ *
+ */
+
+ exports.serialize = {
+ 'application/x-www-form-urlencoded': qs.stringify,
+ 'application/json': safeStringify
+ };
+ /**
+ * Default parsers.
+ *
+ * superagent.parse['application/xml'] = function(res, fn){
+ * fn(null, res);
+ * };
+ *
+ */
+
+ exports.parse = requireParsers();
+ /**
+ * Default buffering map. Can be used to set certain
+ * response types to buffer/not buffer.
+ *
+ * superagent.buffer['application/xml'] = true;
+ */
+
+ exports.buffer = {};
+ /**
+ * Initialize internal header tracking properties on a request instance.
+ *
+ * @param {Object} req the instance
+ * @api private
+ */
+
+ function _initHeaders(request_) {
+ request_._header = {// coerces header names to lowercase
+ };
+ request_.header = {// preserves header name case
+ };
+ }
+ /**
+ * Initialize a new `Request` with the given `method` and `url`.
+ *
+ * @param {String} method
+ * @param {String|Object} url
+ * @api public
+ */
+
+
+ function Request(method, url) {
+ Stream.call(this);
+ if (typeof url !== 'string') url = format(url);
+ this._enableHttp2 = Boolean(process.env.HTTP2_TEST); // internal only
+
+ this._agent = false;
+ this._formData = null;
+ this.method = method;
+ this.url = url;
+
+ _initHeaders(this);
+
+ this.writable = true;
+ this._redirects = 0;
+ this.redirects(method === 'HEAD' ? 0 : 5);
+ this.cookies = '';
+ this.qs = {};
+ this._query = [];
+ this.qsRaw = this._query; // Unused, for backwards compatibility only
+
+ this._redirectList = [];
+ this._streamRequest = false;
+ this._lookup = undefined;
+ this.once('end', this.clearTimeout.bind(this));
+ }
+ /**
+ * Inherit from `Stream` (which inherits from `EventEmitter`).
+ * Mixin `RequestBase`.
+ */
+
+
+ util.inherits(Request, Stream);
+ mixin(Request.prototype, RequestBase.prototype);
+ /**
+ * Enable or Disable http2.
+ *
+ * Enable http2.
+ *
+ * ``` js
+ * request.get('http://localhost/')
+ * .http2()
+ * .end(callback);
+ *
+ * request.get('http://localhost/')
+ * .http2(true)
+ * .end(callback);
+ * ```
+ *
+ * Disable http2.
+ *
+ * ``` js
+ * request = request.http2();
+ * request.get('http://localhost/')
+ * .http2(false)
+ * .end(callback);
+ * ```
+ *
+ * @param {Boolean} enable
+ * @return {Request} for chaining
+ * @api public
+ */
+
+ Request.prototype.http2 = function (bool) {
+ if (exports.protocols['http2:'] === undefined) {
+ throw new Error('superagent: this version of Node.js does not support http2');
+ }
+
+ this._enableHttp2 = bool === undefined ? true : bool;
+ return this;
+ };
+ /**
+ * Queue the given `file` as an attachment to the specified `field`,
+ * with optional `options` (or filename).
+ *
+ * ``` js
+ * request.post('http://localhost/upload')
+ * .attach('field', Buffer.from('Hello world'), 'hello.html')
+ * .end(callback);
+ * ```
+ *
+ * A filename may also be used:
+ *
+ * ``` js
+ * request.post('http://localhost/upload')
+ * .attach('files', 'image.jpg')
+ * .end(callback);
+ * ```
+ *
+ * @param {String} field
+ * @param {String|fs.ReadStream|Buffer} file
+ * @param {String|Object} options
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.attach = function (field, file, options) {
+ var _this = this;
+
+ if (file) {
+ if (this._data) {
+ throw new Error("superagent can't mix .send() and .attach()");
+ }
+
+ var o = options || {};
+
+ if (typeof options === 'string') {
+ o = {
+ filename: options
+ };
+ }
+
+ if (typeof file === 'string') {
+ if (!o.filename) o.filename = file;
+ debug('creating `fs.ReadStream` instance for file: %s', file);
+ file = fs.createReadStream(file);
+ file.on('error', function (error) {
+ var formData = _this._getFormData();
+
+ formData.emit('error', error);
+ });
+ } else if (!o.filename && file.path) {
+ o.filename = file.path;
+ }
+
+ this._getFormData().append(field, file, o);
+ }
+
+ return this;
+ };
+
+ Request.prototype._getFormData = function () {
+ var _this2 = this;
+
+ if (!this._formData) {
+ this._formData = new FormData();
+
+ this._formData.on('error', function (error) {
+ debug('FormData error', error);
+
+ if (_this2.called) {
+ // The request has already finished and the callback was called.
+ // Silently ignore the error.
+ return;
+ }
+
+ _this2.callback(error);
+
+ _this2.abort();
+ });
+ }
+
+ return this._formData;
+ };
+ /**
+ * Gets/sets the `Agent` to use for this HTTP request. The default (if this
+ * function is not called) is to opt out of connection pooling (`agent: false`).
+ *
+ * @param {http.Agent} agent
+ * @return {http.Agent}
+ * @api public
+ */
+
+
+ Request.prototype.agent = function (agent) {
+ if (arguments.length === 0) return this._agent;
+ this._agent = agent;
+ return this;
+ };
+ /**
+ * Gets/sets the `lookup` function to use custom DNS resolver.
+ *
+ * @param {Function} lookup
+ * @return {Function}
+ * @api public
+ */
+
+
+ Request.prototype.lookup = function (lookup) {
+ if (arguments.length === 0) return this._lookup;
+ this._lookup = lookup;
+ return this;
+ };
+ /**
+ * Set _Content-Type_ response header passed through `mime.getType()`.
+ *
+ * Examples:
+ *
+ * request.post('/')
+ * .type('xml')
+ * .send(xmlstring)
+ * .end(callback);
+ *
+ * request.post('/')
+ * .type('json')
+ * .send(jsonstring)
+ * .end(callback);
+ *
+ * request.post('/')
+ * .type('application/json')
+ * .send(jsonstring)
+ * .end(callback);
+ *
+ * @param {String} type
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.type = function (type) {
+ return this.set('Content-Type', type.includes('/') ? type : mime.getType(type));
+ };
+ /**
+ * Set _Accept_ response header passed through `mime.getType()`.
+ *
+ * Examples:
+ *
+ * superagent.types.json = 'application/json';
+ *
+ * request.get('/agent')
+ * .accept('json')
+ * .end(callback);
+ *
+ * request.get('/agent')
+ * .accept('application/json')
+ * .end(callback);
+ *
+ * @param {String} accept
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.accept = function (type) {
+ return this.set('Accept', type.includes('/') ? type : mime.getType(type));
+ };
+ /**
+ * Add query-string `val`.
+ *
+ * Examples:
+ *
+ * request.get('/shoes')
+ * .query('size=10')
+ * .query({ color: 'blue' })
+ *
+ * @param {Object|String} val
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.query = function (value) {
+ if (typeof value === 'string') {
+ this._query.push(value);
+ } else {
+ Object.assign(this.qs, value);
+ }
+
+ return this;
+ };
+ /**
+ * Write raw `data` / `encoding` to the socket.
+ *
+ * @param {Buffer|String} data
+ * @param {String} encoding
+ * @return {Boolean}
+ * @api public
+ */
+
+
+ Request.prototype.write = function (data, encoding) {
+ var request_ = this.request();
+
+ if (!this._streamRequest) {
+ this._streamRequest = true;
+ }
+
+ return request_.write(data, encoding);
+ };
+ /**
+ * Pipe the request body to `stream`.
+ *
+ * @param {Stream} stream
+ * @param {Object} options
+ * @return {Stream}
+ * @api public
+ */
+
+
+ Request.prototype.pipe = function (stream, options) {
+ this.piped = true; // HACK...
+
+ this.buffer(false);
+ this.end();
+ return this._pipeContinue(stream, options);
+ };
+
+ Request.prototype._pipeContinue = function (stream, options) {
+ var _this3 = this;
+
+ this.req.once('response', function (res) {
+ // redirect
+ if (isRedirect(res.statusCode) && _this3._redirects++ !== _this3._maxRedirects) {
+ return _this3._redirect(res) === _this3 ? _this3._pipeContinue(stream, options) : undefined;
+ }
+
+ _this3.res = res;
+
+ _this3._emitResponse();
+
+ if (_this3._aborted) return;
+
+ if (_this3._shouldUnzip(res)) {
+ var unzipObject = zlib.createUnzip();
+ unzipObject.on('error', function (error) {
+ if (error && error.code === 'Z_BUF_ERROR') {
+ // unexpected end of file is ignored by browsers and curl
+ stream.emit('end');
+ return;
+ }
+
+ stream.emit('error', error);
+ });
+ res.pipe(unzipObject).pipe(stream, options);
+ } else {
+ res.pipe(stream, options);
+ }
+
+ res.once('end', function () {
+ _this3.emit('end');
+ });
+ });
+ return stream;
+ };
+ /**
+ * Enable / disable buffering.
+ *
+ * @return {Boolean} [val]
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.buffer = function (value) {
+ this._buffer = value !== false;
+ return this;
+ };
+ /**
+ * Redirect to `url
+ *
+ * @param {IncomingMessage} res
+ * @return {Request} for chaining
+ * @api private
+ */
+
+
+ Request.prototype._redirect = function (res) {
+ var url = res.headers.location;
+
+ if (!url) {
+ return this.callback(new Error('No location header for redirect'), res);
+ }
+
+ debug('redirect %s -> %s', this.url, url); // location
+
+ url = resolve(this.url, url); // ensure the response is being consumed
+ // this is required for Node v0.10+
+
+ res.resume();
+ var headers = this.req.getHeaders ? this.req.getHeaders() : this.req._headers;
+ var changesOrigin = parse(url).host !== parse(this.url).host; // implementation of 302 following defacto standard
+
+ if (res.statusCode === 301 || res.statusCode === 302) {
+ // strip Content-* related fields
+ // in case of POST etc
+ headers = utils.cleanHeader(headers, changesOrigin); // force GET
+
+ this.method = this.method === 'HEAD' ? 'HEAD' : 'GET'; // clear data
+
+ this._data = null;
+ } // 303 is always GET
+
+
+ if (res.statusCode === 303) {
+ // strip Content-* related fields
+ // in case of POST etc
+ headers = utils.cleanHeader(headers, changesOrigin); // force method
+
+ this.method = 'GET'; // clear data
+
+ this._data = null;
+ } // 307 preserves method
+ // 308 preserves method
+
+
+ delete headers.host;
+ delete this.req;
+ delete this._formData; // remove all add header except User-Agent
+
+ _initHeaders(this); // redirect
+
+
+ this._endCalled = false;
+ this.url = url;
+ this.qs = {};
+ this._query.length = 0;
+ this.set(headers);
+ this.emit('redirect', res);
+
+ this._redirectList.push(this.url);
+
+ this.end(this._callback);
+ return this;
+ };
+ /**
+ * Set Authorization field value with `user` and `pass`.
+ *
+ * Examples:
+ *
+ * .auth('tobi', 'learnboost')
+ * .auth('tobi:learnboost')
+ * .auth('tobi')
+ * .auth(accessToken, { type: 'bearer' })
+ *
+ * @param {String} user
+ * @param {String} [pass]
+ * @param {Object} [options] options with authorization type 'basic' or 'bearer' ('basic' is default)
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.auth = function (user, pass, options) {
+ if (arguments.length === 1) pass = '';
+
+ if (_typeof(pass) === 'object' && pass !== null) {
+ // pass is optional and can be replaced with options
+ options = pass;
+ pass = '';
+ }
+
+ if (!options) {
+ options = {
+ type: 'basic'
+ };
+ }
+
+ var encoder = function encoder(string) {
+ return Buffer.from(string).toString('base64');
+ };
+
+ return this._auth(user, pass, options, encoder);
+ };
+ /**
+ * Set the certificate authority option for https request.
+ *
+ * @param {Buffer | Array} cert
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.ca = function (cert) {
+ this._ca = cert;
+ return this;
+ };
+ /**
+ * Set the client certificate key option for https request.
+ *
+ * @param {Buffer | String} cert
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.key = function (cert) {
+ this._key = cert;
+ return this;
+ };
+ /**
+ * Set the key, certificate, and CA certs of the client in PFX or PKCS12 format.
+ *
+ * @param {Buffer | String} cert
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.pfx = function (cert) {
+ if (_typeof(cert) === 'object' && !Buffer.isBuffer(cert)) {
+ this._pfx = cert.pfx;
+ this._passphrase = cert.passphrase;
+ } else {
+ this._pfx = cert;
+ }
+
+ return this;
+ };
+ /**
+ * Set the client certificate option for https request.
+ *
+ * @param {Buffer | String} cert
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.cert = function (cert) {
+ this._cert = cert;
+ return this;
+ };
+ /**
+ * Do not reject expired or invalid TLS certs.
+ * sets `rejectUnauthorized=true`. Be warned that this allows MITM attacks.
+ *
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype.disableTLSCerts = function () {
+ this._disableTLSCerts = true;
+ return this;
+ };
+ /**
+ * Return an http[s] request.
+ *
+ * @return {OutgoingMessage}
+ * @api private
+ */
+ // eslint-disable-next-line complexity
+
+
+ Request.prototype.request = function () {
+ var _this4 = this;
+
+ if (this.req) return this.req;
+ var options = {};
+
+ try {
+ var query = qs.stringify(this.qs, {
+ indices: false,
+ strictNullHandling: true
+ });
+
+ if (query) {
+ this.qs = {};
+
+ this._query.push(query);
+ }
+
+ this._finalizeQueryString();
+ } catch (err) {
+ return this.emit('error', err);
+ }
+
+ var url = this.url;
+ var retries = this._retries; // Capture backticks as-is from the final query string built above.
+ // Note: this'll only find backticks entered in req.query(String)
+ // calls, because qs.stringify unconditionally encodes backticks.
+
+ var queryStringBackticks;
+
+ if (url.includes('`')) {
+ var queryStartIndex = url.indexOf('?');
+
+ if (queryStartIndex !== -1) {
+ var queryString = url.slice(queryStartIndex + 1);
+ queryStringBackticks = queryString.match(/`|%60/g);
+ }
+ } // default to http://
+
+
+ if (url.indexOf('http') !== 0) url = "http://".concat(url);
+ url = parse(url); // See https://github.com/visionmedia/superagent/issues/1367
+
+ if (queryStringBackticks) {
+ var i = 0;
+ url.query = url.query.replace(/%60/g, function () {
+ return queryStringBackticks[i++];
+ });
+ url.search = "?".concat(url.query);
+ url.path = url.pathname + url.search;
+ } // support unix sockets
+
+
+ if (/^https?\+unix:/.test(url.protocol) === true) {
+ // get the protocol
+ url.protocol = "".concat(url.protocol.split('+')[0], ":"); // get the socket, path
+
+ var unixParts = url.path.match(/^([^/]+)(.+)$/);
+ options.socketPath = unixParts[1].replace(/%2F/g, '/');
+ url.path = unixParts[2];
+ } // Override IP address of a hostname
+
+
+ if (this._connectOverride) {
+ var _url = url,
+ hostname = _url.hostname;
+ var match = hostname in this._connectOverride ? this._connectOverride[hostname] : this._connectOverride['*'];
+
+ if (match) {
+ // backup the real host
+ if (!this._header.host) {
+ this.set('host', url.host);
+ }
+
+ var newHost;
+ var newPort;
+
+ if (_typeof(match) === 'object') {
+ newHost = match.host;
+ newPort = match.port;
+ } else {
+ newHost = match;
+ newPort = url.port;
+ } // wrap [ipv6]
+
+
+ url.host = /:/.test(newHost) ? "[".concat(newHost, "]") : newHost;
+
+ if (newPort) {
+ url.host += ":".concat(newPort);
+ url.port = newPort;
+ }
+
+ url.hostname = newHost;
+ }
+ } // options
+
+
+ options.method = this.method;
+ options.port = url.port;
+ options.path = url.path;
+ options.host = url.hostname;
+ options.ca = this._ca;
+ options.key = this._key;
+ options.pfx = this._pfx;
+ options.cert = this._cert;
+ options.passphrase = this._passphrase;
+ options.agent = this._agent;
+ options.lookup = this._lookup;
+ options.rejectUnauthorized = typeof this._disableTLSCerts === 'boolean' ? !this._disableTLSCerts : process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; // Allows request.get('https://1.2.3.4/').set('Host', 'example.com')
+
+ if (this._header.host) {
+ options.servername = this._header.host.replace(/:\d+$/, '');
+ }
+
+ if (this._trustLocalhost && /^(?:localhost|127\.0\.0\.\d+|(0*:)+:0*1)$/.test(url.hostname)) {
+ options.rejectUnauthorized = false;
+ } // initiate request
+
+
+ var module_ = this._enableHttp2 ? exports.protocols['http2:'].setProtocol(url.protocol) : exports.protocols[url.protocol]; // request
+
+ this.req = module_.request(options);
+ var req = this.req; // set tcp no delay
+
+ req.setNoDelay(true);
+
+ if (options.method !== 'HEAD') {
+ req.setHeader('Accept-Encoding', 'gzip, deflate');
+ }
+
+ this.protocol = url.protocol;
+ this.host = url.host; // expose events
+
+ req.once('drain', function () {
+ _this4.emit('drain');
+ });
+ req.on('error', function (error) {
+ // flag abortion here for out timeouts
+ // because node will emit a faux-error "socket hang up"
+ // when request is aborted before a connection is made
+ if (_this4._aborted) return; // if not the same, we are in the **old** (cancelled) request,
+ // so need to continue (same as for above)
+
+ if (_this4._retries !== retries) return; // if we've received a response then we don't want to let
+ // an error in the request blow up the response
+
+ if (_this4.response) return;
+
+ _this4.callback(error);
+ }); // auth
+
+ if (url.auth) {
+ var auth = url.auth.split(':');
+ this.auth(auth[0], auth[1]);
+ }
+
+ if (this.username && this.password) {
+ this.auth(this.username, this.password);
+ }
+
+ for (var key in this.header) {
+ if (hasOwn(this.header, key)) req.setHeader(key, this.header[key]);
+ } // add cookies
+
+
+ if (this.cookies) {
+ if (hasOwn(this._header, 'cookie')) {
+ // merge
+ var temporaryJar = new CookieJar.CookieJar();
+ temporaryJar.setCookies(this._header.cookie.split(';'));
+ temporaryJar.setCookies(this.cookies.split(';'));
+ req.setHeader('Cookie', temporaryJar.getCookies(CookieJar.CookieAccessInfo.All).toValueString());
+ } else {
+ req.setHeader('Cookie', this.cookies);
+ }
+ }
+
+ return req;
+ };
+ /**
+ * Invoke the callback with `err` and `res`
+ * and handle arity check.
+ *
+ * @param {Error} err
+ * @param {Response} res
+ * @api private
+ */
+
+
+ Request.prototype.callback = function (error, res) {
+ if (this._shouldRetry(error, res)) {
+ return this._retry();
+ } // Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime.
+
+
+ var fn = this._callback || noop;
+ this.clearTimeout();
+ if (this.called) return console.warn('superagent: double callback bug');
+ this.called = true;
+
+ if (!error) {
+ try {
+ if (!this._isResponseOK(res)) {
+ var message = 'Unsuccessful HTTP response';
+
+ if (res) {
+ message = http.STATUS_CODES[res.status] || message;
+ }
+
+ error = new Error(message);
+ error.status = res ? res.status : undefined;
+ }
+ } catch (err) {
+ error = err;
+ error.status = error.status || (res ? res.status : undefined);
+ }
+ } // It's important that the callback is called outside try/catch
+ // to avoid double callback
+
+
+ if (!error) {
+ return fn(null, res);
+ }
+
+ error.response = res;
+ if (this._maxRetries) error.retries = this._retries - 1; // only emit error event if there is a listener
+ // otherwise we assume the callback to `.end()` will get the error
+
+ if (error && this.listeners('error').length > 0) {
+ this.emit('error', error);
+ }
+
+ fn(error, res);
+ };
+ /**
+ * Check if `obj` is a host object,
+ *
+ * @param {Object} obj host object
+ * @return {Boolean} is a host object
+ * @api private
+ */
+
+
+ Request.prototype._isHost = function (object) {
+ return Buffer.isBuffer(object) || object instanceof Stream || object instanceof FormData;
+ };
+ /**
+ * Initiate request, invoking callback `fn(err, res)`
+ * with an instanceof `Response`.
+ *
+ * @param {Function} fn
+ * @return {Request} for chaining
+ * @api public
+ */
+
+
+ Request.prototype._emitResponse = function (body, files) {
+ var response = new Response(this);
+ this.response = response;
+ response.redirects = this._redirectList;
+
+ if (undefined !== body) {
+ response.body = body;
+ }
+
+ response.files = files;
+
+ if (this._endCalled) {
+ response.pipe = function () {
+ throw new Error("end() has already been called, so it's too late to start piping");
+ };
+ }
+
+ this.emit('response', response);
+ return response;
+ };
+
+ Request.prototype.end = function (fn) {
+ this.request();
+ debug('%s %s', this.method, this.url);
+
+ if (this._endCalled) {
+ throw new Error('.end() was called twice. This is not supported in superagent');
+ }
+
+ this._endCalled = true; // store callback
+
+ this._callback = fn || noop;
+
+ this._end();
+ };
+
+ Request.prototype._end = function () {
+ var _this5 = this;
+
+ if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
+ var data = this._data;
+ var req = this.req;
+ var method = this.method;
+
+ this._setTimeouts(); // body
+
+
+ if (method !== 'HEAD' && !req._headerSent) {
+ // serialize stuff
+ if (typeof data !== 'string') {
+ var contentType = req.getHeader('Content-Type'); // Parse out just the content type from the header (ignore the charset)
+
+ if (contentType) contentType = contentType.split(';')[0];
+ var serialize = this._serializer || exports.serialize[contentType];
+
+ if (!serialize && isJSON(contentType)) {
+ serialize = exports.serialize['application/json'];
+ }
+
+ if (serialize) data = serialize(data);
+ } // content-length
+
+
+ if (data && !req.getHeader('Content-Length')) {
+ req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data));
+ }
+ } // response
+ // eslint-disable-next-line complexity
+
+
+ req.once('response', function (res) {
+ debug('%s %s -> %s', _this5.method, _this5.url, res.statusCode);
+
+ if (_this5._responseTimeoutTimer) {
+ clearTimeout(_this5._responseTimeoutTimer);
+ }
+
+ if (_this5.piped) {
+ return;
+ }
+
+ var max = _this5._maxRedirects;
+ var mime = utils.type(res.headers['content-type'] || '') || 'text/plain';
+ var type = mime.split('/')[0];
+ if (type) type = type.toLowerCase().trim();
+ var multipart = type === 'multipart';
+ var redirect = isRedirect(res.statusCode);
+ var responseType = _this5._responseType;
+ _this5.res = res; // redirect
+
+ if (redirect && _this5._redirects++ !== max) {
+ return _this5._redirect(res);
+ }
+
+ if (_this5.method === 'HEAD') {
+ _this5.emit('end');
+
+ _this5.callback(null, _this5._emitResponse());
+
+ return;
+ } // zlib support
+
+
+ if (_this5._shouldUnzip(res)) {
+ unzip(req, res);
+ }
+
+ var buffer = _this5._buffer;
+
+ if (buffer === undefined && mime in exports.buffer) {
+ buffer = Boolean(exports.buffer[mime]);
+ }
+
+ var parser = _this5._parser;
+
+ if (undefined === buffer && parser) {
+ console.warn("A custom superagent parser has been set, but buffering strategy for the parser hasn't been configured. Call `req.buffer(true or false)` or set `superagent.buffer[mime] = true or false`");
+ buffer = true;
+ }
+
+ if (!parser) {
+ if (responseType) {
+ parser = exports.parse.image; // It's actually a generic Buffer
+
+ buffer = true;
+ } else if (multipart) {
+ var form = formidable();
+ parser = form.parse.bind(form);
+ buffer = true;
+ } else if (isBinary(mime)) {
+ parser = exports.parse.image;
+ buffer = true; // For backwards-compatibility buffering default is ad-hoc MIME-dependent
+ } else if (exports.parse[mime]) {
+ parser = exports.parse[mime];
+ } else if (type === 'text') {
+ parser = exports.parse.text;
+ buffer = buffer !== false; // everyone wants their own white-labeled json
+ } else if (isJSON(mime)) {
+ parser = exports.parse['application/json'];
+ buffer = buffer !== false;
+ } else if (buffer) {
+ parser = exports.parse.text;
+ } else if (undefined === buffer) {
+ parser = exports.parse.image; // It's actually a generic Buffer
+
+ buffer = true;
+ }
+ } // by default only buffer text/*, json and messed up thing from hell
+
+
+ if (undefined === buffer && isText(mime) || isJSON(mime)) {
+ buffer = true;
+ }
+
+ _this5._resBuffered = buffer;
+ var parserHandlesEnd = false;
+
+ if (buffer) {
+ // Protectiona against zip bombs and other nuisance
+ var responseBytesLeft = _this5._maxResponseSize || 200000000;
+ res.on('data', function (buf) {
+ responseBytesLeft -= buf.byteLength || buf.length > 0 ? buf.length : 0;
+
+ if (responseBytesLeft < 0) {
+ // This will propagate through error event
+ var error = new Error('Maximum response size reached');
+ error.code = 'ETOOLARGE'; // Parsers aren't required to observe error event,
+ // so would incorrectly report success
+
+ parserHandlesEnd = false; // Will not emit error event
+
+ res.destroy(error); // so we do callback now
+
+ _this5.callback(error, null);
+ }
+ });
+ }
+
+ if (parser) {
+ try {
+ // Unbuffered parsers are supposed to emit response early,
+ // which is weird BTW, because response.body won't be there.
+ parserHandlesEnd = buffer;
+ parser(res, function (error, object, files) {
+ if (_this5.timedout) {
+ // Timeout has already handled all callbacks
+ return;
+ } // Intentional (non-timeout) abort is supposed to preserve partial response,
+ // even if it doesn't parse.
+
+
+ if (error && !_this5._aborted) {
+ return _this5.callback(error);
+ }
+
+ if (parserHandlesEnd) {
+ _this5.emit('end');
+
+ _this5.callback(null, _this5._emitResponse(object, files));
+ }
+ });
+ } catch (err) {
+ _this5.callback(err);
+
+ return;
+ }
+ }
+
+ _this5.res = res; // unbuffered
+
+ if (!buffer) {
+ debug('unbuffered %s %s', _this5.method, _this5.url);
+
+ _this5.callback(null, _this5._emitResponse());
+
+ if (multipart) return; // allow multipart to handle end event
+
+ res.once('end', function () {
+ debug('end %s %s', _this5.method, _this5.url);
+
+ _this5.emit('end');
+ });
+ return;
+ } // terminating events
+
+
+ res.once('error', function (error) {
+ parserHandlesEnd = false;
+
+ _this5.callback(error, null);
+ });
+ if (!parserHandlesEnd) res.once('end', function () {
+ debug('end %s %s', _this5.method, _this5.url); // TODO: unless buffering emit earlier to stream
+
+ _this5.emit('end');
+
+ _this5.callback(null, _this5._emitResponse());
+ });
+ });
+ this.emit('request', this);
+
+ var getProgressMonitor = function getProgressMonitor() {
+ var lengthComputable = true;
+ var total = req.getHeader('Content-Length');
+ var loaded = 0;
+ var progress = new Stream.Transform();
+
+ progress._transform = function (chunk, encoding, callback) {
+ loaded += chunk.length;
+
+ _this5.emit('progress', {
+ direction: 'upload',
+ lengthComputable: lengthComputable,
+ loaded: loaded,
+ total: total
+ });
+
+ callback(null, chunk);
+ };
+
+ return progress;
+ };
+
+ var bufferToChunks = function bufferToChunks(buffer) {
+ var chunkSize = 16 * 1024; // default highWaterMark value
+
+ var chunking = new Stream.Readable();
+ var totalLength = buffer.length;
+ var remainder = totalLength % chunkSize;
+ var cutoff = totalLength - remainder;
+
+ for (var i = 0; i < cutoff; i += chunkSize) {
+ var chunk = buffer.slice(i, i + chunkSize);
+ chunking.push(chunk);
+ }
+
+ if (remainder > 0) {
+ var remainderBuffer = buffer.slice(-remainder);
+ chunking.push(remainderBuffer);
+ }
+
+ chunking.push(null); // no more data
+
+ return chunking;
+ }; // if a FormData instance got created, then we send that as the request body
+
+
+ var formData = this._formData;
+
+ if (formData) {
+ // set headers
+ var headers = formData.getHeaders();
+
+ for (var i in headers) {
+ if (hasOwn(headers, i)) {
+ debug('setting FormData header: "%s: %s"', i, headers[i]);
+ req.setHeader(i, headers[i]);
+ }
+ } // attempt to get "Content-Length" header
+
+
+ formData.getLength(function (error, length) {
+ // TODO: Add chunked encoding when no length (if err)
+ if (error) debug('formData.getLength had error', error, length);
+ debug('got FormData Content-Length: %s', length);
+
+ if (typeof length === 'number') {
+ req.setHeader('Content-Length', length);
+ }
+
+ formData.pipe(getProgressMonitor()).pipe(req);
+ });
+ } else if (Buffer.isBuffer(data)) {
+ bufferToChunks(data).pipe(getProgressMonitor()).pipe(req);
+ } else {
+ req.end(data);
+ }
+ }; // Check whether response has a non-0-sized gzip-encoded body
+
+
+ Request.prototype._shouldUnzip = function (res) {
+ if (res.statusCode === 204 || res.statusCode === 304) {
+ // These aren't supposed to have any body
+ return false;
+ } // header content is a string, and distinction between 0 and no information is crucial
+
+
+ if (res.headers['content-length'] === '0') {
+ // We know that the body is empty (unfortunately, this check does not cover chunked encoding)
+ return false;
+ } // console.log(res);
+
+
+ return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']);
+ };
+ /**
+ * Overrides DNS for selected hostnames. Takes object mapping hostnames to IP addresses.
+ *
+ * When making a request to a URL with a hostname exactly matching a key in the object,
+ * use the given IP address to connect, instead of using DNS to resolve the hostname.
+ *
+ * A special host `*` matches every hostname (keep redirects in mind!)
+ *
+ * request.connect({
+ * 'test.example.com': '127.0.0.1',
+ * 'ipv6.example.com': '::1',
+ * })
+ */
+
+
+ Request.prototype.connect = function (connectOverride) {
+ if (typeof connectOverride === 'string') {
+ this._connectOverride = {
+ '*': connectOverride
+ };
+ } else if (_typeof(connectOverride) === 'object') {
+ this._connectOverride = connectOverride;
+ } else {
+ this._connectOverride = undefined;
+ }
+
+ return this;
+ };
+
+ Request.prototype.trustLocalhost = function (toggle) {
+ this._trustLocalhost = toggle === undefined ? true : toggle;
+ return this;
+ }; // generate HTTP verb methods
+
+
+ if (!methods.includes('del')) {
+ // create a copy so we don't cause conflicts with
+ // other packages using the methods package and
+ // npm 3.x
+ methods = _toConsumableArray(methods);
+ methods.push('del');
+ }
+
+ var _iterator = _createForOfIteratorHelper(methods),
+ _step;
+
+ try {
+ var _loop = function _loop() {
+ var method = _step.value;
+ var name = method;
+ method = method === 'del' ? 'delete' : method;
+ method = method.toUpperCase();
+
+ request[name] = function (url, data, fn) {
+ var request_ = request(method, url);
+
+ if (typeof data === 'function') {
+ fn = data;
+ data = null;
+ }
+
+ if (data) {
+ if (method === 'GET' || method === 'HEAD') {
+ request_.query(data);
+ } else {
+ request_.send(data);
+ }
+ }
+
+ if (fn) request_.end(fn);
+ return request_;
+ };
+ };
+
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
+ _loop();
+ }
+ /**
+ * Check if `mime` is text and should be buffered.
+ *
+ * @param {String} mime
+ * @return {Boolean}
+ * @api public
+ */
+
+ } catch (err) {
+ _iterator.e(err);
+ } finally {
+ _iterator.f();
+ }
+
+ function isText(mime) {
+ var parts = mime.split('/');
+ var type = parts[0];
+ if (type) type = type.toLowerCase().trim();
+ var subtype = parts[1];
+ if (subtype) subtype = subtype.toLowerCase().trim();
+ return type === 'text' || subtype === 'x-www-form-urlencoded';
+ } // This is not a catchall, but a start. It might be useful
+ // in the long run to have file that includes all binary
+ // content types from https://www.iana.org/assignments/media-types/media-types.xhtml
+
+
+ function isBinary(mime) {
+ var _mime$split = mime.split('/'),
+ _mime$split2 = _slicedToArray(_mime$split, 2),
+ registry = _mime$split2[0],
+ name = _mime$split2[1];
+
+ if (registry) registry = registry.toLowerCase().trim();
+ if (name) name = name.toLowerCase().trim();
+ return ['audio', 'font', 'image', 'video'].includes(registry) || ['gz', 'gzip'].includes(name);
+ }
+ /**
+ * Check if `mime` is json or has +json structured syntax suffix.
+ *
+ * @param {String} mime
+ * @return {Boolean}
+ * @api private
+ */
+
+
+ function isJSON(mime) {
+ // should match /json or +json
+ // but not /json-seq
+ return /[/+]json($|[^-\w])/i.test(mime);
+ }
+ /**
+ * Check if we should follow the redirect `code`.
+ *
+ * @param {Number} code
+ * @return {Boolean}
+ * @api private
+ */
+
+
+ function isRedirect(code) {
+ return [301, 302, 303, 305, 307, 308].includes(code);
+ }
+
+} (node, nodeExports));
+ return nodeExports;
+}
+
+var smeeClient;
+var hasRequiredSmeeClient;
+
+function requireSmeeClient () {
+ if (hasRequiredSmeeClient) return smeeClient;
+ hasRequiredSmeeClient = 1;
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
+ const validator_1 = __importDefault(requireValidator());
+ const eventsource_1 = __importDefault(requireEventsource());
+ const superagent_1 = __importDefault(requireNode());
+ const url_1 = __importDefault(Url$2);
+ const querystring_1 = __importDefault(require$$8$1);
+ class Client {
+ constructor({ source, target, logger = console }) {
+ this.source = source;
+ this.target = target;
+ this.logger = logger;
+ if (!validator_1.default.isURL(this.source)) {
+ throw new Error('The provided URL is invalid.');
+ }
+ }
+ static async createChannel() {
+ return superagent_1.default.head('https://smee.io/new').redirects(0).catch((err) => {
+ return err.response.headers.location;
+ });
+ }
+ onmessage(msg) {
+ const data = JSON.parse(msg.data);
+ const target = url_1.default.parse(this.target, true);
+ const mergedQuery = Object.assign(target.query, data.query);
+ target.search = querystring_1.default.stringify(mergedQuery);
+ delete data.query;
+ const req = superagent_1.default.post(url_1.default.format(target)).send(data.body);
+ delete data.body;
+ Object.keys(data).forEach(key => {
+ req.set(key, data[key]);
+ });
+ req.end((err, res) => {
+ if (err) {
+ this.logger.error(err);
+ }
+ else {
+ this.logger.info(`${req.method} ${req.url} - ${res.status}`);
+ }
+ });
+ }
+ onopen() {
+ this.logger.info('Connected', this.events.url);
+ }
+ onerror(err) {
+ this.logger.error(err);
+ }
+ start() {
+ const events = new eventsource_1.default(this.source);
+ // Reconnect immediately
+ events.reconnectInterval = 0; // This isn't a valid property of EventSource
+ events.addEventListener('message', this.onmessage.bind(this));
+ events.addEventListener('open', this.onopen.bind(this));
+ events.addEventListener('error', this.onerror.bind(this));
+ this.logger.info(`Forwarding ${this.source} to ${this.target}`);
+ this.events = events;
+ return events;
+ }
+ }
+ smeeClient = Client;
+ return smeeClient;
+}
+
+Object.defineProperty(webhookProxy, "__esModule", { value: true });
+webhookProxy.createWebhookProxy = void 0;
+const createWebhookProxy = (opts) => {
+ try {
+ const SmeeClient = requireSmeeClient();
+ const smee = new SmeeClient({
+ logger: opts.logger,
+ source: opts.url,
+ target: `http://localhost:${opts.port}${opts.path}`,
+ });
+ return smee.start();
+ }
+ catch (error) {
+ opts.logger.warn("Run `npm install --save-dev smee-client` to proxy webhooks to localhost.");
+ return;
+ }
+};
+webhookProxy.createWebhookProxy = createWebhookProxy;
+
+var dist = {};
+
+var expressHandlebars = {};
+
+var handlebarsExports = {};
+var handlebars$1 = {
+ get exports(){ return handlebarsExports; },
+ set exports(v){ handlebarsExports = v; },
+};
+
+var handlebars_runtimeExports = {};
+var handlebars_runtime = {
+ get exports(){ return handlebars_runtimeExports; },
+ set exports(v){ handlebars_runtimeExports = v; },
+};
+
+var base$1 = {};
+
+var utils$1 = {};
+
+utils$1.__esModule = true;
+utils$1.extend = extend$1;
+utils$1.indexOf = indexOf;
+utils$1.escapeExpression = escapeExpression;
+utils$1.isEmpty = isEmpty;
+utils$1.createFrame = createFrame;
+utils$1.blockParams = blockParams;
+utils$1.appendContextPath = appendContextPath;
+var escape$1 = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": ''',
+ '`': '`',
+ '=': '='
+};
+
+var badChars = /[&<>"'`=]/g,
+ possible = /[&<>"'`=]/;
+
+function escapeChar(chr) {
+ return escape$1[chr];
+}
+
+function extend$1(obj /* , ...source */) {
+ for (var i = 1; i < arguments.length; i++) {
+ for (var key in arguments[i]) {
+ if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
+ obj[key] = arguments[i][key];
+ }
+ }
+ }
+
+ return obj;
+}
+
+var toString$2 = Object.prototype.toString;
+
+utils$1.toString = toString$2;
+// Sourced from lodash
+// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
+/* eslint-disable func-style */
+var isFunction$1 = function isFunction(value) {
+ return typeof value === 'function';
+};
+// fallback for older versions of Chrome and Safari
+/* istanbul ignore next */
+if (isFunction$1(/x/)) {
+ utils$1.isFunction = isFunction$1 = function (value) {
+ return typeof value === 'function' && toString$2.call(value) === '[object Function]';
+ };
+}
+utils$1.isFunction = isFunction$1;
+
+/* eslint-enable func-style */
+
+/* istanbul ignore next */
+var isArray = Array.isArray || function (value) {
+ return value && typeof value === 'object' ? toString$2.call(value) === '[object Array]' : false;
+};
+
+utils$1.isArray = isArray;
+// Older IE versions do not directly support indexOf so we must implement our own, sadly.
+
+function indexOf(array, value) {
+ for (var i = 0, len = array.length; i < len; i++) {
+ if (array[i] === value) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+function escapeExpression(string) {
+ if (typeof string !== 'string') {
+ // don't escape SafeStrings, since they're already safe
+ if (string && string.toHTML) {
+ return string.toHTML();
+ } else if (string == null) {
+ return '';
+ } else if (!string) {
+ return string + '';
+ }
+
+ // Force a string conversion as this will be done by the append regardless and
+ // the regex test will do this transparently behind the scenes, causing issues if
+ // an object's to string has escaped characters in it.
+ string = '' + string;
+ }
+
+ if (!possible.test(string)) {
+ return string;
+ }
+ return string.replace(badChars, escapeChar);
+}
+
+function isEmpty(value) {
+ if (!value && value !== 0) {
+ return true;
+ } else if (isArray(value) && value.length === 0) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+function createFrame(object) {
+ var frame = extend$1({}, object);
+ frame._parent = object;
+ return frame;
+}
+
+function blockParams(params, ids) {
+ params.path = ids;
+ return params;
+}
+
+function appendContextPath(contextPath, id) {
+ return (contextPath ? contextPath + '.' : '') + id;
+}
+
+var exceptionExports = {};
+var exception$1 = {
+ get exports(){ return exceptionExports; },
+ set exports(v){ exceptionExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ var errorProps = ['description', 'fileName', 'lineNumber', 'endLineNumber', 'message', 'name', 'number', 'stack'];
+
+ function Exception(message, node) {
+ var loc = node && node.loc,
+ line = undefined,
+ endLineNumber = undefined,
+ column = undefined,
+ endColumn = undefined;
+
+ if (loc) {
+ line = loc.start.line;
+ endLineNumber = loc.end.line;
+ column = loc.start.column;
+ endColumn = loc.end.column;
+
+ message += ' - ' + line + ':' + column;
+ }
+
+ var tmp = Error.prototype.constructor.call(this, message);
+
+ // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
+ for (var idx = 0; idx < errorProps.length; idx++) {
+ this[errorProps[idx]] = tmp[errorProps[idx]];
+ }
+
+ /* istanbul ignore else */
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, Exception);
+ }
+
+ try {
+ if (loc) {
+ this.lineNumber = line;
+ this.endLineNumber = endLineNumber;
+
+ // Work around issue under safari where we can't directly set the column value
+ /* istanbul ignore next */
+ if (Object.defineProperty) {
+ Object.defineProperty(this, 'column', {
+ value: column,
+ enumerable: true
+ });
+ Object.defineProperty(this, 'endColumn', {
+ value: endColumn,
+ enumerable: true
+ });
+ } else {
+ this.column = column;
+ this.endColumn = endColumn;
+ }
+ }
+ } catch (nop) {
+ /* Ignore if the browser is very particular */
+ }
+ }
+
+ Exception.prototype = new Error();
+
+ exports['default'] = Exception;
+ module.exports = exports['default'];
+
+} (exception$1, exceptionExports));
+
+var helpers$1 = {};
+
+var blockHelperMissingExports = {};
+var blockHelperMissing = {
+ get exports(){ return blockHelperMissingExports; },
+ set exports(v){ blockHelperMissingExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ var _utils = utils$1;
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('blockHelperMissing', function (context, options) {
+ var inverse = options.inverse,
+ fn = options.fn;
+
+ if (context === true) {
+ return fn(this);
+ } else if (context === false || context == null) {
+ return inverse(this);
+ } else if (_utils.isArray(context)) {
+ if (context.length > 0) {
+ if (options.ids) {
+ options.ids = [options.name];
+ }
+
+ return instance.helpers.each(context, options);
+ } else {
+ return inverse(this);
+ }
+ } else {
+ if (options.data && options.ids) {
+ var data = _utils.createFrame(options.data);
+ data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
+ options = { data: data };
+ }
+
+ return fn(context, options);
+ }
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (blockHelperMissing, blockHelperMissingExports));
+
+var eachExports = {};
+var each = {
+ get exports(){ return eachExports; },
+ set exports(v){ eachExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _utils = utils$1;
+
+ var _exception = exceptionExports;
+
+ var _exception2 = _interopRequireDefault(_exception);
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('each', function (context, options) {
+ if (!options) {
+ throw new _exception2['default']('Must pass iterator to #each');
+ }
+
+ var fn = options.fn,
+ inverse = options.inverse,
+ i = 0,
+ ret = '',
+ data = undefined,
+ contextPath = undefined;
+
+ if (options.data && options.ids) {
+ contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
+ }
+
+ if (_utils.isFunction(context)) {
+ context = context.call(this);
+ }
+
+ if (options.data) {
+ data = _utils.createFrame(options.data);
+ }
+
+ function execIteration(field, index, last) {
+ if (data) {
+ data.key = field;
+ data.index = index;
+ data.first = index === 0;
+ data.last = !!last;
+
+ if (contextPath) {
+ data.contextPath = contextPath + field;
+ }
+ }
+
+ ret = ret + fn(context[field], {
+ data: data,
+ blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
+ });
+ }
+
+ if (context && typeof context === 'object') {
+ if (_utils.isArray(context)) {
+ for (var j = context.length; i < j; i++) {
+ if (i in context) {
+ execIteration(i, i, i === context.length - 1);
+ }
+ }
+ } else if (commonjsGlobal.Symbol && context[commonjsGlobal.Symbol.iterator]) {
+ var newContext = [];
+ var iterator = context[commonjsGlobal.Symbol.iterator]();
+ for (var it = iterator.next(); !it.done; it = iterator.next()) {
+ newContext.push(it.value);
+ }
+ context = newContext;
+ for (var j = context.length; i < j; i++) {
+ execIteration(i, i, i === context.length - 1);
+ }
+ } else {
+ (function () {
+ var priorKey = undefined;
+
+ Object.keys(context).forEach(function (key) {
+ // We're running the iterations one step out of sync so we can detect
+ // the last iteration without have to scan the object twice and create
+ // an itermediate keys array.
+ if (priorKey !== undefined) {
+ execIteration(priorKey, i - 1);
+ }
+ priorKey = key;
+ i++;
+ });
+ if (priorKey !== undefined) {
+ execIteration(priorKey, i - 1, true);
+ }
+ })();
+ }
+ }
+
+ if (i === 0) {
+ ret = inverse(this);
+ }
+
+ return ret;
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (each, eachExports));
+
+var helperMissingExports = {};
+var helperMissing = {
+ get exports(){ return helperMissingExports; },
+ set exports(v){ helperMissingExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _exception = exceptionExports;
+
+ var _exception2 = _interopRequireDefault(_exception);
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('helperMissing', function () /* [args, ]options */{
+ if (arguments.length === 1) {
+ // A missing field in a {{foo}} construct.
+ return undefined;
+ } else {
+ // Someone is actually trying to call something, blow up.
+ throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
+ }
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (helperMissing, helperMissingExports));
+
+var _ifExports = {};
+var _if = {
+ get exports(){ return _ifExports; },
+ set exports(v){ _ifExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _utils = utils$1;
+
+ var _exception = exceptionExports;
+
+ var _exception2 = _interopRequireDefault(_exception);
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('if', function (conditional, options) {
+ if (arguments.length != 2) {
+ throw new _exception2['default']('#if requires exactly one argument');
+ }
+ if (_utils.isFunction(conditional)) {
+ conditional = conditional.call(this);
+ }
+
+ // Default behavior is to render the positive path if the value is truthy and not empty.
+ // The `includeZero` option may be set to treat the condtional as purely not empty based on the
+ // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
+ if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
+ return options.inverse(this);
+ } else {
+ return options.fn(this);
+ }
+ });
+
+ instance.registerHelper('unless', function (conditional, options) {
+ if (arguments.length != 2) {
+ throw new _exception2['default']('#unless requires exactly one argument');
+ }
+ return instance.helpers['if'].call(this, conditional, {
+ fn: options.inverse,
+ inverse: options.fn,
+ hash: options.hash
+ });
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (_if, _ifExports));
+
+var logExports = {};
+var log$1 = {
+ get exports(){ return logExports; },
+ set exports(v){ logExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('log', function () /* message, options */{
+ var args = [undefined],
+ options = arguments[arguments.length - 1];
+ for (var i = 0; i < arguments.length - 1; i++) {
+ args.push(arguments[i]);
+ }
+
+ var level = 1;
+ if (options.hash.level != null) {
+ level = options.hash.level;
+ } else if (options.data && options.data.level != null) {
+ level = options.data.level;
+ }
+ args[0] = level;
+
+ instance.log.apply(instance, args);
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (log$1, logExports));
+
+var lookupExports = {};
+var lookup = {
+ get exports(){ return lookupExports; },
+ set exports(v){ lookupExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('lookup', function (obj, field, options) {
+ if (!obj) {
+ // Note for 5.0: Change to "obj == null" in 5.0
+ return obj;
+ }
+ return options.lookupProperty(obj, field);
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (lookup, lookupExports));
+
+var _withExports = {};
+var _with = {
+ get exports(){ return _withExports; },
+ set exports(v){ _withExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _utils = utils$1;
+
+ var _exception = exceptionExports;
+
+ var _exception2 = _interopRequireDefault(_exception);
+
+ exports['default'] = function (instance) {
+ instance.registerHelper('with', function (context, options) {
+ if (arguments.length != 2) {
+ throw new _exception2['default']('#with requires exactly one argument');
+ }
+ if (_utils.isFunction(context)) {
+ context = context.call(this);
+ }
+
+ var fn = options.fn;
+
+ if (!_utils.isEmpty(context)) {
+ var data = options.data;
+ if (options.data && options.ids) {
+ data = _utils.createFrame(options.data);
+ data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
+ }
+
+ return fn(context, {
+ data: data,
+ blockParams: _utils.blockParams([context], [data && data.contextPath])
+ });
+ } else {
+ return options.inverse(this);
+ }
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (_with, _withExports));
+
+helpers$1.__esModule = true;
+helpers$1.registerDefaultHelpers = registerDefaultHelpers;
+helpers$1.moveHelperToHooks = moveHelperToHooks;
+// istanbul ignore next
+
+function _interopRequireDefault$7(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _helpersBlockHelperMissing = blockHelperMissingExports;
+
+var _helpersBlockHelperMissing2 = _interopRequireDefault$7(_helpersBlockHelperMissing);
+
+var _helpersEach = eachExports;
+
+var _helpersEach2 = _interopRequireDefault$7(_helpersEach);
+
+var _helpersHelperMissing = helperMissingExports;
+
+var _helpersHelperMissing2 = _interopRequireDefault$7(_helpersHelperMissing);
+
+var _helpersIf = _ifExports;
+
+var _helpersIf2 = _interopRequireDefault$7(_helpersIf);
+
+var _helpersLog = logExports;
+
+var _helpersLog2 = _interopRequireDefault$7(_helpersLog);
+
+var _helpersLookup = lookupExports;
+
+var _helpersLookup2 = _interopRequireDefault$7(_helpersLookup);
+
+var _helpersWith = _withExports;
+
+var _helpersWith2 = _interopRequireDefault$7(_helpersWith);
+
+function registerDefaultHelpers(instance) {
+ _helpersBlockHelperMissing2['default'](instance);
+ _helpersEach2['default'](instance);
+ _helpersHelperMissing2['default'](instance);
+ _helpersIf2['default'](instance);
+ _helpersLog2['default'](instance);
+ _helpersLookup2['default'](instance);
+ _helpersWith2['default'](instance);
+}
+
+function moveHelperToHooks(instance, helperName, keepHelper) {
+ if (instance.helpers[helperName]) {
+ instance.hooks[helperName] = instance.helpers[helperName];
+ if (!keepHelper) {
+ delete instance.helpers[helperName];
+ }
+ }
+}
+
+var decorators = {};
+
+var inlineExports = {};
+var inline = {
+ get exports(){ return inlineExports; },
+ set exports(v){ inlineExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ var _utils = utils$1;
+
+ exports['default'] = function (instance) {
+ instance.registerDecorator('inline', function (fn, props, container, options) {
+ var ret = fn;
+ if (!props.partials) {
+ props.partials = {};
+ ret = function (context, options) {
+ // Create a new partials stack frame prior to exec.
+ var original = container.partials;
+ container.partials = _utils.extend({}, original, props.partials);
+ var ret = fn(context, options);
+ container.partials = original;
+ return ret;
+ };
+ }
+
+ props.partials[options.args[0]] = options.fn;
+
+ return ret;
+ });
+ };
+
+ module.exports = exports['default'];
+
+} (inline, inlineExports));
+
+decorators.__esModule = true;
+decorators.registerDefaultDecorators = registerDefaultDecorators;
+// istanbul ignore next
+
+function _interopRequireDefault$6(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _decoratorsInline = inlineExports;
+
+var _decoratorsInline2 = _interopRequireDefault$6(_decoratorsInline);
+
+function registerDefaultDecorators(instance) {
+ _decoratorsInline2['default'](instance);
+}
+
+var loggerExports = {};
+var logger$1 = {
+ get exports(){ return loggerExports; },
+ set exports(v){ loggerExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ var _utils = utils$1;
+
+ var logger = {
+ methodMap: ['debug', 'info', 'warn', 'error'],
+ level: 'info',
+
+ // Maps a given level value to the `methodMap` indexes above.
+ lookupLevel: function lookupLevel(level) {
+ if (typeof level === 'string') {
+ var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
+ if (levelMap >= 0) {
+ level = levelMap;
+ } else {
+ level = parseInt(level, 10);
+ }
+ }
+
+ return level;
+ },
+
+ // Can be overridden in the host environment
+ log: function log(level) {
+ level = logger.lookupLevel(level);
+
+ if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
+ var method = logger.methodMap[level];
+ // eslint-disable-next-line no-console
+ if (!console[method]) {
+ method = 'log';
+ }
+
+ for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ message[_key - 1] = arguments[_key];
+ }
+
+ console[method].apply(console, message); // eslint-disable-line no-console
+ }
+ }
+ };
+
+ exports['default'] = logger;
+ module.exports = exports['default'];
+
+} (logger$1, loggerExports));
+
+var protoAccess = {};
+
+var createNewLookupObject$1 = {};
+
+createNewLookupObject$1.__esModule = true;
+createNewLookupObject$1.createNewLookupObject = createNewLookupObject;
+
+var _utils$4 = utils$1;
+
+/**
+ * Create a new object with "null"-prototype to avoid truthy results on prototype properties.
+ * The resulting object can be used with "object[property]" to check if a property exists
+ * @param {...object} sources a varargs parameter of source objects that will be merged
+ * @returns {object}
+ */
+
+function createNewLookupObject() {
+ for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) {
+ sources[_key] = arguments[_key];
+ }
+
+ return _utils$4.extend.apply(undefined, [Object.create(null)].concat(sources));
+}
+
+protoAccess.__esModule = true;
+protoAccess.createProtoAccessControl = createProtoAccessControl;
+protoAccess.resultIsAllowed = resultIsAllowed;
+protoAccess.resetLoggedProperties = resetLoggedProperties;
+// istanbul ignore next
+
+function _interopRequireWildcard$2(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
+
+var _createNewLookupObject = createNewLookupObject$1;
+
+var _logger$1 = loggerExports;
+
+var logger = _interopRequireWildcard$2(_logger$1);
+
+var loggedProperties = Object.create(null);
+
+function createProtoAccessControl(runtimeOptions) {
+ var defaultMethodWhiteList = Object.create(null);
+ defaultMethodWhiteList['constructor'] = false;
+ defaultMethodWhiteList['__defineGetter__'] = false;
+ defaultMethodWhiteList['__defineSetter__'] = false;
+ defaultMethodWhiteList['__lookupGetter__'] = false;
+
+ var defaultPropertyWhiteList = Object.create(null);
+ // eslint-disable-next-line no-proto
+ defaultPropertyWhiteList['__proto__'] = false;
+
+ return {
+ properties: {
+ whitelist: _createNewLookupObject.createNewLookupObject(defaultPropertyWhiteList, runtimeOptions.allowedProtoProperties),
+ defaultValue: runtimeOptions.allowProtoPropertiesByDefault
+ },
+ methods: {
+ whitelist: _createNewLookupObject.createNewLookupObject(defaultMethodWhiteList, runtimeOptions.allowedProtoMethods),
+ defaultValue: runtimeOptions.allowProtoMethodsByDefault
+ }
+ };
+}
+
+function resultIsAllowed(result, protoAccessControl, propertyName) {
+ if (typeof result === 'function') {
+ return checkWhiteList(protoAccessControl.methods, propertyName);
+ } else {
+ return checkWhiteList(protoAccessControl.properties, propertyName);
+ }
+}
+
+function checkWhiteList(protoAccessControlForType, propertyName) {
+ if (protoAccessControlForType.whitelist[propertyName] !== undefined) {
+ return protoAccessControlForType.whitelist[propertyName] === true;
+ }
+ if (protoAccessControlForType.defaultValue !== undefined) {
+ return protoAccessControlForType.defaultValue;
+ }
+ logUnexpecedPropertyAccessOnce(propertyName);
+ return false;
+}
+
+function logUnexpecedPropertyAccessOnce(propertyName) {
+ if (loggedProperties[propertyName] !== true) {
+ loggedProperties[propertyName] = true;
+ logger.log('error', 'Handlebars: Access has been denied to resolve the property "' + propertyName + '" because it is not an "own property" of its parent.\n' + 'You can add a runtime option to disable the check or this warning:\n' + 'See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details');
+ }
+}
+
+function resetLoggedProperties() {
+ Object.keys(loggedProperties).forEach(function (propertyName) {
+ delete loggedProperties[propertyName];
+ });
+}
+
+base$1.__esModule = true;
+base$1.HandlebarsEnvironment = HandlebarsEnvironment;
+// istanbul ignore next
+
+function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _utils$3 = utils$1;
+
+var _exception$3 = exceptionExports;
+
+var _exception2$3 = _interopRequireDefault$5(_exception$3);
+
+var _helpers$2 = helpers$1;
+
+var _decorators = decorators;
+
+var _logger = loggerExports;
+
+var _logger2 = _interopRequireDefault$5(_logger);
+
+var _internalProtoAccess$1 = protoAccess;
+
+var VERSION$1 = '4.7.7';
+base$1.VERSION = VERSION$1;
+var COMPILER_REVISION = 8;
+base$1.COMPILER_REVISION = COMPILER_REVISION;
+var LAST_COMPATIBLE_COMPILER_REVISION = 7;
+
+base$1.LAST_COMPATIBLE_COMPILER_REVISION = LAST_COMPATIBLE_COMPILER_REVISION;
+var REVISION_CHANGES = {
+ 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
+ 2: '== 1.0.0-rc.3',
+ 3: '== 1.0.0-rc.4',
+ 4: '== 1.x.x',
+ 5: '== 2.0.0-alpha.x',
+ 6: '>= 2.0.0-beta.1',
+ 7: '>= 4.0.0 <4.3.0',
+ 8: '>= 4.3.0'
+};
+
+base$1.REVISION_CHANGES = REVISION_CHANGES;
+var objectType = '[object Object]';
+
+function HandlebarsEnvironment(helpers, partials, decorators) {
+ this.helpers = helpers || {};
+ this.partials = partials || {};
+ this.decorators = decorators || {};
+
+ _helpers$2.registerDefaultHelpers(this);
+ _decorators.registerDefaultDecorators(this);
+}
+
+HandlebarsEnvironment.prototype = {
+ constructor: HandlebarsEnvironment,
+
+ logger: _logger2['default'],
+ log: _logger2['default'].log,
+
+ registerHelper: function registerHelper(name, fn) {
+ if (_utils$3.toString.call(name) === objectType) {
+ if (fn) {
+ throw new _exception2$3['default']('Arg not supported with multiple helpers');
+ }
+ _utils$3.extend(this.helpers, name);
+ } else {
+ this.helpers[name] = fn;
+ }
+ },
+ unregisterHelper: function unregisterHelper(name) {
+ delete this.helpers[name];
+ },
+
+ registerPartial: function registerPartial(name, partial) {
+ if (_utils$3.toString.call(name) === objectType) {
+ _utils$3.extend(this.partials, name);
+ } else {
+ if (typeof partial === 'undefined') {
+ throw new _exception2$3['default']('Attempting to register a partial called "' + name + '" as undefined');
+ }
+ this.partials[name] = partial;
+ }
+ },
+ unregisterPartial: function unregisterPartial(name) {
+ delete this.partials[name];
+ },
+
+ registerDecorator: function registerDecorator(name, fn) {
+ if (_utils$3.toString.call(name) === objectType) {
+ if (fn) {
+ throw new _exception2$3['default']('Arg not supported with multiple decorators');
+ }
+ _utils$3.extend(this.decorators, name);
+ } else {
+ this.decorators[name] = fn;
+ }
+ },
+ unregisterDecorator: function unregisterDecorator(name) {
+ delete this.decorators[name];
+ },
+ /**
+ * Reset the memory of illegal property accesses that have already been logged.
+ * @deprecated should only be used in handlebars test-cases
+ */
+ resetLoggedPropertyAccesses: function resetLoggedPropertyAccesses() {
+ _internalProtoAccess$1.resetLoggedProperties();
+ }
+};
+
+var log = _logger2['default'].log;
+
+base$1.log = log;
+base$1.createFrame = _utils$3.createFrame;
+base$1.logger = _logger2['default'];
+
+var safeStringExports = {};
+var safeString = {
+ get exports(){ return safeStringExports; },
+ set exports(v){ safeStringExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ function SafeString(string) {
+ this.string = string;
+ }
+
+ SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
+ return '' + this.string;
+ };
+
+ exports['default'] = SafeString;
+ module.exports = exports['default'];
+
+} (safeString, safeStringExports));
+
+var runtime = {};
+
+var wrapHelper$1 = {};
+
+wrapHelper$1.__esModule = true;
+wrapHelper$1.wrapHelper = wrapHelper;
+
+function wrapHelper(helper, transformOptionsFn) {
+ if (typeof helper !== 'function') {
+ // This should not happen, but apparently it does in https://github.com/wycats/handlebars.js/issues/1639
+ // We try to make the wrapper least-invasive by not wrapping it, if the helper is not a function.
+ return helper;
+ }
+ var wrapper = function wrapper() /* dynamic arguments */{
+ var options = arguments[arguments.length - 1];
+ arguments[arguments.length - 1] = transformOptionsFn(options);
+ return helper.apply(this, arguments);
+ };
+ return wrapper;
+}
+
+runtime.__esModule = true;
+runtime.checkRevision = checkRevision;
+runtime.template = template;
+runtime.wrapProgram = wrapProgram;
+runtime.resolvePartial = resolvePartial;
+runtime.invokePartial = invokePartial;
+runtime.noop = noop$5;
+// istanbul ignore next
+
+function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+// istanbul ignore next
+
+function _interopRequireWildcard$1(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
+
+var _utils$2 = utils$1;
+
+var Utils = _interopRequireWildcard$1(_utils$2);
+
+var _exception$2 = exceptionExports;
+
+var _exception2$2 = _interopRequireDefault$4(_exception$2);
+
+var _base = base$1;
+
+var _helpers$1 = helpers$1;
+
+var _internalWrapHelper = wrapHelper$1;
+
+var _internalProtoAccess = protoAccess;
+
+function checkRevision(compilerInfo) {
+ var compilerRevision = compilerInfo && compilerInfo[0] || 1,
+ currentRevision = _base.COMPILER_REVISION;
+
+ if (compilerRevision >= _base.LAST_COMPATIBLE_COMPILER_REVISION && compilerRevision <= _base.COMPILER_REVISION) {
+ return;
+ }
+
+ if (compilerRevision < _base.LAST_COMPATIBLE_COMPILER_REVISION) {
+ var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
+ compilerVersions = _base.REVISION_CHANGES[compilerRevision];
+ throw new _exception2$2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
+ } else {
+ // Use the embedded version info since the runtime doesn't know about this revision yet
+ throw new _exception2$2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
+ }
+}
+
+function template(templateSpec, env) {
+ /* istanbul ignore next */
+ if (!env) {
+ throw new _exception2$2['default']('No environment passed to template');
+ }
+ if (!templateSpec || !templateSpec.main) {
+ throw new _exception2$2['default']('Unknown template object: ' + typeof templateSpec);
+ }
+
+ templateSpec.main.decorator = templateSpec.main_d;
+
+ // Note: Using env.VM references rather than local var references throughout this section to allow
+ // for external users to override these as pseudo-supported APIs.
+ env.VM.checkRevision(templateSpec.compiler);
+
+ // backwards compatibility for precompiled templates with compiler-version 7 (<4.3.0)
+ var templateWasPrecompiledWithCompilerV7 = templateSpec.compiler && templateSpec.compiler[0] === 7;
+
+ function invokePartialWrapper(partial, context, options) {
+ if (options.hash) {
+ context = Utils.extend({}, context, options.hash);
+ if (options.ids) {
+ options.ids[0] = true;
+ }
+ }
+ partial = env.VM.resolvePartial.call(this, partial, context, options);
+
+ var extendedOptions = Utils.extend({}, options, {
+ hooks: this.hooks,
+ protoAccessControl: this.protoAccessControl
+ });
+
+ var result = env.VM.invokePartial.call(this, partial, context, extendedOptions);
+
+ if (result == null && env.compile) {
+ options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
+ result = options.partials[options.name](context, extendedOptions);
+ }
+ if (result != null) {
+ if (options.indent) {
+ var lines = result.split('\n');
+ for (var i = 0, l = lines.length; i < l; i++) {
+ if (!lines[i] && i + 1 === l) {
+ break;
+ }
+
+ lines[i] = options.indent + lines[i];
+ }
+ result = lines.join('\n');
+ }
+ return result;
+ } else {
+ throw new _exception2$2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
+ }
+ }
+
+ // Just add water
+ var container = {
+ strict: function strict(obj, name, loc) {
+ if (!obj || !(name in obj)) {
+ throw new _exception2$2['default']('"' + name + '" not defined in ' + obj, {
+ loc: loc
+ });
+ }
+ return container.lookupProperty(obj, name);
+ },
+ lookupProperty: function lookupProperty(parent, propertyName) {
+ var result = parent[propertyName];
+ if (result == null) {
+ return result;
+ }
+ if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
+ return result;
+ }
+
+ if (_internalProtoAccess.resultIsAllowed(result, container.protoAccessControl, propertyName)) {
+ return result;
+ }
+ return undefined;
+ },
+ lookup: function lookup(depths, name) {
+ var len = depths.length;
+ for (var i = 0; i < len; i++) {
+ var result = depths[i] && container.lookupProperty(depths[i], name);
+ if (result != null) {
+ return depths[i][name];
+ }
+ }
+ },
+ lambda: function lambda(current, context) {
+ return typeof current === 'function' ? current.call(context) : current;
+ },
+
+ escapeExpression: Utils.escapeExpression,
+ invokePartial: invokePartialWrapper,
+
+ fn: function fn(i) {
+ var ret = templateSpec[i];
+ ret.decorator = templateSpec[i + '_d'];
+ return ret;
+ },
+
+ programs: [],
+ program: function program(i, data, declaredBlockParams, blockParams, depths) {
+ var programWrapper = this.programs[i],
+ fn = this.fn(i);
+ if (data || depths || blockParams || declaredBlockParams) {
+ programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
+ } else if (!programWrapper) {
+ programWrapper = this.programs[i] = wrapProgram(this, i, fn);
+ }
+ return programWrapper;
+ },
+
+ data: function data(value, depth) {
+ while (value && depth--) {
+ value = value._parent;
+ }
+ return value;
+ },
+ mergeIfNeeded: function mergeIfNeeded(param, common) {
+ var obj = param || common;
+
+ if (param && common && param !== common) {
+ obj = Utils.extend({}, common, param);
+ }
+
+ return obj;
+ },
+ // An empty object to use as replacement for null-contexts
+ nullContext: Object.seal({}),
+
+ noop: env.VM.noop,
+ compilerInfo: templateSpec.compiler
+ };
+
+ function ret(context) {
+ var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
+
+ var data = options.data;
+
+ ret._setup(options);
+ if (!options.partial && templateSpec.useData) {
+ data = initData(context, data);
+ }
+ var depths = undefined,
+ blockParams = templateSpec.useBlockParams ? [] : undefined;
+ if (templateSpec.useDepths) {
+ if (options.depths) {
+ depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
+ } else {
+ depths = [context];
+ }
+ }
+
+ function main(context /*, options*/) {
+ return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
+ }
+
+ main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
+ return main(context, options);
+ }
+
+ ret.isTop = true;
+
+ ret._setup = function (options) {
+ if (!options.partial) {
+ var mergedHelpers = Utils.extend({}, env.helpers, options.helpers);
+ wrapHelpersToPassLookupProperty(mergedHelpers, container);
+ container.helpers = mergedHelpers;
+
+ if (templateSpec.usePartial) {
+ // Use mergeIfNeeded here to prevent compiling global partials multiple times
+ container.partials = container.mergeIfNeeded(options.partials, env.partials);
+ }
+ if (templateSpec.usePartial || templateSpec.useDecorators) {
+ container.decorators = Utils.extend({}, env.decorators, options.decorators);
+ }
+
+ container.hooks = {};
+ container.protoAccessControl = _internalProtoAccess.createProtoAccessControl(options);
+
+ var keepHelperInHelpers = options.allowCallsToHelperMissing || templateWasPrecompiledWithCompilerV7;
+ _helpers$1.moveHelperToHooks(container, 'helperMissing', keepHelperInHelpers);
+ _helpers$1.moveHelperToHooks(container, 'blockHelperMissing', keepHelperInHelpers);
+ } else {
+ container.protoAccessControl = options.protoAccessControl; // internal option
+ container.helpers = options.helpers;
+ container.partials = options.partials;
+ container.decorators = options.decorators;
+ container.hooks = options.hooks;
+ }
+ };
+
+ ret._child = function (i, data, blockParams, depths) {
+ if (templateSpec.useBlockParams && !blockParams) {
+ throw new _exception2$2['default']('must pass block params');
+ }
+ if (templateSpec.useDepths && !depths) {
+ throw new _exception2$2['default']('must pass parent depths');
+ }
+
+ return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
+ };
+ return ret;
+}
+
+function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
+ function prog(context) {
+ var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
+
+ var currentDepths = depths;
+ if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
+ currentDepths = [context].concat(depths);
+ }
+
+ return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
+ }
+
+ prog = executeDecorators(fn, prog, container, depths, data, blockParams);
+
+ prog.program = i;
+ prog.depth = depths ? depths.length : 0;
+ prog.blockParams = declaredBlockParams || 0;
+ return prog;
+}
+
+/**
+ * This is currently part of the official API, therefore implementation details should not be changed.
+ */
+
+function resolvePartial(partial, context, options) {
+ if (!partial) {
+ if (options.name === '@partial-block') {
+ partial = options.data['partial-block'];
+ } else {
+ partial = options.partials[options.name];
+ }
+ } else if (!partial.call && !options.name) {
+ // This is a dynamic partial that returned a string
+ options.name = partial;
+ partial = options.partials[partial];
+ }
+ return partial;
+}
+
+function invokePartial(partial, context, options) {
+ // Use the current closure context to save the partial-block if this partial
+ var currentPartialBlock = options.data && options.data['partial-block'];
+ options.partial = true;
+ if (options.ids) {
+ options.data.contextPath = options.ids[0] || options.data.contextPath;
+ }
+
+ var partialBlock = undefined;
+ if (options.fn && options.fn !== noop$5) {
+ (function () {
+ options.data = _base.createFrame(options.data);
+ // Wrapper function to get access to currentPartialBlock from the closure
+ var fn = options.fn;
+ partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
+ var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
+
+ // Restore the partial-block from the closure for the execution of the block
+ // i.e. the part inside the block of the partial call.
+ options.data = _base.createFrame(options.data);
+ options.data['partial-block'] = currentPartialBlock;
+ return fn(context, options);
+ };
+ if (fn.partials) {
+ options.partials = Utils.extend({}, options.partials, fn.partials);
+ }
+ })();
+ }
+
+ if (partial === undefined && partialBlock) {
+ partial = partialBlock;
+ }
+
+ if (partial === undefined) {
+ throw new _exception2$2['default']('The partial ' + options.name + ' could not be found');
+ } else if (partial instanceof Function) {
+ return partial(context, options);
+ }
+}
+
+function noop$5() {
+ return '';
+}
+
+function initData(context, data) {
+ if (!data || !('root' in data)) {
+ data = data ? _base.createFrame(data) : {};
+ data.root = context;
+ }
+ return data;
+}
+
+function executeDecorators(fn, prog, container, depths, data, blockParams) {
+ if (fn.decorator) {
+ var props = {};
+ prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
+ Utils.extend(prog, props);
+ }
+ return prog;
+}
+
+function wrapHelpersToPassLookupProperty(mergedHelpers, container) {
+ Object.keys(mergedHelpers).forEach(function (helperName) {
+ var helper = mergedHelpers[helperName];
+ mergedHelpers[helperName] = passLookupPropertyOption(helper, container);
+ });
+}
+
+function passLookupPropertyOption(helper, container) {
+ var lookupProperty = container.lookupProperty;
+ return _internalWrapHelper.wrapHelper(helper, function (options) {
+ return Utils.extend({ lookupProperty: lookupProperty }, options);
+ });
+}
+
+var noConflictExports = {};
+var noConflict = {
+ get exports(){ return noConflictExports; },
+ set exports(v){ noConflictExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ exports['default'] = function (Handlebars) {
+ /* istanbul ignore next */
+ var root = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : window,
+ $Handlebars = root.Handlebars;
+ /* istanbul ignore next */
+ Handlebars.noConflict = function () {
+ if (root.Handlebars === Handlebars) {
+ root.Handlebars = $Handlebars;
+ }
+ return Handlebars;
+ };
+ };
+
+ module.exports = exports['default'];
+
+} (noConflict, noConflictExports));
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ // istanbul ignore next
+
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
+
+ var _handlebarsBase = base$1;
+
+ var base = _interopRequireWildcard(_handlebarsBase);
+
+ // Each of these augment the Handlebars object. No need to setup here.
+ // (This is done to easily share code between commonjs and browse envs)
+
+ var _handlebarsSafeString = safeStringExports;
+
+ var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
+
+ var _handlebarsException = exceptionExports;
+
+ var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
+
+ var _handlebarsUtils = utils$1;
+
+ var Utils = _interopRequireWildcard(_handlebarsUtils);
+
+ var _handlebarsRuntime = runtime;
+
+ var runtime$1 = _interopRequireWildcard(_handlebarsRuntime);
+
+ var _handlebarsNoConflict = noConflictExports;
+
+ var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
+
+ // For compatibility and usage outside of module systems, make the Handlebars object a namespace
+ function create() {
+ var hb = new base.HandlebarsEnvironment();
+
+ Utils.extend(hb, base);
+ hb.SafeString = _handlebarsSafeString2['default'];
+ hb.Exception = _handlebarsException2['default'];
+ hb.Utils = Utils;
+ hb.escapeExpression = Utils.escapeExpression;
+
+ hb.VM = runtime$1;
+ hb.template = function (spec) {
+ return runtime$1.template(spec, hb);
+ };
+
+ return hb;
+ }
+
+ var inst = create();
+ inst.create = create;
+
+ _handlebarsNoConflict2['default'](inst);
+
+ inst['default'] = inst;
+
+ exports['default'] = inst;
+ module.exports = exports['default'];
+
+} (handlebars_runtime, handlebars_runtimeExports));
+
+var astExports = {};
+var ast = {
+ get exports(){ return astExports; },
+ set exports(v){ astExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ var AST = {
+ // Public API used to evaluate derived attributes regarding AST nodes
+ helpers: {
+ // a mustache is definitely a helper if:
+ // * it is an eligible helper, and
+ // * it has at least one parameter or hash segment
+ helperExpression: function helperExpression(node) {
+ return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
+ },
+
+ scopedId: function scopedId(path) {
+ return (/^\.|this\b/.test(path.original)
+ );
+ },
+
+ // an ID is simple if it only has one part, and that part is not
+ // `..` or `this`.
+ simpleId: function simpleId(path) {
+ return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
+ }
+ }
+ };
+
+ // Must be exported as an object rather than the root of the module as the jison lexer
+ // must modify the object to operate properly.
+ exports['default'] = AST;
+ module.exports = exports['default'];
+
+} (ast, astExports));
+
+var base = {};
+
+var parserExports = {};
+var parser = {
+ get exports(){ return parserExports; },
+ set exports(v){ parserExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ var handlebars = (function () {
+ var parser = { trace: function trace() {},
+ yy: {},
+ symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 },
+ terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" },
+ productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 0], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]],
+ performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
+
+ var $0 = $$.length - 1;
+ switch (yystate) {
+ case 1:
+ return $$[$0 - 1];
+ case 2:
+ this.$ = yy.prepareProgram($$[$0]);
+ break;
+ case 3:
+ this.$ = $$[$0];
+ break;
+ case 4:
+ this.$ = $$[$0];
+ break;
+ case 5:
+ this.$ = $$[$0];
+ break;
+ case 6:
+ this.$ = $$[$0];
+ break;
+ case 7:
+ this.$ = $$[$0];
+ break;
+ case 8:
+ this.$ = $$[$0];
+ break;
+ case 9:
+ this.$ = {
+ type: 'CommentStatement',
+ value: yy.stripComment($$[$0]),
+ strip: yy.stripFlags($$[$0], $$[$0]),
+ loc: yy.locInfo(this._$)
+ };
+
+ break;
+ case 10:
+ this.$ = {
+ type: 'ContentStatement',
+ original: $$[$0],
+ value: $$[$0],
+ loc: yy.locInfo(this._$)
+ };
+
+ break;
+ case 11:
+ this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
+ break;
+ case 12:
+ this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
+ break;
+ case 13:
+ this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
+ break;
+ case 14:
+ this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
+ break;
+ case 15:
+ this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
+ break;
+ case 16:
+ this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
+ break;
+ case 17:
+ this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
+ break;
+ case 18:
+ this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
+ break;
+ case 19:
+ var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
+ program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
+ program.chained = true;
+
+ this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
+
+ break;
+ case 20:
+ this.$ = $$[$0];
+ break;
+ case 21:
+ this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
+ break;
+ case 22:
+ this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
+ break;
+ case 23:
+ this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
+ break;
+ case 24:
+ this.$ = {
+ type: 'PartialStatement',
+ name: $$[$0 - 3],
+ params: $$[$0 - 2],
+ hash: $$[$0 - 1],
+ indent: '',
+ strip: yy.stripFlags($$[$0 - 4], $$[$0]),
+ loc: yy.locInfo(this._$)
+ };
+
+ break;
+ case 25:
+ this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
+ break;
+ case 26:
+ this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
+ break;
+ case 27:
+ this.$ = $$[$0];
+ break;
+ case 28:
+ this.$ = $$[$0];
+ break;
+ case 29:
+ this.$ = {
+ type: 'SubExpression',
+ path: $$[$0 - 3],
+ params: $$[$0 - 2],
+ hash: $$[$0 - 1],
+ loc: yy.locInfo(this._$)
+ };
+
+ break;
+ case 30:
+ this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
+ break;
+ case 31:
+ this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
+ break;
+ case 32:
+ this.$ = yy.id($$[$0 - 1]);
+ break;
+ case 33:
+ this.$ = $$[$0];
+ break;
+ case 34:
+ this.$ = $$[$0];
+ break;
+ case 35:
+ this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
+ break;
+ case 36:
+ this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
+ break;
+ case 37:
+ this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
+ break;
+ case 38:
+ this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
+ break;
+ case 39:
+ this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
+ break;
+ case 40:
+ this.$ = $$[$0];
+ break;
+ case 41:
+ this.$ = $$[$0];
+ break;
+ case 42:
+ this.$ = yy.preparePath(true, $$[$0], this._$);
+ break;
+ case 43:
+ this.$ = yy.preparePath(false, $$[$0], this._$);
+ break;
+ case 44:
+ $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
+ break;
+ case 45:
+ this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
+ break;
+ case 46:
+ this.$ = [];
+ break;
+ case 47:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 48:
+ this.$ = [];
+ break;
+ case 49:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 50:
+ this.$ = [];
+ break;
+ case 51:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 58:
+ this.$ = [];
+ break;
+ case 59:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 64:
+ this.$ = [];
+ break;
+ case 65:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 70:
+ this.$ = [];
+ break;
+ case 71:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 78:
+ this.$ = [];
+ break;
+ case 79:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 82:
+ this.$ = [];
+ break;
+ case 83:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 86:
+ this.$ = [];
+ break;
+ case 87:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 90:
+ this.$ = [];
+ break;
+ case 91:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 94:
+ this.$ = [];
+ break;
+ case 95:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 98:
+ this.$ = [$$[$0]];
+ break;
+ case 99:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ case 100:
+ this.$ = [$$[$0]];
+ break;
+ case 101:
+ $$[$0 - 1].push($$[$0]);
+ break;
+ }
+ },
+ table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 15: [2, 48], 17: 39, 18: [2, 48] }, { 20: 41, 56: 40, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 44, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 45, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 41, 56: 48, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 49, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 50] }, { 72: [1, 35], 86: 51 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 52, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 53, 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 54, 47: [2, 54] }, { 28: 59, 43: 60, 44: [1, 58], 47: [2, 56] }, { 13: 62, 15: [1, 20], 18: [1, 61] }, { 33: [2, 86], 57: 63, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 64, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 65, 47: [1, 66] }, { 30: 67, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 68, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 69, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 70, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 74, 33: [2, 80], 50: 71, 63: 72, 64: 75, 65: [1, 43], 69: 73, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 79] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 50] }, { 20: 74, 53: 80, 54: [2, 84], 63: 81, 64: 75, 65: [1, 43], 69: 82, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 83, 47: [1, 66] }, { 47: [2, 55] }, { 4: 84, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 85, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 86, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 87, 47: [1, 66] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 74, 33: [2, 88], 58: 88, 63: 89, 64: 75, 65: [1, 43], 69: 90, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 91, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 92, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 31: 93, 33: [2, 60], 63: 94, 64: 75, 65: [1, 43], 69: 95, 70: 76, 71: 77, 72: [1, 78], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 66], 36: 96, 63: 97, 64: 75, 65: [1, 43], 69: 98, 70: 76, 71: 77, 72: [1, 78], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 22: 99, 23: [2, 52], 63: 100, 64: 75, 65: [1, 43], 69: 101, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 92], 62: 102, 63: 103, 64: 75, 65: [1, 43], 69: 104, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 105] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 106, 72: [1, 107], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 108], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 109] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 111, 46: 110, 47: [2, 76] }, { 33: [2, 70], 40: 112, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 113] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 74, 63: 115, 64: 75, 65: [1, 43], 67: 114, 68: [2, 96], 69: 116, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 117] }, { 32: 118, 33: [2, 62], 74: 119, 75: [1, 120] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 121, 74: 122, 75: [1, 120] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 123] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 124] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 108] }, { 20: 74, 63: 125, 64: 75, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 74, 33: [2, 72], 41: 126, 63: 127, 64: 75, 65: [1, 43], 69: 128, 70: 76, 71: 77, 72: [1, 78], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 129] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 130] }, { 33: [2, 63] }, { 72: [1, 132], 76: 131 }, { 33: [1, 133] }, { 33: [2, 69] }, { 15: [2, 12], 18: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 134, 74: 135, 75: [1, 120] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 137], 77: [1, 136] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 138] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }],
+ defaultActions: { 4: [2, 1], 54: [2, 55], 56: [2, 20], 60: [2, 57], 73: [2, 81], 82: [2, 85], 86: [2, 18], 90: [2, 89], 101: [2, 53], 104: [2, 93], 110: [2, 19], 111: [2, 77], 116: [2, 97], 119: [2, 63], 122: [2, 69], 135: [2, 75], 136: [2, 32] },
+ parseError: function parseError(str, hash) {
+ throw new Error(str);
+ },
+ parse: function parse(input) {
+ var self = this,
+ stack = [0],
+ vstack = [null],
+ lstack = [],
+ table = this.table,
+ yytext = "",
+ yylineno = 0,
+ yyleng = 0;
+ this.lexer.setInput(input);
+ this.lexer.yy = this.yy;
+ this.yy.lexer = this.lexer;
+ this.yy.parser = this;
+ if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
+ var yyloc = this.lexer.yylloc;
+ lstack.push(yyloc);
+ var ranges = this.lexer.options && this.lexer.options.ranges;
+ if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
+ function lex() {
+ var token;
+ token = self.lexer.lex() || 1;
+ if (typeof token !== "number") {
+ token = self.symbols_[token] || token;
+ }
+ return token;
+ }
+ var symbol,
+ state,
+ action,
+ r,
+ yyval = {},
+ p,
+ len,
+ newState,
+ expected;
+ while (true) {
+ state = stack[stack.length - 1];
+ if (this.defaultActions[state]) {
+ action = this.defaultActions[state];
+ } else {
+ if (symbol === null || typeof symbol == "undefined") {
+ symbol = lex();
+ }
+ action = table[state] && table[state][symbol];
+ }
+ if (typeof action === "undefined" || !action.length || !action[0]) {
+ var errStr = "";
+ {
+ expected = [];
+ for (p in table[state]) if (this.terminals_[p] && p > 2) {
+ expected.push("'" + this.terminals_[p] + "'");
+ }
+ if (this.lexer.showPosition) {
+ errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
+ } else {
+ errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
+ }
+ this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
+ }
+ }
+ if (action[0] instanceof Array && action.length > 1) {
+ throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
+ }
+ switch (action[0]) {
+ case 1:
+ stack.push(symbol);
+ vstack.push(this.lexer.yytext);
+ lstack.push(this.lexer.yylloc);
+ stack.push(action[1]);
+ symbol = null;
+ {
+ yyleng = this.lexer.yyleng;
+ yytext = this.lexer.yytext;
+ yylineno = this.lexer.yylineno;
+ yyloc = this.lexer.yylloc;
+ }
+ break;
+ case 2:
+ len = this.productions_[action[1]][1];
+ yyval.$ = vstack[vstack.length - len];
+ yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
+ if (ranges) {
+ yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
+ }
+ r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
+ if (typeof r !== "undefined") {
+ return r;
+ }
+ if (len) {
+ stack = stack.slice(0, -1 * len * 2);
+ vstack = vstack.slice(0, -1 * len);
+ lstack = lstack.slice(0, -1 * len);
+ }
+ stack.push(this.productions_[action[1]][0]);
+ vstack.push(yyval.$);
+ lstack.push(yyval._$);
+ newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
+ stack.push(newState);
+ break;
+ case 3:
+ return true;
+ }
+ }
+ return true;
+ }
+ };
+ /* Jison generated lexer */
+ var lexer = (function () {
+ var lexer = { EOF: 1,
+ parseError: function parseError(str, hash) {
+ if (this.yy.parser) {
+ this.yy.parser.parseError(str, hash);
+ } else {
+ throw new Error(str);
+ }
+ },
+ setInput: function setInput(input) {
+ this._input = input;
+ this._more = this._less = this.done = false;
+ this.yylineno = this.yyleng = 0;
+ this.yytext = this.matched = this.match = '';
+ this.conditionStack = ['INITIAL'];
+ this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
+ if (this.options.ranges) this.yylloc.range = [0, 0];
+ this.offset = 0;
+ return this;
+ },
+ input: function input() {
+ var ch = this._input[0];
+ this.yytext += ch;
+ this.yyleng++;
+ this.offset++;
+ this.match += ch;
+ this.matched += ch;
+ var lines = ch.match(/(?:\r\n?|\n).*/g);
+ if (lines) {
+ this.yylineno++;
+ this.yylloc.last_line++;
+ } else {
+ this.yylloc.last_column++;
+ }
+ if (this.options.ranges) this.yylloc.range[1]++;
+
+ this._input = this._input.slice(1);
+ return ch;
+ },
+ unput: function unput(ch) {
+ var len = ch.length;
+ var lines = ch.split(/(?:\r\n?|\n)/g);
+
+ this._input = ch + this._input;
+ this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
+ //this.yyleng -= len;
+ this.offset -= len;
+ var oldLines = this.match.split(/(?:\r\n?|\n)/g);
+ this.match = this.match.substr(0, this.match.length - 1);
+ this.matched = this.matched.substr(0, this.matched.length - 1);
+
+ if (lines.length - 1) this.yylineno -= lines.length - 1;
+ var r = this.yylloc.range;
+
+ this.yylloc = { first_line: this.yylloc.first_line,
+ last_line: this.yylineno + 1,
+ first_column: this.yylloc.first_column,
+ last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
+ };
+
+ if (this.options.ranges) {
+ this.yylloc.range = [r[0], r[0] + this.yyleng - len];
+ }
+ return this;
+ },
+ more: function more() {
+ this._more = true;
+ return this;
+ },
+ less: function less(n) {
+ this.unput(this.match.slice(n));
+ },
+ pastInput: function pastInput() {
+ var past = this.matched.substr(0, this.matched.length - this.match.length);
+ return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
+ },
+ upcomingInput: function upcomingInput() {
+ var next = this.match;
+ if (next.length < 20) {
+ next += this._input.substr(0, 20 - next.length);
+ }
+ return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
+ },
+ showPosition: function showPosition() {
+ var pre = this.pastInput();
+ var c = new Array(pre.length + 1).join("-");
+ return pre + this.upcomingInput() + "\n" + c + "^";
+ },
+ next: function next() {
+ if (this.done) {
+ return this.EOF;
+ }
+ if (!this._input) this.done = true;
+
+ var token, match, tempMatch, index, lines;
+ if (!this._more) {
+ this.yytext = '';
+ this.match = '';
+ }
+ var rules = this._currentRules();
+ for (var i = 0; i < rules.length; i++) {
+ tempMatch = this._input.match(this.rules[rules[i]]);
+ if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
+ match = tempMatch;
+ index = i;
+ if (!this.options.flex) break;
+ }
+ }
+ if (match) {
+ lines = match[0].match(/(?:\r\n?|\n).*/g);
+ if (lines) this.yylineno += lines.length;
+ this.yylloc = { first_line: this.yylloc.last_line,
+ last_line: this.yylineno + 1,
+ first_column: this.yylloc.last_column,
+ last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
+ this.yytext += match[0];
+ this.match += match[0];
+ this.matches = match;
+ this.yyleng = this.yytext.length;
+ if (this.options.ranges) {
+ this.yylloc.range = [this.offset, this.offset += this.yyleng];
+ }
+ this._more = false;
+ this._input = this._input.slice(match[0].length);
+ this.matched += match[0];
+ token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
+ if (this.done && this._input) this.done = false;
+ if (token) return token;else return;
+ }
+ if (this._input === "") {
+ return this.EOF;
+ } else {
+ return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
+ }
+ },
+ lex: function lex() {
+ var r = this.next();
+ if (typeof r !== 'undefined') {
+ return r;
+ } else {
+ return this.lex();
+ }
+ },
+ begin: function begin(condition) {
+ this.conditionStack.push(condition);
+ },
+ popState: function popState() {
+ return this.conditionStack.pop();
+ },
+ _currentRules: function _currentRules() {
+ return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
+ },
+ topState: function topState() {
+ return this.conditionStack[this.conditionStack.length - 2];
+ },
+ pushState: function begin(condition) {
+ this.begin(condition);
+ } };
+ lexer.options = {};
+ lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
+
+ function strip(start, end) {
+ return yy_.yytext = yy_.yytext.substring(start, yy_.yyleng - end + start);
+ }
+ switch ($avoiding_name_collisions) {
+ case 0:
+ if (yy_.yytext.slice(-2) === "\\\\") {
+ strip(0, 1);
+ this.begin("mu");
+ } else if (yy_.yytext.slice(-1) === "\\") {
+ strip(0, 1);
+ this.begin("emu");
+ } else {
+ this.begin("mu");
+ }
+ if (yy_.yytext) return 15;
+
+ break;
+ case 1:
+ return 15;
+ case 2:
+ this.popState();
+ return 15;
+ case 3:
+ this.begin('raw');return 15;
+ case 4:
+ this.popState();
+ // Should be using `this.topState()` below, but it currently
+ // returns the second top instead of the first top. Opened an
+ // issue about it at https://github.com/zaach/jison/issues/291
+ if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
+ return 15;
+ } else {
+ strip(5, 9);
+ return 'END_RAW_BLOCK';
+ }
+ case 5:
+ return 15;
+ case 6:
+ this.popState();
+ return 14;
+ case 7:
+ return 65;
+ case 8:
+ return 68;
+ case 9:
+ return 19;
+ case 10:
+ this.popState();
+ this.begin('raw');
+ return 23;
+ case 11:
+ return 55;
+ case 12:
+ return 60;
+ case 13:
+ return 29;
+ case 14:
+ return 47;
+ case 15:
+ this.popState();return 44;
+ case 16:
+ this.popState();return 44;
+ case 17:
+ return 34;
+ case 18:
+ return 39;
+ case 19:
+ return 51;
+ case 20:
+ return 48;
+ case 21:
+ this.unput(yy_.yytext);
+ this.popState();
+ this.begin('com');
+
+ break;
+ case 22:
+ this.popState();
+ return 14;
+ case 23:
+ return 48;
+ case 24:
+ return 73;
+ case 25:
+ return 72;
+ case 26:
+ return 72;
+ case 27:
+ return 87;
+ case 28:
+ // ignore whitespace
+ break;
+ case 29:
+ this.popState();return 54;
+ case 30:
+ this.popState();return 33;
+ case 31:
+ yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
+ case 32:
+ yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
+ case 33:
+ return 85;
+ case 34:
+ return 82;
+ case 35:
+ return 82;
+ case 36:
+ return 83;
+ case 37:
+ return 84;
+ case 38:
+ return 81;
+ case 39:
+ return 75;
+ case 40:
+ return 77;
+ case 41:
+ return 72;
+ case 42:
+ yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
+ case 43:
+ return 'INVALID';
+ case 44:
+ return 5;
+ }
+ };
+ lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^\/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]+?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
+ lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
+ return lexer;
+ })();
+ parser.lexer = lexer;
+ function Parser() {
+ this.yy = {};
+ }Parser.prototype = parser;parser.Parser = Parser;
+ return new Parser();
+ })();exports["default"] = handlebars;
+ module.exports = exports["default"];
+
+} (parser, parserExports));
+
+var whitespaceControlExports = {};
+var whitespaceControl = {
+ get exports(){ return whitespaceControlExports; },
+ set exports(v){ whitespaceControlExports = v; },
+};
+
+var visitorExports = {};
+var visitor = {
+ get exports(){ return visitorExports; },
+ set exports(v){ visitorExports = v; },
+};
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _exception = exceptionExports;
+
+ var _exception2 = _interopRequireDefault(_exception);
+
+ function Visitor() {
+ this.parents = [];
+ }
+
+ Visitor.prototype = {
+ constructor: Visitor,
+ mutating: false,
+
+ // Visits a given value. If mutating, will replace the value if necessary.
+ acceptKey: function acceptKey(node, name) {
+ var value = this.accept(node[name]);
+ if (this.mutating) {
+ // Hacky sanity check: This may have a few false positives for type for the helper
+ // methods but will generally do the right thing without a lot of overhead.
+ if (value && !Visitor.prototype[value.type]) {
+ throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
+ }
+ node[name] = value;
+ }
+ },
+
+ // Performs an accept operation with added sanity check to ensure
+ // required keys are not removed.
+ acceptRequired: function acceptRequired(node, name) {
+ this.acceptKey(node, name);
+
+ if (!node[name]) {
+ throw new _exception2['default'](node.type + ' requires ' + name);
+ }
+ },
+
+ // Traverses a given array. If mutating, empty respnses will be removed
+ // for child elements.
+ acceptArray: function acceptArray(array) {
+ for (var i = 0, l = array.length; i < l; i++) {
+ this.acceptKey(array, i);
+
+ if (!array[i]) {
+ array.splice(i, 1);
+ i--;
+ l--;
+ }
+ }
+ },
+
+ accept: function accept(object) {
+ if (!object) {
+ return;
+ }
+
+ /* istanbul ignore next: Sanity code */
+ if (!this[object.type]) {
+ throw new _exception2['default']('Unknown type: ' + object.type, object);
+ }
+
+ if (this.current) {
+ this.parents.unshift(this.current);
+ }
+ this.current = object;
+
+ var ret = this[object.type](object);
+
+ this.current = this.parents.shift();
+
+ if (!this.mutating || ret) {
+ return ret;
+ } else if (ret !== false) {
+ return object;
+ }
+ },
+
+ Program: function Program(program) {
+ this.acceptArray(program.body);
+ },
+
+ MustacheStatement: visitSubExpression,
+ Decorator: visitSubExpression,
+
+ BlockStatement: visitBlock,
+ DecoratorBlock: visitBlock,
+
+ PartialStatement: visitPartial,
+ PartialBlockStatement: function PartialBlockStatement(partial) {
+ visitPartial.call(this, partial);
+
+ this.acceptKey(partial, 'program');
+ },
+
+ ContentStatement: function ContentStatement() /* content */{},
+ CommentStatement: function CommentStatement() /* comment */{},
+
+ SubExpression: visitSubExpression,
+
+ PathExpression: function PathExpression() /* path */{},
+
+ StringLiteral: function StringLiteral() /* string */{},
+ NumberLiteral: function NumberLiteral() /* number */{},
+ BooleanLiteral: function BooleanLiteral() /* bool */{},
+ UndefinedLiteral: function UndefinedLiteral() /* literal */{},
+ NullLiteral: function NullLiteral() /* literal */{},
+
+ Hash: function Hash(hash) {
+ this.acceptArray(hash.pairs);
+ },
+ HashPair: function HashPair(pair) {
+ this.acceptRequired(pair, 'value');
+ }
+ };
+
+ function visitSubExpression(mustache) {
+ this.acceptRequired(mustache, 'path');
+ this.acceptArray(mustache.params);
+ this.acceptKey(mustache, 'hash');
+ }
+ function visitBlock(block) {
+ visitSubExpression.call(this, block);
+
+ this.acceptKey(block, 'program');
+ this.acceptKey(block, 'inverse');
+ }
+ function visitPartial(partial) {
+ this.acceptRequired(partial, 'name');
+ this.acceptArray(partial.params);
+ this.acceptKey(partial, 'hash');
+ }
+
+ exports['default'] = Visitor;
+ module.exports = exports['default'];
+
+} (visitor, visitorExports));
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _visitor = visitorExports;
+
+ var _visitor2 = _interopRequireDefault(_visitor);
+
+ function WhitespaceControl() {
+ var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
+
+ this.options = options;
+ }
+ WhitespaceControl.prototype = new _visitor2['default']();
+
+ WhitespaceControl.prototype.Program = function (program) {
+ var doStandalone = !this.options.ignoreStandalone;
+
+ var isRoot = !this.isRootSeen;
+ this.isRootSeen = true;
+
+ var body = program.body;
+ for (var i = 0, l = body.length; i < l; i++) {
+ var current = body[i],
+ strip = this.accept(current);
+
+ if (!strip) {
+ continue;
+ }
+
+ var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
+ _isNextWhitespace = isNextWhitespace(body, i, isRoot),
+ openStandalone = strip.openStandalone && _isPrevWhitespace,
+ closeStandalone = strip.closeStandalone && _isNextWhitespace,
+ inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
+
+ if (strip.close) {
+ omitRight(body, i, true);
+ }
+ if (strip.open) {
+ omitLeft(body, i, true);
+ }
+
+ if (doStandalone && inlineStandalone) {
+ omitRight(body, i);
+
+ if (omitLeft(body, i)) {
+ // If we are on a standalone node, save the indent info for partials
+ if (current.type === 'PartialStatement') {
+ // Pull out the whitespace from the final line
+ current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
+ }
+ }
+ }
+ if (doStandalone && openStandalone) {
+ omitRight((current.program || current.inverse).body);
+
+ // Strip out the previous content node if it's whitespace only
+ omitLeft(body, i);
+ }
+ if (doStandalone && closeStandalone) {
+ // Always strip the next node
+ omitRight(body, i);
+
+ omitLeft((current.inverse || current.program).body);
+ }
+ }
+
+ return program;
+ };
+
+ WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
+ this.accept(block.program);
+ this.accept(block.inverse);
+
+ // Find the inverse program that is involed with whitespace stripping.
+ var program = block.program || block.inverse,
+ inverse = block.program && block.inverse,
+ firstInverse = inverse,
+ lastInverse = inverse;
+
+ if (inverse && inverse.chained) {
+ firstInverse = inverse.body[0].program;
+
+ // Walk the inverse chain to find the last inverse that is actually in the chain.
+ while (lastInverse.chained) {
+ lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
+ }
+ }
+
+ var strip = {
+ open: block.openStrip.open,
+ close: block.closeStrip.close,
+
+ // Determine the standalone candiacy. Basically flag our content as being possibly standalone
+ // so our parent can determine if we actually are standalone
+ openStandalone: isNextWhitespace(program.body),
+ closeStandalone: isPrevWhitespace((firstInverse || program).body)
+ };
+
+ if (block.openStrip.close) {
+ omitRight(program.body, null, true);
+ }
+
+ if (inverse) {
+ var inverseStrip = block.inverseStrip;
+
+ if (inverseStrip.open) {
+ omitLeft(program.body, null, true);
+ }
+
+ if (inverseStrip.close) {
+ omitRight(firstInverse.body, null, true);
+ }
+ if (block.closeStrip.open) {
+ omitLeft(lastInverse.body, null, true);
+ }
+
+ // Find standalone else statments
+ if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
+ omitLeft(program.body);
+ omitRight(firstInverse.body);
+ }
+ } else if (block.closeStrip.open) {
+ omitLeft(program.body, null, true);
+ }
+
+ return strip;
+ };
+
+ WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
+ return mustache.strip;
+ };
+
+ WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
+ /* istanbul ignore next */
+ var strip = node.strip || {};
+ return {
+ inlineStandalone: true,
+ open: strip.open,
+ close: strip.close
+ };
+ };
+
+ function isPrevWhitespace(body, i, isRoot) {
+ if (i === undefined) {
+ i = body.length;
+ }
+
+ // Nodes that end with newlines are considered whitespace (but are special
+ // cased for strip operations)
+ var prev = body[i - 1],
+ sibling = body[i - 2];
+ if (!prev) {
+ return isRoot;
+ }
+
+ if (prev.type === 'ContentStatement') {
+ return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
+ }
+ }
+ function isNextWhitespace(body, i, isRoot) {
+ if (i === undefined) {
+ i = -1;
+ }
+
+ var next = body[i + 1],
+ sibling = body[i + 2];
+ if (!next) {
+ return isRoot;
+ }
+
+ if (next.type === 'ContentStatement') {
+ return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
+ }
+ }
+
+ // Marks the node to the right of the position as omitted.
+ // I.e. {{foo}}' ' will mark the ' ' node as omitted.
+ //
+ // If i is undefined, then the first child will be marked as such.
+ //
+ // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
+ // content is met.
+ function omitRight(body, i, multiple) {
+ var current = body[i == null ? 0 : i + 1];
+ if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
+ return;
+ }
+
+ var original = current.value;
+ current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
+ current.rightStripped = current.value !== original;
+ }
+
+ // Marks the node to the left of the position as omitted.
+ // I.e. ' '{{foo}} will mark the ' ' node as omitted.
+ //
+ // If i is undefined then the last child will be marked as such.
+ //
+ // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
+ // content is met.
+ function omitLeft(body, i, multiple) {
+ var current = body[i == null ? body.length - 1 : i - 1];
+ if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
+ return;
+ }
+
+ // We omit the last node if it's whitespace only and not preceded by a non-content node.
+ var original = current.value;
+ current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
+ current.leftStripped = current.value !== original;
+ return current.leftStripped;
+ }
+
+ exports['default'] = WhitespaceControl;
+ module.exports = exports['default'];
+
+} (whitespaceControl, whitespaceControlExports));
+
+var helpers = {};
+
+helpers.__esModule = true;
+helpers.SourceLocation = SourceLocation;
+helpers.id = id;
+helpers.stripFlags = stripFlags;
+helpers.stripComment = stripComment;
+helpers.preparePath = preparePath;
+helpers.prepareMustache = prepareMustache;
+helpers.prepareRawBlock = prepareRawBlock;
+helpers.prepareBlock = prepareBlock;
+helpers.prepareProgram = prepareProgram;
+helpers.preparePartialBlock = preparePartialBlock;
+// istanbul ignore next
+
+function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _exception$1 = exceptionExports;
+
+var _exception2$1 = _interopRequireDefault$3(_exception$1);
+
+function validateClose(open, close) {
+ close = close.path ? close.path.original : close;
+
+ if (open.path.original !== close) {
+ var errorNode = { loc: open.path.loc };
+
+ throw new _exception2$1['default'](open.path.original + " doesn't match " + close, errorNode);
+ }
+}
+
+function SourceLocation(source, locInfo) {
+ this.source = source;
+ this.start = {
+ line: locInfo.first_line,
+ column: locInfo.first_column
+ };
+ this.end = {
+ line: locInfo.last_line,
+ column: locInfo.last_column
+ };
+}
+
+function id(token) {
+ if (/^\[.*\]$/.test(token)) {
+ return token.substring(1, token.length - 1);
+ } else {
+ return token;
+ }
+}
+
+function stripFlags(open, close) {
+ return {
+ open: open.charAt(2) === '~',
+ close: close.charAt(close.length - 3) === '~'
+ };
+}
+
+function stripComment(comment) {
+ return comment.replace(/^\{\{~?!-?-?/, '').replace(/-?-?~?\}\}$/, '');
+}
+
+function preparePath(data, parts, loc) {
+ loc = this.locInfo(loc);
+
+ var original = data ? '@' : '',
+ dig = [],
+ depth = 0;
+
+ for (var i = 0, l = parts.length; i < l; i++) {
+ var part = parts[i].part,
+
+ // If we have [] syntax then we do not treat path references as operators,
+ // i.e. foo.[this] resolves to approximately context.foo['this']
+ isLiteral = parts[i].original !== part;
+ original += (parts[i].separator || '') + part;
+
+ if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
+ if (dig.length > 0) {
+ throw new _exception2$1['default']('Invalid path: ' + original, { loc: loc });
+ } else if (part === '..') {
+ depth++;
+ }
+ } else {
+ dig.push(part);
+ }
+ }
+
+ return {
+ type: 'PathExpression',
+ data: data,
+ depth: depth,
+ parts: dig,
+ original: original,
+ loc: loc
+ };
+}
+
+function prepareMustache(path, params, hash, open, strip, locInfo) {
+ // Must use charAt to support IE pre-10
+ var escapeFlag = open.charAt(3) || open.charAt(2),
+ escaped = escapeFlag !== '{' && escapeFlag !== '&';
+
+ var decorator = /\*/.test(open);
+ return {
+ type: decorator ? 'Decorator' : 'MustacheStatement',
+ path: path,
+ params: params,
+ hash: hash,
+ escaped: escaped,
+ strip: strip,
+ loc: this.locInfo(locInfo)
+ };
+}
+
+function prepareRawBlock(openRawBlock, contents, close, locInfo) {
+ validateClose(openRawBlock, close);
+
+ locInfo = this.locInfo(locInfo);
+ var program = {
+ type: 'Program',
+ body: contents,
+ strip: {},
+ loc: locInfo
+ };
+
+ return {
+ type: 'BlockStatement',
+ path: openRawBlock.path,
+ params: openRawBlock.params,
+ hash: openRawBlock.hash,
+ program: program,
+ openStrip: {},
+ inverseStrip: {},
+ closeStrip: {},
+ loc: locInfo
+ };
+}
+
+function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
+ if (close && close.path) {
+ validateClose(openBlock, close);
+ }
+
+ var decorator = /\*/.test(openBlock.open);
+
+ program.blockParams = openBlock.blockParams;
+
+ var inverse = undefined,
+ inverseStrip = undefined;
+
+ if (inverseAndProgram) {
+ if (decorator) {
+ throw new _exception2$1['default']('Unexpected inverse block on decorator', inverseAndProgram);
+ }
+
+ if (inverseAndProgram.chain) {
+ inverseAndProgram.program.body[0].closeStrip = close.strip;
+ }
+
+ inverseStrip = inverseAndProgram.strip;
+ inverse = inverseAndProgram.program;
+ }
+
+ if (inverted) {
+ inverted = inverse;
+ inverse = program;
+ program = inverted;
+ }
+
+ return {
+ type: decorator ? 'DecoratorBlock' : 'BlockStatement',
+ path: openBlock.path,
+ params: openBlock.params,
+ hash: openBlock.hash,
+ program: program,
+ inverse: inverse,
+ openStrip: openBlock.strip,
+ inverseStrip: inverseStrip,
+ closeStrip: close && close.strip,
+ loc: this.locInfo(locInfo)
+ };
+}
+
+function prepareProgram(statements, loc) {
+ if (!loc && statements.length) {
+ var firstLoc = statements[0].loc,
+ lastLoc = statements[statements.length - 1].loc;
+
+ /* istanbul ignore else */
+ if (firstLoc && lastLoc) {
+ loc = {
+ source: firstLoc.source,
+ start: {
+ line: firstLoc.start.line,
+ column: firstLoc.start.column
+ },
+ end: {
+ line: lastLoc.end.line,
+ column: lastLoc.end.column
+ }
+ };
+ }
+ }
+
+ return {
+ type: 'Program',
+ body: statements,
+ strip: {},
+ loc: loc
+ };
+}
+
+function preparePartialBlock(open, program, close, locInfo) {
+ validateClose(open, close);
+
+ return {
+ type: 'PartialBlockStatement',
+ name: open.path,
+ params: open.params,
+ hash: open.hash,
+ program: program,
+ openStrip: open.strip,
+ closeStrip: close && close.strip,
+ loc: this.locInfo(locInfo)
+ };
+}
+
+base.__esModule = true;
+base.parseWithoutProcessing = parseWithoutProcessing;
+base.parse = parse$4;
+// istanbul ignore next
+
+function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
+
+// istanbul ignore next
+
+function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _parser = parserExports;
+
+var _parser2 = _interopRequireDefault$2(_parser);
+
+var _whitespaceControl = whitespaceControlExports;
+
+var _whitespaceControl2 = _interopRequireDefault$2(_whitespaceControl);
+
+var _helpers = helpers;
+
+var Helpers = _interopRequireWildcard(_helpers);
+
+var _utils$1 = utils$1;
+
+base.parser = _parser2['default'];
+
+var yy = {};
+_utils$1.extend(yy, Helpers);
+
+function parseWithoutProcessing(input, options) {
+ // Just return if an already-compiled AST was passed in.
+ if (input.type === 'Program') {
+ return input;
+ }
+
+ _parser2['default'].yy = yy;
+
+ // Altering the shared object here, but this is ok as parser is a sync operation
+ yy.locInfo = function (locInfo) {
+ return new yy.SourceLocation(options && options.srcName, locInfo);
+ };
+
+ var ast = _parser2['default'].parse(input);
+
+ return ast;
+}
+
+function parse$4(input, options) {
+ var ast = parseWithoutProcessing(input, options);
+ var strip = new _whitespaceControl2['default'](options);
+
+ return strip.accept(ast);
+}
+
+var compiler = {};
+
+/* eslint-disable new-cap */
+
+compiler.__esModule = true;
+compiler.Compiler = Compiler;
+compiler.precompile = precompile;
+compiler.compile = compile;
+// istanbul ignore next
+
+function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _exception = exceptionExports;
+
+var _exception2 = _interopRequireDefault$1(_exception);
+
+var _utils = utils$1;
+
+var _ast = astExports;
+
+var _ast2 = _interopRequireDefault$1(_ast);
+
+var slice$1 = [].slice;
+
+function Compiler() {}
+
+// the foundHelper register will disambiguate helper lookup from finding a
+// function in a context. This is necessary for mustache compatibility, which
+// requires that context functions in blocks are evaluated by blockHelperMissing,
+// and then proceed as if the resulting value was provided to blockHelperMissing.
+
+Compiler.prototype = {
+ compiler: Compiler,
+
+ equals: function equals(other) {
+ var len = this.opcodes.length;
+ if (other.opcodes.length !== len) {
+ return false;
+ }
+
+ for (var i = 0; i < len; i++) {
+ var opcode = this.opcodes[i],
+ otherOpcode = other.opcodes[i];
+ if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
+ return false;
+ }
+ }
+
+ // We know that length is the same between the two arrays because they are directly tied
+ // to the opcode behavior above.
+ len = this.children.length;
+ for (var i = 0; i < len; i++) {
+ if (!this.children[i].equals(other.children[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ guid: 0,
+
+ compile: function compile(program, options) {
+ this.sourceNode = [];
+ this.opcodes = [];
+ this.children = [];
+ this.options = options;
+ this.stringParams = options.stringParams;
+ this.trackIds = options.trackIds;
+
+ options.blockParams = options.blockParams || [];
+
+ options.knownHelpers = _utils.extend(Object.create(null), {
+ helperMissing: true,
+ blockHelperMissing: true,
+ each: true,
+ 'if': true,
+ unless: true,
+ 'with': true,
+ log: true,
+ lookup: true
+ }, options.knownHelpers);
+
+ return this.accept(program);
+ },
+
+ compileProgram: function compileProgram(program) {
+ var childCompiler = new this.compiler(),
+ // eslint-disable-line new-cap
+ result = childCompiler.compile(program, this.options),
+ guid = this.guid++;
+
+ this.usePartial = this.usePartial || result.usePartial;
+
+ this.children[guid] = result;
+ this.useDepths = this.useDepths || result.useDepths;
+
+ return guid;
+ },
+
+ accept: function accept(node) {
+ /* istanbul ignore next: Sanity code */
+ if (!this[node.type]) {
+ throw new _exception2['default']('Unknown type: ' + node.type, node);
+ }
+
+ this.sourceNode.unshift(node);
+ var ret = this[node.type](node);
+ this.sourceNode.shift();
+ return ret;
+ },
+
+ Program: function Program(program) {
+ this.options.blockParams.unshift(program.blockParams);
+
+ var body = program.body,
+ bodyLength = body.length;
+ for (var i = 0; i < bodyLength; i++) {
+ this.accept(body[i]);
+ }
+
+ this.options.blockParams.shift();
+
+ this.isSimple = bodyLength === 1;
+ this.blockParams = program.blockParams ? program.blockParams.length : 0;
+
+ return this;
+ },
+
+ BlockStatement: function BlockStatement(block) {
+ transformLiteralToPath(block);
+
+ var program = block.program,
+ inverse = block.inverse;
+
+ program = program && this.compileProgram(program);
+ inverse = inverse && this.compileProgram(inverse);
+
+ var type = this.classifySexpr(block);
+
+ if (type === 'helper') {
+ this.helperSexpr(block, program, inverse);
+ } else if (type === 'simple') {
+ this.simpleSexpr(block);
+
+ // now that the simple mustache is resolved, we need to
+ // evaluate it by executing `blockHelperMissing`
+ this.opcode('pushProgram', program);
+ this.opcode('pushProgram', inverse);
+ this.opcode('emptyHash');
+ this.opcode('blockValue', block.path.original);
+ } else {
+ this.ambiguousSexpr(block, program, inverse);
+
+ // now that the simple mustache is resolved, we need to
+ // evaluate it by executing `blockHelperMissing`
+ this.opcode('pushProgram', program);
+ this.opcode('pushProgram', inverse);
+ this.opcode('emptyHash');
+ this.opcode('ambiguousBlockValue');
+ }
+
+ this.opcode('append');
+ },
+
+ DecoratorBlock: function DecoratorBlock(decorator) {
+ var program = decorator.program && this.compileProgram(decorator.program);
+ var params = this.setupFullMustacheParams(decorator, program, undefined),
+ path = decorator.path;
+
+ this.useDecorators = true;
+ this.opcode('registerDecorator', params.length, path.original);
+ },
+
+ PartialStatement: function PartialStatement(partial) {
+ this.usePartial = true;
+
+ var program = partial.program;
+ if (program) {
+ program = this.compileProgram(partial.program);
+ }
+
+ var params = partial.params;
+ if (params.length > 1) {
+ throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
+ } else if (!params.length) {
+ if (this.options.explicitPartialContext) {
+ this.opcode('pushLiteral', 'undefined');
+ } else {
+ params.push({ type: 'PathExpression', parts: [], depth: 0 });
+ }
+ }
+
+ var partialName = partial.name.original,
+ isDynamic = partial.name.type === 'SubExpression';
+ if (isDynamic) {
+ this.accept(partial.name);
+ }
+
+ this.setupFullMustacheParams(partial, program, undefined, true);
+
+ var indent = partial.indent || '';
+ if (this.options.preventIndent && indent) {
+ this.opcode('appendContent', indent);
+ indent = '';
+ }
+
+ this.opcode('invokePartial', isDynamic, partialName, indent);
+ this.opcode('append');
+ },
+ PartialBlockStatement: function PartialBlockStatement(partialBlock) {
+ this.PartialStatement(partialBlock);
+ },
+
+ MustacheStatement: function MustacheStatement(mustache) {
+ this.SubExpression(mustache);
+
+ if (mustache.escaped && !this.options.noEscape) {
+ this.opcode('appendEscaped');
+ } else {
+ this.opcode('append');
+ }
+ },
+ Decorator: function Decorator(decorator) {
+ this.DecoratorBlock(decorator);
+ },
+
+ ContentStatement: function ContentStatement(content) {
+ if (content.value) {
+ this.opcode('appendContent', content.value);
+ }
+ },
+
+ CommentStatement: function CommentStatement() {},
+
+ SubExpression: function SubExpression(sexpr) {
+ transformLiteralToPath(sexpr);
+ var type = this.classifySexpr(sexpr);
+
+ if (type === 'simple') {
+ this.simpleSexpr(sexpr);
+ } else if (type === 'helper') {
+ this.helperSexpr(sexpr);
+ } else {
+ this.ambiguousSexpr(sexpr);
+ }
+ },
+ ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
+ var path = sexpr.path,
+ name = path.parts[0],
+ isBlock = program != null || inverse != null;
+
+ this.opcode('getContext', path.depth);
+
+ this.opcode('pushProgram', program);
+ this.opcode('pushProgram', inverse);
+
+ path.strict = true;
+ this.accept(path);
+
+ this.opcode('invokeAmbiguous', name, isBlock);
+ },
+
+ simpleSexpr: function simpleSexpr(sexpr) {
+ var path = sexpr.path;
+ path.strict = true;
+ this.accept(path);
+ this.opcode('resolvePossibleLambda');
+ },
+
+ helperSexpr: function helperSexpr(sexpr, program, inverse) {
+ var params = this.setupFullMustacheParams(sexpr, program, inverse),
+ path = sexpr.path,
+ name = path.parts[0];
+
+ if (this.options.knownHelpers[name]) {
+ this.opcode('invokeKnownHelper', params.length, name);
+ } else if (this.options.knownHelpersOnly) {
+ throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
+ } else {
+ path.strict = true;
+ path.falsy = true;
+
+ this.accept(path);
+ this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
+ }
+ },
+
+ PathExpression: function PathExpression(path) {
+ this.addDepth(path.depth);
+ this.opcode('getContext', path.depth);
+
+ var name = path.parts[0],
+ scoped = _ast2['default'].helpers.scopedId(path),
+ blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
+
+ if (blockParamId) {
+ this.opcode('lookupBlockParam', blockParamId, path.parts);
+ } else if (!name) {
+ // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
+ this.opcode('pushContext');
+ } else if (path.data) {
+ this.options.data = true;
+ this.opcode('lookupData', path.depth, path.parts, path.strict);
+ } else {
+ this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
+ }
+ },
+
+ StringLiteral: function StringLiteral(string) {
+ this.opcode('pushString', string.value);
+ },
+
+ NumberLiteral: function NumberLiteral(number) {
+ this.opcode('pushLiteral', number.value);
+ },
+
+ BooleanLiteral: function BooleanLiteral(bool) {
+ this.opcode('pushLiteral', bool.value);
+ },
+
+ UndefinedLiteral: function UndefinedLiteral() {
+ this.opcode('pushLiteral', 'undefined');
+ },
+
+ NullLiteral: function NullLiteral() {
+ this.opcode('pushLiteral', 'null');
+ },
+
+ Hash: function Hash(hash) {
+ var pairs = hash.pairs,
+ i = 0,
+ l = pairs.length;
+
+ this.opcode('pushHash');
+
+ for (; i < l; i++) {
+ this.pushParam(pairs[i].value);
+ }
+ while (i--) {
+ this.opcode('assignToHash', pairs[i].key);
+ }
+ this.opcode('popHash');
+ },
+
+ // HELPERS
+ opcode: function opcode(name) {
+ this.opcodes.push({
+ opcode: name,
+ args: slice$1.call(arguments, 1),
+ loc: this.sourceNode[0].loc
+ });
+ },
+
+ addDepth: function addDepth(depth) {
+ if (!depth) {
+ return;
+ }
+
+ this.useDepths = true;
+ },
+
+ classifySexpr: function classifySexpr(sexpr) {
+ var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
+
+ var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
+
+ // a mustache is an eligible helper if:
+ // * its id is simple (a single part, not `this` or `..`)
+ var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
+
+ // if a mustache is an eligible helper but not a definite
+ // helper, it is ambiguous, and will be resolved in a later
+ // pass or at runtime.
+ var isEligible = !isBlockParam && (isHelper || isSimple);
+
+ // if ambiguous, we can possibly resolve the ambiguity now
+ // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
+ if (isEligible && !isHelper) {
+ var _name = sexpr.path.parts[0],
+ options = this.options;
+ if (options.knownHelpers[_name]) {
+ isHelper = true;
+ } else if (options.knownHelpersOnly) {
+ isEligible = false;
+ }
+ }
+
+ if (isHelper) {
+ return 'helper';
+ } else if (isEligible) {
+ return 'ambiguous';
+ } else {
+ return 'simple';
+ }
+ },
+
+ pushParams: function pushParams(params) {
+ for (var i = 0, l = params.length; i < l; i++) {
+ this.pushParam(params[i]);
+ }
+ },
+
+ pushParam: function pushParam(val) {
+ var value = val.value != null ? val.value : val.original || '';
+
+ if (this.stringParams) {
+ if (value.replace) {
+ value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
+ }
+
+ if (val.depth) {
+ this.addDepth(val.depth);
+ }
+ this.opcode('getContext', val.depth || 0);
+ this.opcode('pushStringParam', value, val.type);
+
+ if (val.type === 'SubExpression') {
+ // SubExpressions get evaluated and passed in
+ // in string params mode.
+ this.accept(val);
+ }
+ } else {
+ if (this.trackIds) {
+ var blockParamIndex = undefined;
+ if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
+ blockParamIndex = this.blockParamIndex(val.parts[0]);
+ }
+ if (blockParamIndex) {
+ var blockParamChild = val.parts.slice(1).join('.');
+ this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
+ } else {
+ value = val.original || value;
+ if (value.replace) {
+ value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
+ }
+
+ this.opcode('pushId', val.type, value);
+ }
+ }
+ this.accept(val);
+ }
+ },
+
+ setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
+ var params = sexpr.params;
+ this.pushParams(params);
+
+ this.opcode('pushProgram', program);
+ this.opcode('pushProgram', inverse);
+
+ if (sexpr.hash) {
+ this.accept(sexpr.hash);
+ } else {
+ this.opcode('emptyHash', omitEmpty);
+ }
+
+ return params;
+ },
+
+ blockParamIndex: function blockParamIndex(name) {
+ for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
+ var blockParams = this.options.blockParams[depth],
+ param = blockParams && _utils.indexOf(blockParams, name);
+ if (blockParams && param >= 0) {
+ return [depth, param];
+ }
+ }
+ }
+};
+
+function precompile(input, options, env) {
+ if (input == null || typeof input !== 'string' && input.type !== 'Program') {
+ throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
+ }
+
+ options = options || {};
+ if (!('data' in options)) {
+ options.data = true;
+ }
+ if (options.compat) {
+ options.useDepths = true;
+ }
+
+ var ast = env.parse(input, options),
+ environment = new env.Compiler().compile(ast, options);
+ return new env.JavaScriptCompiler().compile(environment, options);
+}
+
+function compile(input, options, env) {
+ if (options === undefined) options = {};
+
+ if (input == null || typeof input !== 'string' && input.type !== 'Program') {
+ throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
+ }
+
+ options = _utils.extend({}, options);
+ if (!('data' in options)) {
+ options.data = true;
+ }
+ if (options.compat) {
+ options.useDepths = true;
+ }
+
+ var compiled = undefined;
+
+ function compileInput() {
+ var ast = env.parse(input, options),
+ environment = new env.Compiler().compile(ast, options),
+ templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
+ return env.template(templateSpec);
+ }
+
+ // Template is only compiled on first use and cached after that point.
+ function ret(context, execOptions) {
+ if (!compiled) {
+ compiled = compileInput();
+ }
+ return compiled.call(this, context, execOptions);
+ }
+ ret._setup = function (setupOptions) {
+ if (!compiled) {
+ compiled = compileInput();
+ }
+ return compiled._setup(setupOptions);
+ };
+ ret._child = function (i, data, blockParams, depths) {
+ if (!compiled) {
+ compiled = compileInput();
+ }
+ return compiled._child(i, data, blockParams, depths);
+ };
+ return ret;
+}
+
+function argEquals(a, b) {
+ if (a === b) {
+ return true;
+ }
+
+ if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
+ for (var i = 0; i < a.length; i++) {
+ if (!argEquals(a[i], b[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
+
+function transformLiteralToPath(sexpr) {
+ if (!sexpr.path.parts) {
+ var literal = sexpr.path;
+ // Casting to string here to make false and 0 literal values play nicely with the rest
+ // of the system.
+ sexpr.path = {
+ type: 'PathExpression',
+ data: false,
+ depth: 0,
+ parts: [literal.original + ''],
+ original: literal.original + '',
+ loc: literal.loc
+ };
+ }
+}
+
+var javascriptCompilerExports = {};
+var javascriptCompiler = {
+ get exports(){ return javascriptCompilerExports; },
+ set exports(v){ javascriptCompilerExports = v; },
+};
+
+var codeGenExports = {};
+var codeGen = {
+ get exports(){ return codeGenExports; },
+ set exports(v){ codeGenExports = v; },
+};
+
+var sourceMap = {};
+
+var sourceMapGenerator = {};
+
+var base64Vlq = {};
+
+var base64 = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredBase64;
+
+function requireBase64 () {
+ if (hasRequiredBase64) return base64;
+ hasRequiredBase64 = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
+
+ /**
+ * Encode an integer in the range of 0 to 63 to a single base 64 digit.
+ */
+ base64.encode = function (number) {
+ if (0 <= number && number < intToCharMap.length) {
+ return intToCharMap[number];
+ }
+ throw new TypeError("Must be between 0 and 63: " + number);
+ };
+
+ /**
+ * Decode a single base 64 character code digit to an integer. Returns -1 on
+ * failure.
+ */
+ base64.decode = function (charCode) {
+ var bigA = 65; // 'A'
+ var bigZ = 90; // 'Z'
+
+ var littleA = 97; // 'a'
+ var littleZ = 122; // 'z'
+
+ var zero = 48; // '0'
+ var nine = 57; // '9'
+
+ var plus = 43; // '+'
+ var slash = 47; // '/'
+
+ var littleOffset = 26;
+ var numberOffset = 52;
+
+ // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
+ if (bigA <= charCode && charCode <= bigZ) {
+ return (charCode - bigA);
+ }
+
+ // 26 - 51: abcdefghijklmnopqrstuvwxyz
+ if (littleA <= charCode && charCode <= littleZ) {
+ return (charCode - littleA + littleOffset);
+ }
+
+ // 52 - 61: 0123456789
+ if (zero <= charCode && charCode <= nine) {
+ return (charCode - zero + numberOffset);
+ }
+
+ // 62: +
+ if (charCode == plus) {
+ return 62;
+ }
+
+ // 63: /
+ if (charCode == slash) {
+ return 63;
+ }
+
+ // Invalid base64 digit.
+ return -1;
+ };
+ return base64;
+}
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredBase64Vlq;
+
+function requireBase64Vlq () {
+ if (hasRequiredBase64Vlq) return base64Vlq;
+ hasRequiredBase64Vlq = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ *
+ * Based on the Base 64 VLQ implementation in Closure Compiler:
+ * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
+ *
+ * Copyright 2011 The Closure Compiler Authors. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+ var base64 = requireBase64();
+
+ // A single base 64 digit can contain 6 bits of data. For the base 64 variable
+ // length quantities we use in the source map spec, the first bit is the sign,
+ // the next four bits are the actual value, and the 6th bit is the
+ // continuation bit. The continuation bit tells us whether there are more
+ // digits in this value following this digit.
+ //
+ // Continuation
+ // | Sign
+ // | |
+ // V V
+ // 101011
+
+ var VLQ_BASE_SHIFT = 5;
+
+ // binary: 100000
+ var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
+
+ // binary: 011111
+ var VLQ_BASE_MASK = VLQ_BASE - 1;
+
+ // binary: 100000
+ var VLQ_CONTINUATION_BIT = VLQ_BASE;
+
+ /**
+ * Converts from a two-complement value to a value where the sign bit is
+ * placed in the least significant bit. For example, as decimals:
+ * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
+ * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
+ */
+ function toVLQSigned(aValue) {
+ return aValue < 0
+ ? ((-aValue) << 1) + 1
+ : (aValue << 1) + 0;
+ }
+
+ /**
+ * Converts to a two-complement value from a value where the sign bit is
+ * placed in the least significant bit. For example, as decimals:
+ * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
+ * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
+ */
+ function fromVLQSigned(aValue) {
+ var isNegative = (aValue & 1) === 1;
+ var shifted = aValue >> 1;
+ return isNegative
+ ? -shifted
+ : shifted;
+ }
+
+ /**
+ * Returns the base 64 VLQ encoded value.
+ */
+ base64Vlq.encode = function base64VLQ_encode(aValue) {
+ var encoded = "";
+ var digit;
+
+ var vlq = toVLQSigned(aValue);
+
+ do {
+ digit = vlq & VLQ_BASE_MASK;
+ vlq >>>= VLQ_BASE_SHIFT;
+ if (vlq > 0) {
+ // There are still more digits in this value, so we must make sure the
+ // continuation bit is marked.
+ digit |= VLQ_CONTINUATION_BIT;
+ }
+ encoded += base64.encode(digit);
+ } while (vlq > 0);
+
+ return encoded;
+ };
+
+ /**
+ * Decodes the next base 64 VLQ value from the given string and returns the
+ * value and the rest of the string via the out parameter.
+ */
+ base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
+ var strLen = aStr.length;
+ var result = 0;
+ var shift = 0;
+ var continuation, digit;
+
+ do {
+ if (aIndex >= strLen) {
+ throw new Error("Expected more digits in base 64 VLQ value.");
+ }
+
+ digit = base64.decode(aStr.charCodeAt(aIndex++));
+ if (digit === -1) {
+ throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
+ }
+
+ continuation = !!(digit & VLQ_CONTINUATION_BIT);
+ digit &= VLQ_BASE_MASK;
+ result = result + (digit << shift);
+ shift += VLQ_BASE_SHIFT;
+ } while (continuation);
+
+ aOutParam.value = fromVLQSigned(result);
+ aOutParam.rest = aIndex;
+ };
+ return base64Vlq;
+}
+
+var util$5 = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredUtil;
+
+function requireUtil () {
+ if (hasRequiredUtil) return util$5;
+ hasRequiredUtil = 1;
+ (function (exports) {
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ /**
+ * This is a helper function for getting values from parameter/options
+ * objects.
+ *
+ * @param args The object we are extracting values from
+ * @param name The name of the property we are getting.
+ * @param defaultValue An optional value to return if the property is missing
+ * from the object. If this is not specified and the property is missing, an
+ * error will be thrown.
+ */
+ function getArg(aArgs, aName, aDefaultValue) {
+ if (aName in aArgs) {
+ return aArgs[aName];
+ } else if (arguments.length === 3) {
+ return aDefaultValue;
+ } else {
+ throw new Error('"' + aName + '" is a required argument.');
+ }
+ }
+ exports.getArg = getArg;
+
+ var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
+ var dataUrlRegexp = /^data:.+\,.+$/;
+
+ function urlParse(aUrl) {
+ var match = aUrl.match(urlRegexp);
+ if (!match) {
+ return null;
+ }
+ return {
+ scheme: match[1],
+ auth: match[2],
+ host: match[3],
+ port: match[4],
+ path: match[5]
+ };
+ }
+ exports.urlParse = urlParse;
+
+ function urlGenerate(aParsedUrl) {
+ var url = '';
+ if (aParsedUrl.scheme) {
+ url += aParsedUrl.scheme + ':';
+ }
+ url += '//';
+ if (aParsedUrl.auth) {
+ url += aParsedUrl.auth + '@';
+ }
+ if (aParsedUrl.host) {
+ url += aParsedUrl.host;
+ }
+ if (aParsedUrl.port) {
+ url += ":" + aParsedUrl.port;
+ }
+ if (aParsedUrl.path) {
+ url += aParsedUrl.path;
+ }
+ return url;
+ }
+ exports.urlGenerate = urlGenerate;
+
+ /**
+ * Normalizes a path, or the path portion of a URL:
+ *
+ * - Replaces consecutive slashes with one slash.
+ * - Removes unnecessary '.' parts.
+ * - Removes unnecessary '/..' parts.
+ *
+ * Based on code in the Node.js 'path' core module.
+ *
+ * @param aPath The path or url to normalize.
+ */
+ function normalize(aPath) {
+ var path = aPath;
+ var url = urlParse(aPath);
+ if (url) {
+ if (!url.path) {
+ return aPath;
+ }
+ path = url.path;
+ }
+ var isAbsolute = exports.isAbsolute(path);
+
+ var parts = path.split(/\/+/);
+ for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
+ part = parts[i];
+ if (part === '.') {
+ parts.splice(i, 1);
+ } else if (part === '..') {
+ up++;
+ } else if (up > 0) {
+ if (part === '') {
+ // The first part is blank if the path is absolute. Trying to go
+ // above the root is a no-op. Therefore we can remove all '..' parts
+ // directly after the root.
+ parts.splice(i + 1, up);
+ up = 0;
+ } else {
+ parts.splice(i, 2);
+ up--;
+ }
+ }
+ }
+ path = parts.join('/');
+
+ if (path === '') {
+ path = isAbsolute ? '/' : '.';
+ }
+
+ if (url) {
+ url.path = path;
+ return urlGenerate(url);
+ }
+ return path;
+ }
+ exports.normalize = normalize;
+
+ /**
+ * Joins two paths/URLs.
+ *
+ * @param aRoot The root path or URL.
+ * @param aPath The path or URL to be joined with the root.
+ *
+ * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
+ * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
+ * first.
+ * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
+ * is updated with the result and aRoot is returned. Otherwise the result
+ * is returned.
+ * - If aPath is absolute, the result is aPath.
+ * - Otherwise the two paths are joined with a slash.
+ * - Joining for example 'http://' and 'www.example.com' is also supported.
+ */
+ function join(aRoot, aPath) {
+ if (aRoot === "") {
+ aRoot = ".";
+ }
+ if (aPath === "") {
+ aPath = ".";
+ }
+ var aPathUrl = urlParse(aPath);
+ var aRootUrl = urlParse(aRoot);
+ if (aRootUrl) {
+ aRoot = aRootUrl.path || '/';
+ }
+
+ // `join(foo, '//www.example.org')`
+ if (aPathUrl && !aPathUrl.scheme) {
+ if (aRootUrl) {
+ aPathUrl.scheme = aRootUrl.scheme;
+ }
+ return urlGenerate(aPathUrl);
+ }
+
+ if (aPathUrl || aPath.match(dataUrlRegexp)) {
+ return aPath;
+ }
+
+ // `join('http://', 'www.example.com')`
+ if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
+ aRootUrl.host = aPath;
+ return urlGenerate(aRootUrl);
+ }
+
+ var joined = aPath.charAt(0) === '/'
+ ? aPath
+ : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
+
+ if (aRootUrl) {
+ aRootUrl.path = joined;
+ return urlGenerate(aRootUrl);
+ }
+ return joined;
+ }
+ exports.join = join;
+
+ exports.isAbsolute = function (aPath) {
+ return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
+ };
+
+ /**
+ * Make a path relative to a URL or another path.
+ *
+ * @param aRoot The root path or URL.
+ * @param aPath The path or URL to be made relative to aRoot.
+ */
+ function relative(aRoot, aPath) {
+ if (aRoot === "") {
+ aRoot = ".";
+ }
+
+ aRoot = aRoot.replace(/\/$/, '');
+
+ // It is possible for the path to be above the root. In this case, simply
+ // checking whether the root is a prefix of the path won't work. Instead, we
+ // need to remove components from the root one by one, until either we find
+ // a prefix that fits, or we run out of components to remove.
+ var level = 0;
+ while (aPath.indexOf(aRoot + '/') !== 0) {
+ var index = aRoot.lastIndexOf("/");
+ if (index < 0) {
+ return aPath;
+ }
+
+ // If the only part of the root that is left is the scheme (i.e. http://,
+ // file:///, etc.), one or more slashes (/), or simply nothing at all, we
+ // have exhausted all components, so the path is not relative to the root.
+ aRoot = aRoot.slice(0, index);
+ if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
+ return aPath;
+ }
+
+ ++level;
+ }
+
+ // Make sure we add a "../" for each component we removed from the root.
+ return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
+ }
+ exports.relative = relative;
+
+ var supportsNullProto = (function () {
+ var obj = Object.create(null);
+ return !('__proto__' in obj);
+ }());
+
+ function identity (s) {
+ return s;
+ }
+
+ /**
+ * Because behavior goes wacky when you set `__proto__` on objects, we
+ * have to prefix all the strings in our set with an arbitrary character.
+ *
+ * See https://github.com/mozilla/source-map/pull/31 and
+ * https://github.com/mozilla/source-map/issues/30
+ *
+ * @param String aStr
+ */
+ function toSetString(aStr) {
+ if (isProtoString(aStr)) {
+ return '$' + aStr;
+ }
+
+ return aStr;
+ }
+ exports.toSetString = supportsNullProto ? identity : toSetString;
+
+ function fromSetString(aStr) {
+ if (isProtoString(aStr)) {
+ return aStr.slice(1);
+ }
+
+ return aStr;
+ }
+ exports.fromSetString = supportsNullProto ? identity : fromSetString;
+
+ function isProtoString(s) {
+ if (!s) {
+ return false;
+ }
+
+ var length = s.length;
+
+ if (length < 9 /* "__proto__".length */) {
+ return false;
+ }
+
+ if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
+ s.charCodeAt(length - 2) !== 95 /* '_' */ ||
+ s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
+ s.charCodeAt(length - 4) !== 116 /* 't' */ ||
+ s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
+ s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
+ s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
+ s.charCodeAt(length - 8) !== 95 /* '_' */ ||
+ s.charCodeAt(length - 9) !== 95 /* '_' */) {
+ return false;
+ }
+
+ for (var i = length - 10; i >= 0; i--) {
+ if (s.charCodeAt(i) !== 36 /* '$' */) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Comparator between two mappings where the original positions are compared.
+ *
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
+ * mappings with the same original source/line/column, but different generated
+ * line and column the same. Useful when searching for a mapping with a
+ * stubbed out mapping.
+ */
+ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
+ var cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0 || onlyCompareOriginal) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+ }
+ exports.compareByOriginalPositions = compareByOriginalPositions;
+
+ /**
+ * Comparator between two mappings with deflated source and name indices where
+ * the generated positions are compared.
+ *
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
+ * mappings with the same generated line and column, but different
+ * source/name/original line and column the same. Useful when searching for a
+ * mapping with a stubbed out mapping.
+ */
+ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
+ var cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0 || onlyCompareGenerated) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+ }
+ exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
+
+ function strcmp(aStr1, aStr2) {
+ if (aStr1 === aStr2) {
+ return 0;
+ }
+
+ if (aStr1 === null) {
+ return 1; // aStr2 !== null
+ }
+
+ if (aStr2 === null) {
+ return -1; // aStr1 !== null
+ }
+
+ if (aStr1 > aStr2) {
+ return 1;
+ }
+
+ return -1;
+ }
+
+ /**
+ * Comparator between two mappings with inflated source and name strings where
+ * the generated positions are compared.
+ */
+ function compareByGeneratedPositionsInflated(mappingA, mappingB) {
+ var cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp !== 0) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+ }
+ exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
+
+ /**
+ * Strip any JSON XSSI avoidance prefix from the string (as documented
+ * in the source maps specification), and then parse the string as
+ * JSON.
+ */
+ function parseSourceMapInput(str) {
+ return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
+ }
+ exports.parseSourceMapInput = parseSourceMapInput;
+
+ /**
+ * Compute the URL of a source given the the source root, the source's
+ * URL, and the source map's URL.
+ */
+ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
+ sourceURL = sourceURL || '';
+
+ if (sourceRoot) {
+ // This follows what Chrome does.
+ if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
+ sourceRoot += '/';
+ }
+ // The spec says:
+ // Line 4: An optional source root, useful for relocating source
+ // files on a server or removing repeated values in the
+ // “sources” entry. This value is prepended to the individual
+ // entries in the “source” field.
+ sourceURL = sourceRoot + sourceURL;
+ }
+
+ // Historically, SourceMapConsumer did not take the sourceMapURL as
+ // a parameter. This mode is still somewhat supported, which is why
+ // this code block is conditional. However, it's preferable to pass
+ // the source map URL to SourceMapConsumer, so that this function
+ // can implement the source URL resolution algorithm as outlined in
+ // the spec. This block is basically the equivalent of:
+ // new URL(sourceURL, sourceMapURL).toString()
+ // ... except it avoids using URL, which wasn't available in the
+ // older releases of node still supported by this library.
+ //
+ // The spec says:
+ // If the sources are not absolute URLs after prepending of the
+ // “sourceRoot”, the sources are resolved relative to the
+ // SourceMap (like resolving script src in a html document).
+ if (sourceMapURL) {
+ var parsed = urlParse(sourceMapURL);
+ if (!parsed) {
+ throw new Error("sourceMapURL could not be parsed");
+ }
+ if (parsed.path) {
+ // Strip the last path component, but keep the "/".
+ var index = parsed.path.lastIndexOf('/');
+ if (index >= 0) {
+ parsed.path = parsed.path.substring(0, index + 1);
+ }
+ }
+ sourceURL = join(urlGenerate(parsed), sourceURL);
+ }
+
+ return normalize(sourceURL);
+ }
+ exports.computeSourceURL = computeSourceURL;
+} (util$5));
+ return util$5;
+}
+
+var arraySet = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredArraySet;
+
+function requireArraySet () {
+ if (hasRequiredArraySet) return arraySet;
+ hasRequiredArraySet = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ var util = requireUtil();
+ var has = Object.prototype.hasOwnProperty;
+ var hasNativeMap = typeof Map !== "undefined";
+
+ /**
+ * A data structure which is a combination of an array and a set. Adding a new
+ * member is O(1), testing for membership is O(1), and finding the index of an
+ * element is O(1). Removing elements from the set is not supported. Only
+ * strings are supported for membership.
+ */
+ function ArraySet() {
+ this._array = [];
+ this._set = hasNativeMap ? new Map() : Object.create(null);
+ }
+
+ /**
+ * Static method for creating ArraySet instances from an existing array.
+ */
+ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
+ var set = new ArraySet();
+ for (var i = 0, len = aArray.length; i < len; i++) {
+ set.add(aArray[i], aAllowDuplicates);
+ }
+ return set;
+ };
+
+ /**
+ * Return how many unique items are in this ArraySet. If duplicates have been
+ * added, than those do not count towards the size.
+ *
+ * @returns Number
+ */
+ ArraySet.prototype.size = function ArraySet_size() {
+ return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
+ };
+
+ /**
+ * Add the given string to this set.
+ *
+ * @param String aStr
+ */
+ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
+ var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
+ var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
+ var idx = this._array.length;
+ if (!isDuplicate || aAllowDuplicates) {
+ this._array.push(aStr);
+ }
+ if (!isDuplicate) {
+ if (hasNativeMap) {
+ this._set.set(aStr, idx);
+ } else {
+ this._set[sStr] = idx;
+ }
+ }
+ };
+
+ /**
+ * Is the given string a member of this set?
+ *
+ * @param String aStr
+ */
+ ArraySet.prototype.has = function ArraySet_has(aStr) {
+ if (hasNativeMap) {
+ return this._set.has(aStr);
+ } else {
+ var sStr = util.toSetString(aStr);
+ return has.call(this._set, sStr);
+ }
+ };
+
+ /**
+ * What is the index of the given string in the array?
+ *
+ * @param String aStr
+ */
+ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
+ if (hasNativeMap) {
+ var idx = this._set.get(aStr);
+ if (idx >= 0) {
+ return idx;
+ }
+ } else {
+ var sStr = util.toSetString(aStr);
+ if (has.call(this._set, sStr)) {
+ return this._set[sStr];
+ }
+ }
+
+ throw new Error('"' + aStr + '" is not in the set.');
+ };
+
+ /**
+ * What is the element at the given index?
+ *
+ * @param Number aIdx
+ */
+ ArraySet.prototype.at = function ArraySet_at(aIdx) {
+ if (aIdx >= 0 && aIdx < this._array.length) {
+ return this._array[aIdx];
+ }
+ throw new Error('No element indexed by ' + aIdx);
+ };
+
+ /**
+ * Returns the array representation of this set (which has the proper indices
+ * indicated by indexOf). Note that this is a copy of the internal array used
+ * for storing the members so that no one can mess with internal state.
+ */
+ ArraySet.prototype.toArray = function ArraySet_toArray() {
+ return this._array.slice();
+ };
+
+ arraySet.ArraySet = ArraySet;
+ return arraySet;
+}
+
+var mappingList = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredMappingList;
+
+function requireMappingList () {
+ if (hasRequiredMappingList) return mappingList;
+ hasRequiredMappingList = 1;
+ /*
+ * Copyright 2014 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ var util = requireUtil();
+
+ /**
+ * Determine whether mappingB is after mappingA with respect to generated
+ * position.
+ */
+ function generatedPositionAfter(mappingA, mappingB) {
+ // Optimized for most common case
+ var lineA = mappingA.generatedLine;
+ var lineB = mappingB.generatedLine;
+ var columnA = mappingA.generatedColumn;
+ var columnB = mappingB.generatedColumn;
+ return lineB > lineA || lineB == lineA && columnB >= columnA ||
+ util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
+ }
+
+ /**
+ * A data structure to provide a sorted view of accumulated mappings in a
+ * performance conscious manner. It trades a neglibable overhead in general
+ * case for a large speedup in case of mappings being added in order.
+ */
+ function MappingList() {
+ this._array = [];
+ this._sorted = true;
+ // Serves as infimum
+ this._last = {generatedLine: -1, generatedColumn: 0};
+ }
+
+ /**
+ * Iterate through internal items. This method takes the same arguments that
+ * `Array.prototype.forEach` takes.
+ *
+ * NOTE: The order of the mappings is NOT guaranteed.
+ */
+ MappingList.prototype.unsortedForEach =
+ function MappingList_forEach(aCallback, aThisArg) {
+ this._array.forEach(aCallback, aThisArg);
+ };
+
+ /**
+ * Add the given source mapping.
+ *
+ * @param Object aMapping
+ */
+ MappingList.prototype.add = function MappingList_add(aMapping) {
+ if (generatedPositionAfter(this._last, aMapping)) {
+ this._last = aMapping;
+ this._array.push(aMapping);
+ } else {
+ this._sorted = false;
+ this._array.push(aMapping);
+ }
+ };
+
+ /**
+ * Returns the flat, sorted array of mappings. The mappings are sorted by
+ * generated position.
+ *
+ * WARNING: This method returns internal data without copying, for
+ * performance. The return value must NOT be mutated, and should be treated as
+ * an immutable borrow. If you want to take ownership, you must make your own
+ * copy.
+ */
+ MappingList.prototype.toArray = function MappingList_toArray() {
+ if (!this._sorted) {
+ this._array.sort(util.compareByGeneratedPositionsInflated);
+ this._sorted = true;
+ }
+ return this._array;
+ };
+
+ mappingList.MappingList = MappingList;
+ return mappingList;
+}
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredSourceMapGenerator;
+
+function requireSourceMapGenerator () {
+ if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
+ hasRequiredSourceMapGenerator = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ var base64VLQ = requireBase64Vlq();
+ var util = requireUtil();
+ var ArraySet = requireArraySet().ArraySet;
+ var MappingList = requireMappingList().MappingList;
+
+ /**
+ * An instance of the SourceMapGenerator represents a source map which is
+ * being built incrementally. You may pass an object with the following
+ * properties:
+ *
+ * - file: The filename of the generated source.
+ * - sourceRoot: A root for all relative URLs in this source map.
+ */
+ function SourceMapGenerator(aArgs) {
+ if (!aArgs) {
+ aArgs = {};
+ }
+ this._file = util.getArg(aArgs, 'file', null);
+ this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
+ this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
+ this._sources = new ArraySet();
+ this._names = new ArraySet();
+ this._mappings = new MappingList();
+ this._sourcesContents = null;
+ }
+
+ SourceMapGenerator.prototype._version = 3;
+
+ /**
+ * Creates a new SourceMapGenerator based on a SourceMapConsumer
+ *
+ * @param aSourceMapConsumer The SourceMap.
+ */
+ SourceMapGenerator.fromSourceMap =
+ function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
+ var sourceRoot = aSourceMapConsumer.sourceRoot;
+ var generator = new SourceMapGenerator({
+ file: aSourceMapConsumer.file,
+ sourceRoot: sourceRoot
+ });
+ aSourceMapConsumer.eachMapping(function (mapping) {
+ var newMapping = {
+ generated: {
+ line: mapping.generatedLine,
+ column: mapping.generatedColumn
+ }
+ };
+
+ if (mapping.source != null) {
+ newMapping.source = mapping.source;
+ if (sourceRoot != null) {
+ newMapping.source = util.relative(sourceRoot, newMapping.source);
+ }
+
+ newMapping.original = {
+ line: mapping.originalLine,
+ column: mapping.originalColumn
+ };
+
+ if (mapping.name != null) {
+ newMapping.name = mapping.name;
+ }
+ }
+
+ generator.addMapping(newMapping);
+ });
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var sourceRelative = sourceFile;
+ if (sourceRoot !== null) {
+ sourceRelative = util.relative(sourceRoot, sourceFile);
+ }
+
+ if (!generator._sources.has(sourceRelative)) {
+ generator._sources.add(sourceRelative);
+ }
+
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content != null) {
+ generator.setSourceContent(sourceFile, content);
+ }
+ });
+ return generator;
+ };
+
+ /**
+ * Add a single mapping from original source line and column to the generated
+ * source's line and column for this source map being created. The mapping
+ * object should have the following properties:
+ *
+ * - generated: An object with the generated line and column positions.
+ * - original: An object with the original line and column positions.
+ * - source: The original source file (relative to the sourceRoot).
+ * - name: An optional original token name for this mapping.
+ */
+ SourceMapGenerator.prototype.addMapping =
+ function SourceMapGenerator_addMapping(aArgs) {
+ var generated = util.getArg(aArgs, 'generated');
+ var original = util.getArg(aArgs, 'original', null);
+ var source = util.getArg(aArgs, 'source', null);
+ var name = util.getArg(aArgs, 'name', null);
+
+ if (!this._skipValidation) {
+ this._validateMapping(generated, original, source, name);
+ }
+
+ if (source != null) {
+ source = String(source);
+ if (!this._sources.has(source)) {
+ this._sources.add(source);
+ }
+ }
+
+ if (name != null) {
+ name = String(name);
+ if (!this._names.has(name)) {
+ this._names.add(name);
+ }
+ }
+
+ this._mappings.add({
+ generatedLine: generated.line,
+ generatedColumn: generated.column,
+ originalLine: original != null && original.line,
+ originalColumn: original != null && original.column,
+ source: source,
+ name: name
+ });
+ };
+
+ /**
+ * Set the source content for a source file.
+ */
+ SourceMapGenerator.prototype.setSourceContent =
+ function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
+ var source = aSourceFile;
+ if (this._sourceRoot != null) {
+ source = util.relative(this._sourceRoot, source);
+ }
+
+ if (aSourceContent != null) {
+ // Add the source content to the _sourcesContents map.
+ // Create a new _sourcesContents map if the property is null.
+ if (!this._sourcesContents) {
+ this._sourcesContents = Object.create(null);
+ }
+ this._sourcesContents[util.toSetString(source)] = aSourceContent;
+ } else if (this._sourcesContents) {
+ // Remove the source file from the _sourcesContents map.
+ // If the _sourcesContents map is empty, set the property to null.
+ delete this._sourcesContents[util.toSetString(source)];
+ if (Object.keys(this._sourcesContents).length === 0) {
+ this._sourcesContents = null;
+ }
+ }
+ };
+
+ /**
+ * Applies the mappings of a sub-source-map for a specific source file to the
+ * source map being generated. Each mapping to the supplied source file is
+ * rewritten using the supplied source map. Note: The resolution for the
+ * resulting mappings is the minimium of this map and the supplied map.
+ *
+ * @param aSourceMapConsumer The source map to be applied.
+ * @param aSourceFile Optional. The filename of the source file.
+ * If omitted, SourceMapConsumer's file property will be used.
+ * @param aSourceMapPath Optional. The dirname of the path to the source map
+ * to be applied. If relative, it is relative to the SourceMapConsumer.
+ * This parameter is needed when the two source maps aren't in the same
+ * directory, and the source map to be applied contains relative source
+ * paths. If so, those relative source paths need to be rewritten
+ * relative to the SourceMapGenerator.
+ */
+ SourceMapGenerator.prototype.applySourceMap =
+ function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
+ var sourceFile = aSourceFile;
+ // If aSourceFile is omitted, we will use the file property of the SourceMap
+ if (aSourceFile == null) {
+ if (aSourceMapConsumer.file == null) {
+ throw new Error(
+ 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
+ 'or the source map\'s "file" property. Both were omitted.'
+ );
+ }
+ sourceFile = aSourceMapConsumer.file;
+ }
+ var sourceRoot = this._sourceRoot;
+ // Make "sourceFile" relative if an absolute Url is passed.
+ if (sourceRoot != null) {
+ sourceFile = util.relative(sourceRoot, sourceFile);
+ }
+ // Applying the SourceMap can add and remove items from the sources and
+ // the names array.
+ var newSources = new ArraySet();
+ var newNames = new ArraySet();
+
+ // Find mappings for the "sourceFile"
+ this._mappings.unsortedForEach(function (mapping) {
+ if (mapping.source === sourceFile && mapping.originalLine != null) {
+ // Check if it can be mapped by the source map, then update the mapping.
+ var original = aSourceMapConsumer.originalPositionFor({
+ line: mapping.originalLine,
+ column: mapping.originalColumn
+ });
+ if (original.source != null) {
+ // Copy mapping
+ mapping.source = original.source;
+ if (aSourceMapPath != null) {
+ mapping.source = util.join(aSourceMapPath, mapping.source);
+ }
+ if (sourceRoot != null) {
+ mapping.source = util.relative(sourceRoot, mapping.source);
+ }
+ mapping.originalLine = original.line;
+ mapping.originalColumn = original.column;
+ if (original.name != null) {
+ mapping.name = original.name;
+ }
+ }
+ }
+
+ var source = mapping.source;
+ if (source != null && !newSources.has(source)) {
+ newSources.add(source);
+ }
+
+ var name = mapping.name;
+ if (name != null && !newNames.has(name)) {
+ newNames.add(name);
+ }
+
+ }, this);
+ this._sources = newSources;
+ this._names = newNames;
+
+ // Copy sourcesContents of applied map.
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content != null) {
+ if (aSourceMapPath != null) {
+ sourceFile = util.join(aSourceMapPath, sourceFile);
+ }
+ if (sourceRoot != null) {
+ sourceFile = util.relative(sourceRoot, sourceFile);
+ }
+ this.setSourceContent(sourceFile, content);
+ }
+ }, this);
+ };
+
+ /**
+ * A mapping can have one of the three levels of data:
+ *
+ * 1. Just the generated position.
+ * 2. The Generated position, original position, and original source.
+ * 3. Generated and original position, original source, as well as a name
+ * token.
+ *
+ * To maintain consistency, we validate that any new mapping being added falls
+ * in to one of these categories.
+ */
+ SourceMapGenerator.prototype._validateMapping =
+ function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
+ aName) {
+ // When aOriginal is truthy but has empty values for .line and .column,
+ // it is most likely a programmer error. In this case we throw a very
+ // specific error message to try to guide them the right way.
+ // For example: https://github.com/Polymer/polymer-bundler/pull/519
+ if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
+ throw new Error(
+ 'original.line and original.column are not numbers -- you probably meant to omit ' +
+ 'the original mapping entirely and only map the generated position. If so, pass ' +
+ 'null for the original mapping instead of an object with empty or null values.'
+ );
+ }
+
+ if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
+ && aGenerated.line > 0 && aGenerated.column >= 0
+ && !aOriginal && !aSource && !aName) {
+ // Case 1.
+ return;
+ }
+ else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
+ && aOriginal && 'line' in aOriginal && 'column' in aOriginal
+ && aGenerated.line > 0 && aGenerated.column >= 0
+ && aOriginal.line > 0 && aOriginal.column >= 0
+ && aSource) {
+ // Cases 2 and 3.
+ return;
+ }
+ else {
+ throw new Error('Invalid mapping: ' + JSON.stringify({
+ generated: aGenerated,
+ source: aSource,
+ original: aOriginal,
+ name: aName
+ }));
+ }
+ };
+
+ /**
+ * Serialize the accumulated mappings in to the stream of base 64 VLQs
+ * specified by the source map format.
+ */
+ SourceMapGenerator.prototype._serializeMappings =
+ function SourceMapGenerator_serializeMappings() {
+ var previousGeneratedColumn = 0;
+ var previousGeneratedLine = 1;
+ var previousOriginalColumn = 0;
+ var previousOriginalLine = 0;
+ var previousName = 0;
+ var previousSource = 0;
+ var result = '';
+ var next;
+ var mapping;
+ var nameIdx;
+ var sourceIdx;
+
+ var mappings = this._mappings.toArray();
+ for (var i = 0, len = mappings.length; i < len; i++) {
+ mapping = mappings[i];
+ next = '';
+
+ if (mapping.generatedLine !== previousGeneratedLine) {
+ previousGeneratedColumn = 0;
+ while (mapping.generatedLine !== previousGeneratedLine) {
+ next += ';';
+ previousGeneratedLine++;
+ }
+ }
+ else {
+ if (i > 0) {
+ if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
+ continue;
+ }
+ next += ',';
+ }
+ }
+
+ next += base64VLQ.encode(mapping.generatedColumn
+ - previousGeneratedColumn);
+ previousGeneratedColumn = mapping.generatedColumn;
+
+ if (mapping.source != null) {
+ sourceIdx = this._sources.indexOf(mapping.source);
+ next += base64VLQ.encode(sourceIdx - previousSource);
+ previousSource = sourceIdx;
+
+ // lines are stored 0-based in SourceMap spec version 3
+ next += base64VLQ.encode(mapping.originalLine - 1
+ - previousOriginalLine);
+ previousOriginalLine = mapping.originalLine - 1;
+
+ next += base64VLQ.encode(mapping.originalColumn
+ - previousOriginalColumn);
+ previousOriginalColumn = mapping.originalColumn;
+
+ if (mapping.name != null) {
+ nameIdx = this._names.indexOf(mapping.name);
+ next += base64VLQ.encode(nameIdx - previousName);
+ previousName = nameIdx;
+ }
+ }
+
+ result += next;
+ }
+
+ return result;
+ };
+
+ SourceMapGenerator.prototype._generateSourcesContent =
+ function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
+ return aSources.map(function (source) {
+ if (!this._sourcesContents) {
+ return null;
+ }
+ if (aSourceRoot != null) {
+ source = util.relative(aSourceRoot, source);
+ }
+ var key = util.toSetString(source);
+ return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
+ ? this._sourcesContents[key]
+ : null;
+ }, this);
+ };
+
+ /**
+ * Externalize the source map.
+ */
+ SourceMapGenerator.prototype.toJSON =
+ function SourceMapGenerator_toJSON() {
+ var map = {
+ version: this._version,
+ sources: this._sources.toArray(),
+ names: this._names.toArray(),
+ mappings: this._serializeMappings()
+ };
+ if (this._file != null) {
+ map.file = this._file;
+ }
+ if (this._sourceRoot != null) {
+ map.sourceRoot = this._sourceRoot;
+ }
+ if (this._sourcesContents) {
+ map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
+ }
+
+ return map;
+ };
+
+ /**
+ * Render the source map being generated to a string.
+ */
+ SourceMapGenerator.prototype.toString =
+ function SourceMapGenerator_toString() {
+ return JSON.stringify(this.toJSON());
+ };
+
+ sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
+ return sourceMapGenerator;
+}
+
+var sourceMapConsumer = {};
+
+var binarySearch = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredBinarySearch;
+
+function requireBinarySearch () {
+ if (hasRequiredBinarySearch) return binarySearch;
+ hasRequiredBinarySearch = 1;
+ (function (exports) {
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ exports.GREATEST_LOWER_BOUND = 1;
+ exports.LEAST_UPPER_BOUND = 2;
+
+ /**
+ * Recursive implementation of binary search.
+ *
+ * @param aLow Indices here and lower do not contain the needle.
+ * @param aHigh Indices here and higher do not contain the needle.
+ * @param aNeedle The element being searched for.
+ * @param aHaystack The non-empty array being searched.
+ * @param aCompare Function which takes two elements and returns -1, 0, or 1.
+ * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
+ * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ */
+ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
+ // This function terminates when one of the following is true:
+ //
+ // 1. We find the exact element we are looking for.
+ //
+ // 2. We did not find the exact element, but we can return the index of
+ // the next-closest element.
+ //
+ // 3. We did not find the exact element, and there is no next-closest
+ // element than the one we are searching for, so we return -1.
+ var mid = Math.floor((aHigh - aLow) / 2) + aLow;
+ var cmp = aCompare(aNeedle, aHaystack[mid], true);
+ if (cmp === 0) {
+ // Found the element we are looking for.
+ return mid;
+ }
+ else if (cmp > 0) {
+ // Our needle is greater than aHaystack[mid].
+ if (aHigh - mid > 1) {
+ // The element is in the upper half.
+ return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
+ }
+
+ // The exact needle element was not found in this haystack. Determine if
+ // we are in termination case (3) or (2) and return the appropriate thing.
+ if (aBias == exports.LEAST_UPPER_BOUND) {
+ return aHigh < aHaystack.length ? aHigh : -1;
+ } else {
+ return mid;
+ }
+ }
+ else {
+ // Our needle is less than aHaystack[mid].
+ if (mid - aLow > 1) {
+ // The element is in the lower half.
+ return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
+ }
+
+ // we are in termination case (3) or (2) and return the appropriate thing.
+ if (aBias == exports.LEAST_UPPER_BOUND) {
+ return mid;
+ } else {
+ return aLow < 0 ? -1 : aLow;
+ }
+ }
+ }
+
+ /**
+ * This is an implementation of binary search which will always try and return
+ * the index of the closest element if there is no exact hit. This is because
+ * mappings between original and generated line/col pairs are single points,
+ * and there is an implicit region between each of them, so a miss just means
+ * that you aren't on the very start of a region.
+ *
+ * @param aNeedle The element you are looking for.
+ * @param aHaystack The array that is being searched.
+ * @param aCompare A function which takes the needle and an element in the
+ * array and returns -1, 0, or 1 depending on whether the needle is less
+ * than, equal to, or greater than the element, respectively.
+ * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
+ * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
+ */
+ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
+ if (aHaystack.length === 0) {
+ return -1;
+ }
+
+ var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
+ aCompare, aBias || exports.GREATEST_LOWER_BOUND);
+ if (index < 0) {
+ return -1;
+ }
+
+ // We have found either the exact element, or the next-closest element than
+ // the one we are searching for. However, there may be more than one such
+ // element. Make sure we always return the smallest of these.
+ while (index - 1 >= 0) {
+ if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
+ break;
+ }
+ --index;
+ }
+
+ return index;
+ };
+} (binarySearch));
+ return binarySearch;
+}
+
+var quickSort = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredQuickSort;
+
+function requireQuickSort () {
+ if (hasRequiredQuickSort) return quickSort;
+ hasRequiredQuickSort = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ // It turns out that some (most?) JavaScript engines don't self-host
+ // `Array.prototype.sort`. This makes sense because C++ will likely remain
+ // faster than JS when doing raw CPU-intensive sorting. However, when using a
+ // custom comparator function, calling back and forth between the VM's C++ and
+ // JIT'd JS is rather slow *and* loses JIT type information, resulting in
+ // worse generated code for the comparator function than would be optimal. In
+ // fact, when sorting with a comparator, these costs outweigh the benefits of
+ // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
+ // a ~3500ms mean speed-up in `bench/bench.html`.
+
+ /**
+ * Swap the elements indexed by `x` and `y` in the array `ary`.
+ *
+ * @param {Array} ary
+ * The array.
+ * @param {Number} x
+ * The index of the first item.
+ * @param {Number} y
+ * The index of the second item.
+ */
+ function swap(ary, x, y) {
+ var temp = ary[x];
+ ary[x] = ary[y];
+ ary[y] = temp;
+ }
+
+ /**
+ * Returns a random integer within the range `low .. high` inclusive.
+ *
+ * @param {Number} low
+ * The lower bound on the range.
+ * @param {Number} high
+ * The upper bound on the range.
+ */
+ function randomIntInRange(low, high) {
+ return Math.round(low + (Math.random() * (high - low)));
+ }
+
+ /**
+ * The Quick Sort algorithm.
+ *
+ * @param {Array} ary
+ * An array to sort.
+ * @param {function} comparator
+ * Function to use to compare two items.
+ * @param {Number} p
+ * Start index of the array
+ * @param {Number} r
+ * End index of the array
+ */
+ function doQuickSort(ary, comparator, p, r) {
+ // If our lower bound is less than our upper bound, we (1) partition the
+ // array into two pieces and (2) recurse on each half. If it is not, this is
+ // the empty array and our base case.
+
+ if (p < r) {
+ // (1) Partitioning.
+ //
+ // The partitioning chooses a pivot between `p` and `r` and moves all
+ // elements that are less than or equal to the pivot to the before it, and
+ // all the elements that are greater than it after it. The effect is that
+ // once partition is done, the pivot is in the exact place it will be when
+ // the array is put in sorted order, and it will not need to be moved
+ // again. This runs in O(n) time.
+
+ // Always choose a random pivot so that an input array which is reverse
+ // sorted does not cause O(n^2) running time.
+ var pivotIndex = randomIntInRange(p, r);
+ var i = p - 1;
+
+ swap(ary, pivotIndex, r);
+ var pivot = ary[r];
+
+ // Immediately after `j` is incremented in this loop, the following hold
+ // true:
+ //
+ // * Every element in `ary[p .. i]` is less than or equal to the pivot.
+ //
+ // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
+ for (var j = p; j < r; j++) {
+ if (comparator(ary[j], pivot) <= 0) {
+ i += 1;
+ swap(ary, i, j);
+ }
+ }
+
+ swap(ary, i + 1, j);
+ var q = i + 1;
+
+ // (2) Recurse on each half.
+
+ doQuickSort(ary, comparator, p, q - 1);
+ doQuickSort(ary, comparator, q + 1, r);
+ }
+ }
+
+ /**
+ * Sort the given array in-place with the given comparator function.
+ *
+ * @param {Array} ary
+ * An array to sort.
+ * @param {function} comparator
+ * Function to use to compare two items.
+ */
+ quickSort.quickSort = function (ary, comparator) {
+ doQuickSort(ary, comparator, 0, ary.length - 1);
+ };
+ return quickSort;
+}
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredSourceMapConsumer;
+
+function requireSourceMapConsumer () {
+ if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
+ hasRequiredSourceMapConsumer = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ var util = requireUtil();
+ var binarySearch = requireBinarySearch();
+ var ArraySet = requireArraySet().ArraySet;
+ var base64VLQ = requireBase64Vlq();
+ var quickSort = requireQuickSort().quickSort;
+
+ function SourceMapConsumer(aSourceMap, aSourceMapURL) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = util.parseSourceMapInput(aSourceMap);
+ }
+
+ return sourceMap.sections != null
+ ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
+ : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
+ }
+
+ SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
+ return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
+ };
+
+ /**
+ * The version of the source mapping spec that we are consuming.
+ */
+ SourceMapConsumer.prototype._version = 3;
+
+ // `__generatedMappings` and `__originalMappings` are arrays that hold the
+ // parsed mapping coordinates from the source map's "mappings" attribute. They
+ // are lazily instantiated, accessed via the `_generatedMappings` and
+ // `_originalMappings` getters respectively, and we only parse the mappings
+ // and create these arrays once queried for a source location. We jump through
+ // these hoops because there can be many thousands of mappings, and parsing
+ // them is expensive, so we only want to do it if we must.
+ //
+ // Each object in the arrays is of the form:
+ //
+ // {
+ // generatedLine: The line number in the generated code,
+ // generatedColumn: The column number in the generated code,
+ // source: The path to the original source file that generated this
+ // chunk of code,
+ // originalLine: The line number in the original source that
+ // corresponds to this chunk of generated code,
+ // originalColumn: The column number in the original source that
+ // corresponds to this chunk of generated code,
+ // name: The name of the original symbol which generated this chunk of
+ // code.
+ // }
+ //
+ // All properties except for `generatedLine` and `generatedColumn` can be
+ // `null`.
+ //
+ // `_generatedMappings` is ordered by the generated positions.
+ //
+ // `_originalMappings` is ordered by the original positions.
+
+ SourceMapConsumer.prototype.__generatedMappings = null;
+ Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ if (!this.__generatedMappings) {
+ this._parseMappings(this._mappings, this.sourceRoot);
+ }
+
+ return this.__generatedMappings;
+ }
+ });
+
+ SourceMapConsumer.prototype.__originalMappings = null;
+ Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ if (!this.__originalMappings) {
+ this._parseMappings(this._mappings, this.sourceRoot);
+ }
+
+ return this.__originalMappings;
+ }
+ });
+
+ SourceMapConsumer.prototype._charIsMappingSeparator =
+ function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
+ var c = aStr.charAt(index);
+ return c === ";" || c === ",";
+ };
+
+ /**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+ SourceMapConsumer.prototype._parseMappings =
+ function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ throw new Error("Subclasses must implement _parseMappings");
+ };
+
+ SourceMapConsumer.GENERATED_ORDER = 1;
+ SourceMapConsumer.ORIGINAL_ORDER = 2;
+
+ SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
+ SourceMapConsumer.LEAST_UPPER_BOUND = 2;
+
+ /**
+ * Iterate over each mapping between an original source/line/column and a
+ * generated line/column in this source map.
+ *
+ * @param Function aCallback
+ * The function that is called with each mapping.
+ * @param Object aContext
+ * Optional. If specified, this object will be the value of `this` every
+ * time that `aCallback` is called.
+ * @param aOrder
+ * Either `SourceMapConsumer.GENERATED_ORDER` or
+ * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
+ * iterate over the mappings sorted by the generated file's line/column
+ * order or the original's source/line/column order, respectively. Defaults to
+ * `SourceMapConsumer.GENERATED_ORDER`.
+ */
+ SourceMapConsumer.prototype.eachMapping =
+ function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
+ var context = aContext || null;
+ var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
+
+ var mappings;
+ switch (order) {
+ case SourceMapConsumer.GENERATED_ORDER:
+ mappings = this._generatedMappings;
+ break;
+ case SourceMapConsumer.ORIGINAL_ORDER:
+ mappings = this._originalMappings;
+ break;
+ default:
+ throw new Error("Unknown order of iteration.");
+ }
+
+ var sourceRoot = this.sourceRoot;
+ mappings.map(function (mapping) {
+ var source = mapping.source === null ? null : this._sources.at(mapping.source);
+ source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
+ return {
+ source: source,
+ generatedLine: mapping.generatedLine,
+ generatedColumn: mapping.generatedColumn,
+ originalLine: mapping.originalLine,
+ originalColumn: mapping.originalColumn,
+ name: mapping.name === null ? null : this._names.at(mapping.name)
+ };
+ }, this).forEach(aCallback, context);
+ };
+
+ /**
+ * Returns all generated line and column information for the original source,
+ * line, and column provided. If no column is provided, returns all mappings
+ * corresponding to a either the line we are searching for or the next
+ * closest line that has any mappings. Otherwise, returns all mappings
+ * corresponding to the given line and either the column we are searching for
+ * or the next closest column that has any offsets.
+ *
+ * The only argument is an object with the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source. The line number is 1-based.
+ * - column: Optional. the column number in the original source.
+ * The column number is 0-based.
+ *
+ * and an array of objects is returned, each with the following properties:
+ *
+ * - line: The line number in the generated source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the generated source, or null.
+ * The column number is 0-based.
+ */
+ SourceMapConsumer.prototype.allGeneratedPositionsFor =
+ function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
+ var line = util.getArg(aArgs, 'line');
+
+ // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
+ // returns the index of the closest mapping less than the needle. By
+ // setting needle.originalColumn to 0, we thus find the last mapping for
+ // the given line, provided such a mapping exists.
+ var needle = {
+ source: util.getArg(aArgs, 'source'),
+ originalLine: line,
+ originalColumn: util.getArg(aArgs, 'column', 0)
+ };
+
+ needle.source = this._findSourceIndex(needle.source);
+ if (needle.source < 0) {
+ return [];
+ }
+
+ var mappings = [];
+
+ var index = this._findMapping(needle,
+ this._originalMappings,
+ "originalLine",
+ "originalColumn",
+ util.compareByOriginalPositions,
+ binarySearch.LEAST_UPPER_BOUND);
+ if (index >= 0) {
+ var mapping = this._originalMappings[index];
+
+ if (aArgs.column === undefined) {
+ var originalLine = mapping.originalLine;
+
+ // Iterate until either we run out of mappings, or we run into
+ // a mapping for a different line than the one we found. Since
+ // mappings are sorted, this is guaranteed to find all mappings for
+ // the line we found.
+ while (mapping && mapping.originalLine === originalLine) {
+ mappings.push({
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null),
+ lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
+ });
+
+ mapping = this._originalMappings[++index];
+ }
+ } else {
+ var originalColumn = mapping.originalColumn;
+
+ // Iterate until either we run out of mappings, or we run into
+ // a mapping for a different line than the one we were searching for.
+ // Since mappings are sorted, this is guaranteed to find all mappings for
+ // the line we are searching for.
+ while (mapping &&
+ mapping.originalLine === line &&
+ mapping.originalColumn == originalColumn) {
+ mappings.push({
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null),
+ lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
+ });
+
+ mapping = this._originalMappings[++index];
+ }
+ }
+ }
+
+ return mappings;
+ };
+
+ sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
+
+ /**
+ * A BasicSourceMapConsumer instance represents a parsed source map which we can
+ * query for information about the original file positions by giving it a file
+ * position in the generated source.
+ *
+ * The first parameter is the raw source map (either as a JSON string, or
+ * already parsed to an object). According to the spec, source maps have the
+ * following attributes:
+ *
+ * - version: Which version of the source map spec this map is following.
+ * - sources: An array of URLs to the original source files.
+ * - names: An array of identifiers which can be referrenced by individual mappings.
+ * - sourceRoot: Optional. The URL root from which all sources are relative.
+ * - sourcesContent: Optional. An array of contents of the original source files.
+ * - mappings: A string of base64 VLQs which contain the actual mappings.
+ * - file: Optional. The generated file this source map is associated with.
+ *
+ * Here is an example source map, taken from the source map spec[0]:
+ *
+ * {
+ * version : 3,
+ * file: "out.js",
+ * sourceRoot : "",
+ * sources: ["foo.js", "bar.js"],
+ * names: ["src", "maps", "are", "fun"],
+ * mappings: "AA,AB;;ABCDE;"
+ * }
+ *
+ * The second parameter, if given, is a string whose value is the URL
+ * at which the source map was found. This URL is used to compute the
+ * sources array.
+ *
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
+ */
+ function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = util.parseSourceMapInput(aSourceMap);
+ }
+
+ var version = util.getArg(sourceMap, 'version');
+ var sources = util.getArg(sourceMap, 'sources');
+ // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
+ // requires the array) to play nice here.
+ var names = util.getArg(sourceMap, 'names', []);
+ var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
+ var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
+ var mappings = util.getArg(sourceMap, 'mappings');
+ var file = util.getArg(sourceMap, 'file', null);
+
+ // Once again, Sass deviates from the spec and supplies the version as a
+ // string rather than a number, so we use loose equality checking here.
+ if (version != this._version) {
+ throw new Error('Unsupported version: ' + version);
+ }
+
+ if (sourceRoot) {
+ sourceRoot = util.normalize(sourceRoot);
+ }
+
+ sources = sources
+ .map(String)
+ // Some source maps produce relative source paths like "./foo.js" instead of
+ // "foo.js". Normalize these first so that future comparisons will succeed.
+ // See bugzil.la/1090768.
+ .map(util.normalize)
+ // Always ensure that absolute sources are internally stored relative to
+ // the source root, if the source root is absolute. Not doing this would
+ // be particularly problematic when the source root is a prefix of the
+ // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
+ .map(function (source) {
+ return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
+ ? util.relative(sourceRoot, source)
+ : source;
+ });
+
+ // Pass `true` below to allow duplicate names and sources. While source maps
+ // are intended to be compressed and deduplicated, the TypeScript compiler
+ // sometimes generates source maps with duplicates in them. See Github issue
+ // #72 and bugzil.la/889492.
+ this._names = ArraySet.fromArray(names.map(String), true);
+ this._sources = ArraySet.fromArray(sources, true);
+
+ this._absoluteSources = this._sources.toArray().map(function (s) {
+ return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
+ });
+
+ this.sourceRoot = sourceRoot;
+ this.sourcesContent = sourcesContent;
+ this._mappings = mappings;
+ this._sourceMapURL = aSourceMapURL;
+ this.file = file;
+ }
+
+ BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
+ BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
+
+ /**
+ * Utility function to find the index of a source. Returns -1 if not
+ * found.
+ */
+ BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
+ var relativeSource = aSource;
+ if (this.sourceRoot != null) {
+ relativeSource = util.relative(this.sourceRoot, relativeSource);
+ }
+
+ if (this._sources.has(relativeSource)) {
+ return this._sources.indexOf(relativeSource);
+ }
+
+ // Maybe aSource is an absolute URL as returned by |sources|. In
+ // this case we can't simply undo the transform.
+ var i;
+ for (i = 0; i < this._absoluteSources.length; ++i) {
+ if (this._absoluteSources[i] == aSource) {
+ return i;
+ }
+ }
+
+ return -1;
+ };
+
+ /**
+ * Create a BasicSourceMapConsumer from a SourceMapGenerator.
+ *
+ * @param SourceMapGenerator aSourceMap
+ * The source map that will be consumed.
+ * @param String aSourceMapURL
+ * The URL at which the source map can be found (optional)
+ * @returns BasicSourceMapConsumer
+ */
+ BasicSourceMapConsumer.fromSourceMap =
+ function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
+ var smc = Object.create(BasicSourceMapConsumer.prototype);
+
+ var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
+ var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
+ smc.sourceRoot = aSourceMap._sourceRoot;
+ smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
+ smc.sourceRoot);
+ smc.file = aSourceMap._file;
+ smc._sourceMapURL = aSourceMapURL;
+ smc._absoluteSources = smc._sources.toArray().map(function (s) {
+ return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
+ });
+
+ // Because we are modifying the entries (by converting string sources and
+ // names to indices into the sources and names ArraySets), we have to make
+ // a copy of the entry or else bad things happen. Shared mutable state
+ // strikes again! See github issue #191.
+
+ var generatedMappings = aSourceMap._mappings.toArray().slice();
+ var destGeneratedMappings = smc.__generatedMappings = [];
+ var destOriginalMappings = smc.__originalMappings = [];
+
+ for (var i = 0, length = generatedMappings.length; i < length; i++) {
+ var srcMapping = generatedMappings[i];
+ var destMapping = new Mapping;
+ destMapping.generatedLine = srcMapping.generatedLine;
+ destMapping.generatedColumn = srcMapping.generatedColumn;
+
+ if (srcMapping.source) {
+ destMapping.source = sources.indexOf(srcMapping.source);
+ destMapping.originalLine = srcMapping.originalLine;
+ destMapping.originalColumn = srcMapping.originalColumn;
+
+ if (srcMapping.name) {
+ destMapping.name = names.indexOf(srcMapping.name);
+ }
+
+ destOriginalMappings.push(destMapping);
+ }
+
+ destGeneratedMappings.push(destMapping);
+ }
+
+ quickSort(smc.__originalMappings, util.compareByOriginalPositions);
+
+ return smc;
+ };
+
+ /**
+ * The version of the source mapping spec that we are consuming.
+ */
+ BasicSourceMapConsumer.prototype._version = 3;
+
+ /**
+ * The list of original sources.
+ */
+ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
+ get: function () {
+ return this._absoluteSources.slice();
+ }
+ });
+
+ /**
+ * Provide the JIT with a nice shape / hidden class.
+ */
+ function Mapping() {
+ this.generatedLine = 0;
+ this.generatedColumn = 0;
+ this.source = null;
+ this.originalLine = null;
+ this.originalColumn = null;
+ this.name = null;
+ }
+
+ /**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+ BasicSourceMapConsumer.prototype._parseMappings =
+ function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ var generatedLine = 1;
+ var previousGeneratedColumn = 0;
+ var previousOriginalLine = 0;
+ var previousOriginalColumn = 0;
+ var previousSource = 0;
+ var previousName = 0;
+ var length = aStr.length;
+ var index = 0;
+ var cachedSegments = {};
+ var temp = {};
+ var originalMappings = [];
+ var generatedMappings = [];
+ var mapping, str, segment, end, value;
+
+ while (index < length) {
+ if (aStr.charAt(index) === ';') {
+ generatedLine++;
+ index++;
+ previousGeneratedColumn = 0;
+ }
+ else if (aStr.charAt(index) === ',') {
+ index++;
+ }
+ else {
+ mapping = new Mapping();
+ mapping.generatedLine = generatedLine;
+
+ // Because each offset is encoded relative to the previous one,
+ // many segments often have the same encoding. We can exploit this
+ // fact by caching the parsed variable length fields of each segment,
+ // allowing us to avoid a second parse if we encounter the same
+ // segment again.
+ for (end = index; end < length; end++) {
+ if (this._charIsMappingSeparator(aStr, end)) {
+ break;
+ }
+ }
+ str = aStr.slice(index, end);
+
+ segment = cachedSegments[str];
+ if (segment) {
+ index += str.length;
+ } else {
+ segment = [];
+ while (index < end) {
+ base64VLQ.decode(aStr, index, temp);
+ value = temp.value;
+ index = temp.rest;
+ segment.push(value);
+ }
+
+ if (segment.length === 2) {
+ throw new Error('Found a source, but no line and column');
+ }
+
+ if (segment.length === 3) {
+ throw new Error('Found a source and line, but no column');
+ }
+
+ cachedSegments[str] = segment;
+ }
+
+ // Generated column.
+ mapping.generatedColumn = previousGeneratedColumn + segment[0];
+ previousGeneratedColumn = mapping.generatedColumn;
+
+ if (segment.length > 1) {
+ // Original source.
+ mapping.source = previousSource + segment[1];
+ previousSource += segment[1];
+
+ // Original line.
+ mapping.originalLine = previousOriginalLine + segment[2];
+ previousOriginalLine = mapping.originalLine;
+ // Lines are stored 0-based
+ mapping.originalLine += 1;
+
+ // Original column.
+ mapping.originalColumn = previousOriginalColumn + segment[3];
+ previousOriginalColumn = mapping.originalColumn;
+
+ if (segment.length > 4) {
+ // Original name.
+ mapping.name = previousName + segment[4];
+ previousName += segment[4];
+ }
+ }
+
+ generatedMappings.push(mapping);
+ if (typeof mapping.originalLine === 'number') {
+ originalMappings.push(mapping);
+ }
+ }
+ }
+
+ quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
+ this.__generatedMappings = generatedMappings;
+
+ quickSort(originalMappings, util.compareByOriginalPositions);
+ this.__originalMappings = originalMappings;
+ };
+
+ /**
+ * Find the mapping that best matches the hypothetical "needle" mapping that
+ * we are searching for in the given "haystack" of mappings.
+ */
+ BasicSourceMapConsumer.prototype._findMapping =
+ function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
+ aColumnName, aComparator, aBias) {
+ // To return the position we are searching for, we must first find the
+ // mapping for the given position and then return the opposite position it
+ // points to. Because the mappings are sorted, we can use binary search to
+ // find the best mapping.
+
+ if (aNeedle[aLineName] <= 0) {
+ throw new TypeError('Line must be greater than or equal to 1, got '
+ + aNeedle[aLineName]);
+ }
+ if (aNeedle[aColumnName] < 0) {
+ throw new TypeError('Column must be greater than or equal to 0, got '
+ + aNeedle[aColumnName]);
+ }
+
+ return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
+ };
+
+ /**
+ * Compute the last column for each generated mapping. The last column is
+ * inclusive.
+ */
+ BasicSourceMapConsumer.prototype.computeColumnSpans =
+ function SourceMapConsumer_computeColumnSpans() {
+ for (var index = 0; index < this._generatedMappings.length; ++index) {
+ var mapping = this._generatedMappings[index];
+
+ // Mappings do not contain a field for the last generated columnt. We
+ // can come up with an optimistic estimate, however, by assuming that
+ // mappings are contiguous (i.e. given two consecutive mappings, the
+ // first mapping ends where the second one starts).
+ if (index + 1 < this._generatedMappings.length) {
+ var nextMapping = this._generatedMappings[index + 1];
+
+ if (mapping.generatedLine === nextMapping.generatedLine) {
+ mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
+ continue;
+ }
+ }
+
+ // The last mapping for each line spans the entire line.
+ mapping.lastGeneratedColumn = Infinity;
+ }
+ };
+
+ /**
+ * Returns the original source, line, and column information for the generated
+ * source's line and column positions provided. The only argument is an object
+ * with the following properties:
+ *
+ * - line: The line number in the generated source. The line number
+ * is 1-based.
+ * - column: The column number in the generated source. The column
+ * number is 0-based.
+ * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
+ * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - source: The original source file, or null.
+ * - line: The line number in the original source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the original source, or null. The
+ * column number is 0-based.
+ * - name: The original identifier, or null.
+ */
+ BasicSourceMapConsumer.prototype.originalPositionFor =
+ function SourceMapConsumer_originalPositionFor(aArgs) {
+ var needle = {
+ generatedLine: util.getArg(aArgs, 'line'),
+ generatedColumn: util.getArg(aArgs, 'column')
+ };
+
+ var index = this._findMapping(
+ needle,
+ this._generatedMappings,
+ "generatedLine",
+ "generatedColumn",
+ util.compareByGeneratedPositionsDeflated,
+ util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
+ );
+
+ if (index >= 0) {
+ var mapping = this._generatedMappings[index];
+
+ if (mapping.generatedLine === needle.generatedLine) {
+ var source = util.getArg(mapping, 'source', null);
+ if (source !== null) {
+ source = this._sources.at(source);
+ source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
+ }
+ var name = util.getArg(mapping, 'name', null);
+ if (name !== null) {
+ name = this._names.at(name);
+ }
+ return {
+ source: source,
+ line: util.getArg(mapping, 'originalLine', null),
+ column: util.getArg(mapping, 'originalColumn', null),
+ name: name
+ };
+ }
+ }
+
+ return {
+ source: null,
+ line: null,
+ column: null,
+ name: null
+ };
+ };
+
+ /**
+ * Return true if we have the source content for every source in the source
+ * map, false otherwise.
+ */
+ BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
+ function BasicSourceMapConsumer_hasContentsOfAllSources() {
+ if (!this.sourcesContent) {
+ return false;
+ }
+ return this.sourcesContent.length >= this._sources.size() &&
+ !this.sourcesContent.some(function (sc) { return sc == null; });
+ };
+
+ /**
+ * Returns the original source content. The only argument is the url of the
+ * original source file. Returns null if no original source content is
+ * available.
+ */
+ BasicSourceMapConsumer.prototype.sourceContentFor =
+ function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
+ if (!this.sourcesContent) {
+ return null;
+ }
+
+ var index = this._findSourceIndex(aSource);
+ if (index >= 0) {
+ return this.sourcesContent[index];
+ }
+
+ var relativeSource = aSource;
+ if (this.sourceRoot != null) {
+ relativeSource = util.relative(this.sourceRoot, relativeSource);
+ }
+
+ var url;
+ if (this.sourceRoot != null
+ && (url = util.urlParse(this.sourceRoot))) {
+ // XXX: file:// URIs and absolute paths lead to unexpected behavior for
+ // many users. We can help them out when they expect file:// URIs to
+ // behave like it would if they were running a local HTTP server. See
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
+ var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
+ if (url.scheme == "file"
+ && this._sources.has(fileUriAbsPath)) {
+ return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
+ }
+
+ if ((!url.path || url.path == "/")
+ && this._sources.has("/" + relativeSource)) {
+ return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
+ }
+ }
+
+ // This function is used recursively from
+ // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
+ // don't want to throw if we can't find the source - we just want to
+ // return null, so we provide a flag to exit gracefully.
+ if (nullOnMissing) {
+ return null;
+ }
+ else {
+ throw new Error('"' + relativeSource + '" is not in the SourceMap.');
+ }
+ };
+
+ /**
+ * Returns the generated line and column information for the original source,
+ * line, and column positions provided. The only argument is an object with
+ * the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source. The line number
+ * is 1-based.
+ * - column: The column number in the original source. The column
+ * number is 0-based.
+ * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
+ * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
+ * closest element that is smaller than or greater than the one we are
+ * searching for, respectively, if the exact element cannot be found.
+ * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - line: The line number in the generated source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the generated source, or null.
+ * The column number is 0-based.
+ */
+ BasicSourceMapConsumer.prototype.generatedPositionFor =
+ function SourceMapConsumer_generatedPositionFor(aArgs) {
+ var source = util.getArg(aArgs, 'source');
+ source = this._findSourceIndex(source);
+ if (source < 0) {
+ return {
+ line: null,
+ column: null,
+ lastColumn: null
+ };
+ }
+
+ var needle = {
+ source: source,
+ originalLine: util.getArg(aArgs, 'line'),
+ originalColumn: util.getArg(aArgs, 'column')
+ };
+
+ var index = this._findMapping(
+ needle,
+ this._originalMappings,
+ "originalLine",
+ "originalColumn",
+ util.compareByOriginalPositions,
+ util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
+ );
+
+ if (index >= 0) {
+ var mapping = this._originalMappings[index];
+
+ if (mapping.source === needle.source) {
+ return {
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null),
+ lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
+ };
+ }
+ }
+
+ return {
+ line: null,
+ column: null,
+ lastColumn: null
+ };
+ };
+
+ sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
+
+ /**
+ * An IndexedSourceMapConsumer instance represents a parsed source map which
+ * we can query for information. It differs from BasicSourceMapConsumer in
+ * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
+ * input.
+ *
+ * The first parameter is a raw source map (either as a JSON string, or already
+ * parsed to an object). According to the spec for indexed source maps, they
+ * have the following attributes:
+ *
+ * - version: Which version of the source map spec this map is following.
+ * - file: Optional. The generated file this source map is associated with.
+ * - sections: A list of section definitions.
+ *
+ * Each value under the "sections" field has two fields:
+ * - offset: The offset into the original specified at which this section
+ * begins to apply, defined as an object with a "line" and "column"
+ * field.
+ * - map: A source map definition. This source map could also be indexed,
+ * but doesn't have to be.
+ *
+ * Instead of the "map" field, it's also possible to have a "url" field
+ * specifying a URL to retrieve a source map from, but that's currently
+ * unsupported.
+ *
+ * Here's an example source map, taken from the source map spec[0], but
+ * modified to omit a section which uses the "url" field.
+ *
+ * {
+ * version : 3,
+ * file: "app.js",
+ * sections: [{
+ * offset: {line:100, column:10},
+ * map: {
+ * version : 3,
+ * file: "section.js",
+ * sources: ["foo.js", "bar.js"],
+ * names: ["src", "maps", "are", "fun"],
+ * mappings: "AAAA,E;;ABCDE;"
+ * }
+ * }],
+ * }
+ *
+ * The second parameter, if given, is a string whose value is the URL
+ * at which the source map was found. This URL is used to compute the
+ * sources array.
+ *
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
+ */
+ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = util.parseSourceMapInput(aSourceMap);
+ }
+
+ var version = util.getArg(sourceMap, 'version');
+ var sections = util.getArg(sourceMap, 'sections');
+
+ if (version != this._version) {
+ throw new Error('Unsupported version: ' + version);
+ }
+
+ this._sources = new ArraySet();
+ this._names = new ArraySet();
+
+ var lastOffset = {
+ line: -1,
+ column: 0
+ };
+ this._sections = sections.map(function (s) {
+ if (s.url) {
+ // The url field will require support for asynchronicity.
+ // See https://github.com/mozilla/source-map/issues/16
+ throw new Error('Support for url field in sections not implemented.');
+ }
+ var offset = util.getArg(s, 'offset');
+ var offsetLine = util.getArg(offset, 'line');
+ var offsetColumn = util.getArg(offset, 'column');
+
+ if (offsetLine < lastOffset.line ||
+ (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
+ throw new Error('Section offsets must be ordered and non-overlapping.');
+ }
+ lastOffset = offset;
+
+ return {
+ generatedOffset: {
+ // The offset fields are 0-based, but we use 1-based indices when
+ // encoding/decoding from VLQ.
+ generatedLine: offsetLine + 1,
+ generatedColumn: offsetColumn + 1
+ },
+ consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
+ }
+ });
+ }
+
+ IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
+ IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
+
+ /**
+ * The version of the source mapping spec that we are consuming.
+ */
+ IndexedSourceMapConsumer.prototype._version = 3;
+
+ /**
+ * The list of original sources.
+ */
+ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
+ get: function () {
+ var sources = [];
+ for (var i = 0; i < this._sections.length; i++) {
+ for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
+ sources.push(this._sections[i].consumer.sources[j]);
+ }
+ }
+ return sources;
+ }
+ });
+
+ /**
+ * Returns the original source, line, and column information for the generated
+ * source's line and column positions provided. The only argument is an object
+ * with the following properties:
+ *
+ * - line: The line number in the generated source. The line number
+ * is 1-based.
+ * - column: The column number in the generated source. The column
+ * number is 0-based.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - source: The original source file, or null.
+ * - line: The line number in the original source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the original source, or null. The
+ * column number is 0-based.
+ * - name: The original identifier, or null.
+ */
+ IndexedSourceMapConsumer.prototype.originalPositionFor =
+ function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
+ var needle = {
+ generatedLine: util.getArg(aArgs, 'line'),
+ generatedColumn: util.getArg(aArgs, 'column')
+ };
+
+ // Find the section containing the generated position we're trying to map
+ // to an original position.
+ var sectionIndex = binarySearch.search(needle, this._sections,
+ function(needle, section) {
+ var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
+ if (cmp) {
+ return cmp;
+ }
+
+ return (needle.generatedColumn -
+ section.generatedOffset.generatedColumn);
+ });
+ var section = this._sections[sectionIndex];
+
+ if (!section) {
+ return {
+ source: null,
+ line: null,
+ column: null,
+ name: null
+ };
+ }
+
+ return section.consumer.originalPositionFor({
+ line: needle.generatedLine -
+ (section.generatedOffset.generatedLine - 1),
+ column: needle.generatedColumn -
+ (section.generatedOffset.generatedLine === needle.generatedLine
+ ? section.generatedOffset.generatedColumn - 1
+ : 0),
+ bias: aArgs.bias
+ });
+ };
+
+ /**
+ * Return true if we have the source content for every source in the source
+ * map, false otherwise.
+ */
+ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
+ function IndexedSourceMapConsumer_hasContentsOfAllSources() {
+ return this._sections.every(function (s) {
+ return s.consumer.hasContentsOfAllSources();
+ });
+ };
+
+ /**
+ * Returns the original source content. The only argument is the url of the
+ * original source file. Returns null if no original source content is
+ * available.
+ */
+ IndexedSourceMapConsumer.prototype.sourceContentFor =
+ function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
+ for (var i = 0; i < this._sections.length; i++) {
+ var section = this._sections[i];
+
+ var content = section.consumer.sourceContentFor(aSource, true);
+ if (content) {
+ return content;
+ }
+ }
+ if (nullOnMissing) {
+ return null;
+ }
+ else {
+ throw new Error('"' + aSource + '" is not in the SourceMap.');
+ }
+ };
+
+ /**
+ * Returns the generated line and column information for the original source,
+ * line, and column positions provided. The only argument is an object with
+ * the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source. The line number
+ * is 1-based.
+ * - column: The column number in the original source. The column
+ * number is 0-based.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - line: The line number in the generated source, or null. The
+ * line number is 1-based.
+ * - column: The column number in the generated source, or null.
+ * The column number is 0-based.
+ */
+ IndexedSourceMapConsumer.prototype.generatedPositionFor =
+ function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
+ for (var i = 0; i < this._sections.length; i++) {
+ var section = this._sections[i];
+
+ // Only consider this section if the requested source is in the list of
+ // sources of the consumer.
+ if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
+ continue;
+ }
+ var generatedPosition = section.consumer.generatedPositionFor(aArgs);
+ if (generatedPosition) {
+ var ret = {
+ line: generatedPosition.line +
+ (section.generatedOffset.generatedLine - 1),
+ column: generatedPosition.column +
+ (section.generatedOffset.generatedLine === generatedPosition.line
+ ? section.generatedOffset.generatedColumn - 1
+ : 0)
+ };
+ return ret;
+ }
+ }
+
+ return {
+ line: null,
+ column: null
+ };
+ };
+
+ /**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+ IndexedSourceMapConsumer.prototype._parseMappings =
+ function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ this.__generatedMappings = [];
+ this.__originalMappings = [];
+ for (var i = 0; i < this._sections.length; i++) {
+ var section = this._sections[i];
+ var sectionMappings = section.consumer._generatedMappings;
+ for (var j = 0; j < sectionMappings.length; j++) {
+ var mapping = sectionMappings[j];
+
+ var source = section.consumer._sources.at(mapping.source);
+ source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
+ this._sources.add(source);
+ source = this._sources.indexOf(source);
+
+ var name = null;
+ if (mapping.name) {
+ name = section.consumer._names.at(mapping.name);
+ this._names.add(name);
+ name = this._names.indexOf(name);
+ }
+
+ // The mappings coming from the consumer for the section have
+ // generated positions relative to the start of the section, so we
+ // need to offset them to be relative to the start of the concatenated
+ // generated file.
+ var adjustedMapping = {
+ source: source,
+ generatedLine: mapping.generatedLine +
+ (section.generatedOffset.generatedLine - 1),
+ generatedColumn: mapping.generatedColumn +
+ (section.generatedOffset.generatedLine === mapping.generatedLine
+ ? section.generatedOffset.generatedColumn - 1
+ : 0),
+ originalLine: mapping.originalLine,
+ originalColumn: mapping.originalColumn,
+ name: name
+ };
+
+ this.__generatedMappings.push(adjustedMapping);
+ if (typeof adjustedMapping.originalLine === 'number') {
+ this.__originalMappings.push(adjustedMapping);
+ }
+ }
+ }
+
+ quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
+ quickSort(this.__originalMappings, util.compareByOriginalPositions);
+ };
+
+ sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
+ return sourceMapConsumer;
+}
+
+var sourceNode = {};
+
+/* -*- Mode: js; js-indent-level: 2; -*- */
+
+var hasRequiredSourceNode;
+
+function requireSourceNode () {
+ if (hasRequiredSourceNode) return sourceNode;
+ hasRequiredSourceNode = 1;
+ /*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+ var SourceMapGenerator = requireSourceMapGenerator().SourceMapGenerator;
+ var util = requireUtil();
+
+ // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
+ // operating systems these days (capturing the result).
+ var REGEX_NEWLINE = /(\r?\n)/;
+
+ // Newline character code for charCodeAt() comparisons
+ var NEWLINE_CODE = 10;
+
+ // Private symbol for identifying `SourceNode`s when multiple versions of
+ // the source-map library are loaded. This MUST NOT CHANGE across
+ // versions!
+ var isSourceNode = "$$$isSourceNode$$$";
+
+ /**
+ * SourceNodes provide a way to abstract over interpolating/concatenating
+ * snippets of generated JavaScript source code while maintaining the line and
+ * column information associated with the original source code.
+ *
+ * @param aLine The original line number.
+ * @param aColumn The original column number.
+ * @param aSource The original source's filename.
+ * @param aChunks Optional. An array of strings which are snippets of
+ * generated JS, or other SourceNodes.
+ * @param aName The original identifier.
+ */
+ function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
+ this.children = [];
+ this.sourceContents = {};
+ this.line = aLine == null ? null : aLine;
+ this.column = aColumn == null ? null : aColumn;
+ this.source = aSource == null ? null : aSource;
+ this.name = aName == null ? null : aName;
+ this[isSourceNode] = true;
+ if (aChunks != null) this.add(aChunks);
+ }
+
+ /**
+ * Creates a SourceNode from generated code and a SourceMapConsumer.
+ *
+ * @param aGeneratedCode The generated code
+ * @param aSourceMapConsumer The SourceMap for the generated code
+ * @param aRelativePath Optional. The path that relative sources in the
+ * SourceMapConsumer should be relative to.
+ */
+ SourceNode.fromStringWithSourceMap =
+ function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
+ // The SourceNode we want to fill with the generated code
+ // and the SourceMap
+ var node = new SourceNode();
+
+ // All even indices of this array are one line of the generated code,
+ // while all odd indices are the newlines between two adjacent lines
+ // (since `REGEX_NEWLINE` captures its match).
+ // Processed fragments are accessed by calling `shiftNextLine`.
+ var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
+ var remainingLinesIndex = 0;
+ var shiftNextLine = function() {
+ var lineContents = getNextLine();
+ // The last line of a file might not have a newline.
+ var newLine = getNextLine() || "";
+ return lineContents + newLine;
+
+ function getNextLine() {
+ return remainingLinesIndex < remainingLines.length ?
+ remainingLines[remainingLinesIndex++] : undefined;
+ }
+ };
+
+ // We need to remember the position of "remainingLines"
+ var lastGeneratedLine = 1, lastGeneratedColumn = 0;
+
+ // The generate SourceNodes we need a code range.
+ // To extract it current and last mapping is used.
+ // Here we store the last mapping.
+ var lastMapping = null;
+
+ aSourceMapConsumer.eachMapping(function (mapping) {
+ if (lastMapping !== null) {
+ // We add the code from "lastMapping" to "mapping":
+ // First check if there is a new line in between.
+ if (lastGeneratedLine < mapping.generatedLine) {
+ // Associate first line with "lastMapping"
+ addMappingWithCode(lastMapping, shiftNextLine());
+ lastGeneratedLine++;
+ lastGeneratedColumn = 0;
+ // The remaining code is added without mapping
+ } else {
+ // There is no new line in between.
+ // Associate the code between "lastGeneratedColumn" and
+ // "mapping.generatedColumn" with "lastMapping"
+ var nextLine = remainingLines[remainingLinesIndex] || '';
+ var code = nextLine.substr(0, mapping.generatedColumn -
+ lastGeneratedColumn);
+ remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
+ lastGeneratedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ addMappingWithCode(lastMapping, code);
+ // No more remaining code, continue
+ lastMapping = mapping;
+ return;
+ }
+ }
+ // We add the generated code until the first mapping
+ // to the SourceNode without any mapping.
+ // Each line is added as separate string.
+ while (lastGeneratedLine < mapping.generatedLine) {
+ node.add(shiftNextLine());
+ lastGeneratedLine++;
+ }
+ if (lastGeneratedColumn < mapping.generatedColumn) {
+ var nextLine = remainingLines[remainingLinesIndex] || '';
+ node.add(nextLine.substr(0, mapping.generatedColumn));
+ remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ }
+ lastMapping = mapping;
+ }, this);
+ // We have processed all mappings.
+ if (remainingLinesIndex < remainingLines.length) {
+ if (lastMapping) {
+ // Associate the remaining code in the current line with "lastMapping"
+ addMappingWithCode(lastMapping, shiftNextLine());
+ }
+ // and add the remaining lines without any mapping
+ node.add(remainingLines.splice(remainingLinesIndex).join(""));
+ }
+
+ // Copy sourcesContent into SourceNode
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content != null) {
+ if (aRelativePath != null) {
+ sourceFile = util.join(aRelativePath, sourceFile);
+ }
+ node.setSourceContent(sourceFile, content);
+ }
+ });
+
+ return node;
+
+ function addMappingWithCode(mapping, code) {
+ if (mapping === null || mapping.source === undefined) {
+ node.add(code);
+ } else {
+ var source = aRelativePath
+ ? util.join(aRelativePath, mapping.source)
+ : mapping.source;
+ node.add(new SourceNode(mapping.originalLine,
+ mapping.originalColumn,
+ source,
+ code,
+ mapping.name));
+ }
+ }
+ };
+
+ /**
+ * Add a chunk of generated JS to this source node.
+ *
+ * @param aChunk A string snippet of generated JS code, another instance of
+ * SourceNode, or an array where each member is one of those things.
+ */
+ SourceNode.prototype.add = function SourceNode_add(aChunk) {
+ if (Array.isArray(aChunk)) {
+ aChunk.forEach(function (chunk) {
+ this.add(chunk);
+ }, this);
+ }
+ else if (aChunk[isSourceNode] || typeof aChunk === "string") {
+ if (aChunk) {
+ this.children.push(aChunk);
+ }
+ }
+ else {
+ throw new TypeError(
+ "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
+ );
+ }
+ return this;
+ };
+
+ /**
+ * Add a chunk of generated JS to the beginning of this source node.
+ *
+ * @param aChunk A string snippet of generated JS code, another instance of
+ * SourceNode, or an array where each member is one of those things.
+ */
+ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
+ if (Array.isArray(aChunk)) {
+ for (var i = aChunk.length-1; i >= 0; i--) {
+ this.prepend(aChunk[i]);
+ }
+ }
+ else if (aChunk[isSourceNode] || typeof aChunk === "string") {
+ this.children.unshift(aChunk);
+ }
+ else {
+ throw new TypeError(
+ "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
+ );
+ }
+ return this;
+ };
+
+ /**
+ * Walk over the tree of JS snippets in this node and its children. The
+ * walking function is called once for each snippet of JS and is passed that
+ * snippet and the its original associated source's line/column location.
+ *
+ * @param aFn The traversal function.
+ */
+ SourceNode.prototype.walk = function SourceNode_walk(aFn) {
+ var chunk;
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ chunk = this.children[i];
+ if (chunk[isSourceNode]) {
+ chunk.walk(aFn);
+ }
+ else {
+ if (chunk !== '') {
+ aFn(chunk, { source: this.source,
+ line: this.line,
+ column: this.column,
+ name: this.name });
+ }
+ }
+ }
+ };
+
+ /**
+ * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
+ * each of `this.children`.
+ *
+ * @param aSep The separator.
+ */
+ SourceNode.prototype.join = function SourceNode_join(aSep) {
+ var newChildren;
+ var i;
+ var len = this.children.length;
+ if (len > 0) {
+ newChildren = [];
+ for (i = 0; i < len-1; i++) {
+ newChildren.push(this.children[i]);
+ newChildren.push(aSep);
+ }
+ newChildren.push(this.children[i]);
+ this.children = newChildren;
+ }
+ return this;
+ };
+
+ /**
+ * Call String.prototype.replace on the very right-most source snippet. Useful
+ * for trimming whitespace from the end of a source node, etc.
+ *
+ * @param aPattern The pattern to replace.
+ * @param aReplacement The thing to replace the pattern with.
+ */
+ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
+ var lastChild = this.children[this.children.length - 1];
+ if (lastChild[isSourceNode]) {
+ lastChild.replaceRight(aPattern, aReplacement);
+ }
+ else if (typeof lastChild === 'string') {
+ this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
+ }
+ else {
+ this.children.push(''.replace(aPattern, aReplacement));
+ }
+ return this;
+ };
+
+ /**
+ * Set the source content for a source file. This will be added to the SourceMapGenerator
+ * in the sourcesContent field.
+ *
+ * @param aSourceFile The filename of the source file
+ * @param aSourceContent The content of the source file
+ */
+ SourceNode.prototype.setSourceContent =
+ function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
+ this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
+ };
+
+ /**
+ * Walk over the tree of SourceNodes. The walking function is called for each
+ * source file content and is passed the filename and source content.
+ *
+ * @param aFn The traversal function.
+ */
+ SourceNode.prototype.walkSourceContents =
+ function SourceNode_walkSourceContents(aFn) {
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ if (this.children[i][isSourceNode]) {
+ this.children[i].walkSourceContents(aFn);
+ }
+ }
+
+ var sources = Object.keys(this.sourceContents);
+ for (var i = 0, len = sources.length; i < len; i++) {
+ aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
+ }
+ };
+
+ /**
+ * Return the string representation of this source node. Walks over the tree
+ * and concatenates all the various snippets together to one string.
+ */
+ SourceNode.prototype.toString = function SourceNode_toString() {
+ var str = "";
+ this.walk(function (chunk) {
+ str += chunk;
+ });
+ return str;
+ };
+
+ /**
+ * Returns the string representation of this source node along with a source
+ * map.
+ */
+ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
+ var generated = {
+ code: "",
+ line: 1,
+ column: 0
+ };
+ var map = new SourceMapGenerator(aArgs);
+ var sourceMappingActive = false;
+ var lastOriginalSource = null;
+ var lastOriginalLine = null;
+ var lastOriginalColumn = null;
+ var lastOriginalName = null;
+ this.walk(function (chunk, original) {
+ generated.code += chunk;
+ if (original.source !== null
+ && original.line !== null
+ && original.column !== null) {
+ if(lastOriginalSource !== original.source
+ || lastOriginalLine !== original.line
+ || lastOriginalColumn !== original.column
+ || lastOriginalName !== original.name) {
+ map.addMapping({
+ source: original.source,
+ original: {
+ line: original.line,
+ column: original.column
+ },
+ generated: {
+ line: generated.line,
+ column: generated.column
+ },
+ name: original.name
+ });
+ }
+ lastOriginalSource = original.source;
+ lastOriginalLine = original.line;
+ lastOriginalColumn = original.column;
+ lastOriginalName = original.name;
+ sourceMappingActive = true;
+ } else if (sourceMappingActive) {
+ map.addMapping({
+ generated: {
+ line: generated.line,
+ column: generated.column
+ }
+ });
+ lastOriginalSource = null;
+ sourceMappingActive = false;
+ }
+ for (var idx = 0, length = chunk.length; idx < length; idx++) {
+ if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
+ generated.line++;
+ generated.column = 0;
+ // Mappings end at eol
+ if (idx + 1 === length) {
+ lastOriginalSource = null;
+ sourceMappingActive = false;
+ } else if (sourceMappingActive) {
+ map.addMapping({
+ source: original.source,
+ original: {
+ line: original.line,
+ column: original.column
+ },
+ generated: {
+ line: generated.line,
+ column: generated.column
+ },
+ name: original.name
+ });
+ }
+ } else {
+ generated.column++;
+ }
+ }
+ });
+ this.walkSourceContents(function (sourceFile, sourceContent) {
+ map.setSourceContent(sourceFile, sourceContent);
+ });
+
+ return { code: generated.code, map: map };
+ };
+
+ sourceNode.SourceNode = SourceNode;
+ return sourceNode;
+}
+
+/*
+ * Copyright 2009-2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE.txt or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+var hasRequiredSourceMap;
+
+function requireSourceMap () {
+ if (hasRequiredSourceMap) return sourceMap;
+ hasRequiredSourceMap = 1;
+ sourceMap.SourceMapGenerator = requireSourceMapGenerator().SourceMapGenerator;
+ sourceMap.SourceMapConsumer = requireSourceMapConsumer().SourceMapConsumer;
+ sourceMap.SourceNode = requireSourceNode().SourceNode;
+ return sourceMap;
+}
+
+/* global define */
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+
+ var _utils = utils$1;
+
+ var SourceNode = undefined;
+
+ try {
+ /* istanbul ignore next */
+ if (typeof undefined !== 'function' || !undefined.amd) {
+ // We don't support this in AMD environments. For these environments, we asusme that
+ // they are running on the browser and thus have no need for the source-map library.
+ var SourceMap = requireSourceMap();
+ SourceNode = SourceMap.SourceNode;
+ }
+ } catch (err) {}
+ /* NOP */
+
+ /* istanbul ignore if: tested but not covered in istanbul due to dist build */
+ if (!SourceNode) {
+ SourceNode = function (line, column, srcFile, chunks) {
+ this.src = '';
+ if (chunks) {
+ this.add(chunks);
+ }
+ };
+ /* istanbul ignore next */
+ SourceNode.prototype = {
+ add: function add(chunks) {
+ if (_utils.isArray(chunks)) {
+ chunks = chunks.join('');
+ }
+ this.src += chunks;
+ },
+ prepend: function prepend(chunks) {
+ if (_utils.isArray(chunks)) {
+ chunks = chunks.join('');
+ }
+ this.src = chunks + this.src;
+ },
+ toStringWithSourceMap: function toStringWithSourceMap() {
+ return { code: this.toString() };
+ },
+ toString: function toString() {
+ return this.src;
+ }
+ };
+ }
+
+ function castChunk(chunk, codeGen, loc) {
+ if (_utils.isArray(chunk)) {
+ var ret = [];
+
+ for (var i = 0, len = chunk.length; i < len; i++) {
+ ret.push(codeGen.wrap(chunk[i], loc));
+ }
+ return ret;
+ } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
+ // Handle primitives that the SourceNode will throw up on
+ return chunk + '';
+ }
+ return chunk;
+ }
+
+ function CodeGen(srcFile) {
+ this.srcFile = srcFile;
+ this.source = [];
+ }
+
+ CodeGen.prototype = {
+ isEmpty: function isEmpty() {
+ return !this.source.length;
+ },
+ prepend: function prepend(source, loc) {
+ this.source.unshift(this.wrap(source, loc));
+ },
+ push: function push(source, loc) {
+ this.source.push(this.wrap(source, loc));
+ },
+
+ merge: function merge() {
+ var source = this.empty();
+ this.each(function (line) {
+ source.add([' ', line, '\n']);
+ });
+ return source;
+ },
+
+ each: function each(iter) {
+ for (var i = 0, len = this.source.length; i < len; i++) {
+ iter(this.source[i]);
+ }
+ },
+
+ empty: function empty() {
+ var loc = this.currentLocation || { start: {} };
+ return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
+ },
+ wrap: function wrap(chunk) {
+ var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
+
+ if (chunk instanceof SourceNode) {
+ return chunk;
+ }
+
+ chunk = castChunk(chunk, this, loc);
+
+ return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
+ },
+
+ functionCall: function functionCall(fn, type, params) {
+ params = this.generateList(params);
+ return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
+ },
+
+ quotedString: function quotedString(str) {
+ return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
+ .replace(/\u2029/g, '\\u2029') + '"';
+ },
+
+ objectLiteral: function objectLiteral(obj) {
+ // istanbul ignore next
+
+ var _this = this;
+
+ var pairs = [];
+
+ Object.keys(obj).forEach(function (key) {
+ var value = castChunk(obj[key], _this);
+ if (value !== 'undefined') {
+ pairs.push([_this.quotedString(key), ':', value]);
+ }
+ });
+
+ var ret = this.generateList(pairs);
+ ret.prepend('{');
+ ret.add('}');
+ return ret;
+ },
+
+ generateList: function generateList(entries) {
+ var ret = this.empty();
+
+ for (var i = 0, len = entries.length; i < len; i++) {
+ if (i) {
+ ret.add(',');
+ }
+
+ ret.add(castChunk(entries[i], this));
+ }
+
+ return ret;
+ },
+
+ generateArray: function generateArray(entries) {
+ var ret = this.generateList(entries);
+ ret.prepend('[');
+ ret.add(']');
+
+ return ret;
+ }
+ };
+
+ exports['default'] = CodeGen;
+ module.exports = exports['default'];
+
+} (codeGen, codeGenExports));
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _base = base$1;
+
+ var _exception = exceptionExports;
+
+ var _exception2 = _interopRequireDefault(_exception);
+
+ var _utils = utils$1;
+
+ var _codeGen = codeGenExports;
+
+ var _codeGen2 = _interopRequireDefault(_codeGen);
+
+ function Literal(value) {
+ this.value = value;
+ }
+
+ function JavaScriptCompiler() {}
+
+ JavaScriptCompiler.prototype = {
+ // PUBLIC API: You can override these methods in a subclass to provide
+ // alternative compiled forms for name lookup and buffering semantics
+ nameLookup: function nameLookup(parent, name /*, type */) {
+ return this.internalNameLookup(parent, name);
+ },
+ depthedLookup: function depthedLookup(name) {
+ return [this.aliasable('container.lookup'), '(depths, ', JSON.stringify(name), ')'];
+ },
+
+ compilerInfo: function compilerInfo() {
+ var revision = _base.COMPILER_REVISION,
+ versions = _base.REVISION_CHANGES[revision];
+ return [revision, versions];
+ },
+
+ appendToBuffer: function appendToBuffer(source, location, explicit) {
+ // Force a source as this simplifies the merge logic.
+ if (!_utils.isArray(source)) {
+ source = [source];
+ }
+ source = this.source.wrap(source, location);
+
+ if (this.environment.isSimple) {
+ return ['return ', source, ';'];
+ } else if (explicit) {
+ // This is a case where the buffer operation occurs as a child of another
+ // construct, generally braces. We have to explicitly output these buffer
+ // operations to ensure that the emitted code goes in the correct location.
+ return ['buffer += ', source, ';'];
+ } else {
+ source.appendToBuffer = true;
+ return source;
+ }
+ },
+
+ initializeBuffer: function initializeBuffer() {
+ return this.quotedString('');
+ },
+ // END PUBLIC API
+ internalNameLookup: function internalNameLookup(parent, name) {
+ this.lookupPropertyFunctionIsUsed = true;
+ return ['lookupProperty(', parent, ',', JSON.stringify(name), ')'];
+ },
+
+ lookupPropertyFunctionIsUsed: false,
+
+ compile: function compile(environment, options, context, asObject) {
+ this.environment = environment;
+ this.options = options;
+ this.stringParams = this.options.stringParams;
+ this.trackIds = this.options.trackIds;
+ this.precompile = !asObject;
+
+ this.name = this.environment.name;
+ this.isChild = !!context;
+ this.context = context || {
+ decorators: [],
+ programs: [],
+ environments: []
+ };
+
+ this.preamble();
+
+ this.stackSlot = 0;
+ this.stackVars = [];
+ this.aliases = {};
+ this.registers = { list: [] };
+ this.hashes = [];
+ this.compileStack = [];
+ this.inlineStack = [];
+ this.blockParams = [];
+
+ this.compileChildren(environment, options);
+
+ this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
+ this.useBlockParams = this.useBlockParams || environment.useBlockParams;
+
+ var opcodes = environment.opcodes,
+ opcode = undefined,
+ firstLoc = undefined,
+ i = undefined,
+ l = undefined;
+
+ for (i = 0, l = opcodes.length; i < l; i++) {
+ opcode = opcodes[i];
+
+ this.source.currentLocation = opcode.loc;
+ firstLoc = firstLoc || opcode.loc;
+ this[opcode.opcode].apply(this, opcode.args);
+ }
+
+ // Flush any trailing content that might be pending.
+ this.source.currentLocation = firstLoc;
+ this.pushSource('');
+
+ /* istanbul ignore next */
+ if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
+ throw new _exception2['default']('Compile completed with content left on stack');
+ }
+
+ if (!this.decorators.isEmpty()) {
+ this.useDecorators = true;
+
+ this.decorators.prepend(['var decorators = container.decorators, ', this.lookupPropertyFunctionVarDeclaration(), ';\n']);
+ this.decorators.push('return fn;');
+
+ if (asObject) {
+ this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
+ } else {
+ this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
+ this.decorators.push('}\n');
+ this.decorators = this.decorators.merge();
+ }
+ } else {
+ this.decorators = undefined;
+ }
+
+ var fn = this.createFunctionContext(asObject);
+ if (!this.isChild) {
+ var ret = {
+ compiler: this.compilerInfo(),
+ main: fn
+ };
+
+ if (this.decorators) {
+ ret.main_d = this.decorators; // eslint-disable-line camelcase
+ ret.useDecorators = true;
+ }
+
+ var _context = this.context;
+ var programs = _context.programs;
+ var decorators = _context.decorators;
+
+ for (i = 0, l = programs.length; i < l; i++) {
+ if (programs[i]) {
+ ret[i] = programs[i];
+ if (decorators[i]) {
+ ret[i + '_d'] = decorators[i];
+ ret.useDecorators = true;
+ }
+ }
+ }
+
+ if (this.environment.usePartial) {
+ ret.usePartial = true;
+ }
+ if (this.options.data) {
+ ret.useData = true;
+ }
+ if (this.useDepths) {
+ ret.useDepths = true;
+ }
+ if (this.useBlockParams) {
+ ret.useBlockParams = true;
+ }
+ if (this.options.compat) {
+ ret.compat = true;
+ }
+
+ if (!asObject) {
+ ret.compiler = JSON.stringify(ret.compiler);
+
+ this.source.currentLocation = { start: { line: 1, column: 0 } };
+ ret = this.objectLiteral(ret);
+
+ if (options.srcName) {
+ ret = ret.toStringWithSourceMap({ file: options.destName });
+ ret.map = ret.map && ret.map.toString();
+ } else {
+ ret = ret.toString();
+ }
+ } else {
+ ret.compilerOptions = this.options;
+ }
+
+ return ret;
+ } else {
+ return fn;
+ }
+ },
+
+ preamble: function preamble() {
+ // track the last context pushed into place to allow skipping the
+ // getContext opcode when it would be a noop
+ this.lastContext = 0;
+ this.source = new _codeGen2['default'](this.options.srcName);
+ this.decorators = new _codeGen2['default'](this.options.srcName);
+ },
+
+ createFunctionContext: function createFunctionContext(asObject) {
+ // istanbul ignore next
+
+ var _this = this;
+
+ var varDeclarations = '';
+
+ var locals = this.stackVars.concat(this.registers.list);
+ if (locals.length > 0) {
+ varDeclarations += ', ' + locals.join(', ');
+ }
+
+ // Generate minimizer alias mappings
+ //
+ // When using true SourceNodes, this will update all references to the given alias
+ // as the source nodes are reused in situ. For the non-source node compilation mode,
+ // aliases will not be used, but this case is already being run on the client and
+ // we aren't concern about minimizing the template size.
+ var aliasCount = 0;
+ Object.keys(this.aliases).forEach(function (alias) {
+ var node = _this.aliases[alias];
+ if (node.children && node.referenceCount > 1) {
+ varDeclarations += ', alias' + ++aliasCount + '=' + alias;
+ node.children[0] = 'alias' + aliasCount;
+ }
+ });
+
+ if (this.lookupPropertyFunctionIsUsed) {
+ varDeclarations += ', ' + this.lookupPropertyFunctionVarDeclaration();
+ }
+
+ var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
+
+ if (this.useBlockParams || this.useDepths) {
+ params.push('blockParams');
+ }
+ if (this.useDepths) {
+ params.push('depths');
+ }
+
+ // Perform a second pass over the output to merge content when possible
+ var source = this.mergeSource(varDeclarations);
+
+ if (asObject) {
+ params.push(source);
+
+ return Function.apply(this, params);
+ } else {
+ return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
+ }
+ },
+ mergeSource: function mergeSource(varDeclarations) {
+ var isSimple = this.environment.isSimple,
+ appendOnly = !this.forceBuffer,
+ appendFirst = undefined,
+ sourceSeen = undefined,
+ bufferStart = undefined,
+ bufferEnd = undefined;
+ this.source.each(function (line) {
+ if (line.appendToBuffer) {
+ if (bufferStart) {
+ line.prepend(' + ');
+ } else {
+ bufferStart = line;
+ }
+ bufferEnd = line;
+ } else {
+ if (bufferStart) {
+ if (!sourceSeen) {
+ appendFirst = true;
+ } else {
+ bufferStart.prepend('buffer += ');
+ }
+ bufferEnd.add(';');
+ bufferStart = bufferEnd = undefined;
+ }
+
+ sourceSeen = true;
+ if (!isSimple) {
+ appendOnly = false;
+ }
+ }
+ });
+
+ if (appendOnly) {
+ if (bufferStart) {
+ bufferStart.prepend('return ');
+ bufferEnd.add(';');
+ } else if (!sourceSeen) {
+ this.source.push('return "";');
+ }
+ } else {
+ varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
+
+ if (bufferStart) {
+ bufferStart.prepend('return buffer + ');
+ bufferEnd.add(';');
+ } else {
+ this.source.push('return buffer;');
+ }
+ }
+
+ if (varDeclarations) {
+ this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
+ }
+
+ return this.source.merge();
+ },
+
+ lookupPropertyFunctionVarDeclaration: function lookupPropertyFunctionVarDeclaration() {
+ return '\n lookupProperty = container.lookupProperty || function(parent, propertyName) {\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return parent[propertyName];\n }\n return undefined\n }\n '.trim();
+ },
+
+ // [blockValue]
+ //
+ // On stack, before: hash, inverse, program, value
+ // On stack, after: return value of blockHelperMissing
+ //
+ // The purpose of this opcode is to take a block of the form
+ // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
+ // replace it on the stack with the result of properly
+ // invoking blockHelperMissing.
+ blockValue: function blockValue(name) {
+ var blockHelperMissing = this.aliasable('container.hooks.blockHelperMissing'),
+ params = [this.contextName(0)];
+ this.setupHelperArgs(name, 0, params);
+
+ var blockName = this.popStack();
+ params.splice(1, 0, blockName);
+
+ this.push(this.source.functionCall(blockHelperMissing, 'call', params));
+ },
+
+ // [ambiguousBlockValue]
+ //
+ // On stack, before: hash, inverse, program, value
+ // Compiler value, before: lastHelper=value of last found helper, if any
+ // On stack, after, if no lastHelper: same as [blockValue]
+ // On stack, after, if lastHelper: value
+ ambiguousBlockValue: function ambiguousBlockValue() {
+ // We're being a bit cheeky and reusing the options value from the prior exec
+ var blockHelperMissing = this.aliasable('container.hooks.blockHelperMissing'),
+ params = [this.contextName(0)];
+ this.setupHelperArgs('', 0, params, true);
+
+ this.flushInline();
+
+ var current = this.topStack();
+ params.splice(1, 0, current);
+
+ this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
+ },
+
+ // [appendContent]
+ //
+ // On stack, before: ...
+ // On stack, after: ...
+ //
+ // Appends the string value of `content` to the current buffer
+ appendContent: function appendContent(content) {
+ if (this.pendingContent) {
+ content = this.pendingContent + content;
+ } else {
+ this.pendingLocation = this.source.currentLocation;
+ }
+
+ this.pendingContent = content;
+ },
+
+ // [append]
+ //
+ // On stack, before: value, ...
+ // On stack, after: ...
+ //
+ // Coerces `value` to a String and appends it to the current buffer.
+ //
+ // If `value` is truthy, or 0, it is coerced into a string and appended
+ // Otherwise, the empty string is appended
+ append: function append() {
+ if (this.isInline()) {
+ this.replaceStack(function (current) {
+ return [' != null ? ', current, ' : ""'];
+ });
+
+ this.pushSource(this.appendToBuffer(this.popStack()));
+ } else {
+ var local = this.popStack();
+ this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
+ if (this.environment.isSimple) {
+ this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
+ }
+ }
+ },
+
+ // [appendEscaped]
+ //
+ // On stack, before: value, ...
+ // On stack, after: ...
+ //
+ // Escape `value` and append it to the buffer
+ appendEscaped: function appendEscaped() {
+ this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
+ },
+
+ // [getContext]
+ //
+ // On stack, before: ...
+ // On stack, after: ...
+ // Compiler value, after: lastContext=depth
+ //
+ // Set the value of the `lastContext` compiler value to the depth
+ getContext: function getContext(depth) {
+ this.lastContext = depth;
+ },
+
+ // [pushContext]
+ //
+ // On stack, before: ...
+ // On stack, after: currentContext, ...
+ //
+ // Pushes the value of the current context onto the stack.
+ pushContext: function pushContext() {
+ this.pushStackLiteral(this.contextName(this.lastContext));
+ },
+
+ // [lookupOnContext]
+ //
+ // On stack, before: ...
+ // On stack, after: currentContext[name], ...
+ //
+ // Looks up the value of `name` on the current context and pushes
+ // it onto the stack.
+ lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
+ var i = 0;
+
+ if (!scoped && this.options.compat && !this.lastContext) {
+ // The depthed query is expected to handle the undefined logic for the root level that
+ // is implemented below, so we evaluate that directly in compat mode
+ this.push(this.depthedLookup(parts[i++]));
+ } else {
+ this.pushContext();
+ }
+
+ this.resolvePath('context', parts, i, falsy, strict);
+ },
+
+ // [lookupBlockParam]
+ //
+ // On stack, before: ...
+ // On stack, after: blockParam[name], ...
+ //
+ // Looks up the value of `parts` on the given block param and pushes
+ // it onto the stack.
+ lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
+ this.useBlockParams = true;
+
+ this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
+ this.resolvePath('context', parts, 1);
+ },
+
+ // [lookupData]
+ //
+ // On stack, before: ...
+ // On stack, after: data, ...
+ //
+ // Push the data lookup operator
+ lookupData: function lookupData(depth, parts, strict) {
+ if (!depth) {
+ this.pushStackLiteral('data');
+ } else {
+ this.pushStackLiteral('container.data(data, ' + depth + ')');
+ }
+
+ this.resolvePath('data', parts, 0, true, strict);
+ },
+
+ resolvePath: function resolvePath(type, parts, i, falsy, strict) {
+ // istanbul ignore next
+
+ var _this2 = this;
+
+ if (this.options.strict || this.options.assumeObjects) {
+ this.push(strictLookup(this.options.strict && strict, this, parts, type));
+ return;
+ }
+
+ var len = parts.length;
+ for (; i < len; i++) {
+ /* eslint-disable no-loop-func */
+ this.replaceStack(function (current) {
+ var lookup = _this2.nameLookup(current, parts[i], type);
+ // We want to ensure that zero and false are handled properly if the context (falsy flag)
+ // needs to have the special handling for these values.
+ if (!falsy) {
+ return [' != null ? ', lookup, ' : ', current];
+ } else {
+ // Otherwise we can use generic falsy handling
+ return [' && ', lookup];
+ }
+ });
+ /* eslint-enable no-loop-func */
+ }
+ },
+
+ // [resolvePossibleLambda]
+ //
+ // On stack, before: value, ...
+ // On stack, after: resolved value, ...
+ //
+ // If the `value` is a lambda, replace it on the stack by
+ // the return value of the lambda
+ resolvePossibleLambda: function resolvePossibleLambda() {
+ this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
+ },
+
+ // [pushStringParam]
+ //
+ // On stack, before: ...
+ // On stack, after: string, currentContext, ...
+ //
+ // This opcode is designed for use in string mode, which
+ // provides the string value of a parameter along with its
+ // depth rather than resolving it immediately.
+ pushStringParam: function pushStringParam(string, type) {
+ this.pushContext();
+ this.pushString(type);
+
+ // If it's a subexpression, the string result
+ // will be pushed after this opcode.
+ if (type !== 'SubExpression') {
+ if (typeof string === 'string') {
+ this.pushString(string);
+ } else {
+ this.pushStackLiteral(string);
+ }
+ }
+ },
+
+ emptyHash: function emptyHash(omitEmpty) {
+ if (this.trackIds) {
+ this.push('{}'); // hashIds
+ }
+ if (this.stringParams) {
+ this.push('{}'); // hashContexts
+ this.push('{}'); // hashTypes
+ }
+ this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
+ },
+ pushHash: function pushHash() {
+ if (this.hash) {
+ this.hashes.push(this.hash);
+ }
+ this.hash = { values: {}, types: [], contexts: [], ids: [] };
+ },
+ popHash: function popHash() {
+ var hash = this.hash;
+ this.hash = this.hashes.pop();
+
+ if (this.trackIds) {
+ this.push(this.objectLiteral(hash.ids));
+ }
+ if (this.stringParams) {
+ this.push(this.objectLiteral(hash.contexts));
+ this.push(this.objectLiteral(hash.types));
+ }
+
+ this.push(this.objectLiteral(hash.values));
+ },
+
+ // [pushString]
+ //
+ // On stack, before: ...
+ // On stack, after: quotedString(string), ...
+ //
+ // Push a quoted version of `string` onto the stack
+ pushString: function pushString(string) {
+ this.pushStackLiteral(this.quotedString(string));
+ },
+
+ // [pushLiteral]
+ //
+ // On stack, before: ...
+ // On stack, after: value, ...
+ //
+ // Pushes a value onto the stack. This operation prevents
+ // the compiler from creating a temporary variable to hold
+ // it.
+ pushLiteral: function pushLiteral(value) {
+ this.pushStackLiteral(value);
+ },
+
+ // [pushProgram]
+ //
+ // On stack, before: ...
+ // On stack, after: program(guid), ...
+ //
+ // Push a program expression onto the stack. This takes
+ // a compile-time guid and converts it into a runtime-accessible
+ // expression.
+ pushProgram: function pushProgram(guid) {
+ if (guid != null) {
+ this.pushStackLiteral(this.programExpression(guid));
+ } else {
+ this.pushStackLiteral(null);
+ }
+ },
+
+ // [registerDecorator]
+ //
+ // On stack, before: hash, program, params..., ...
+ // On stack, after: ...
+ //
+ // Pops off the decorator's parameters, invokes the decorator,
+ // and inserts the decorator into the decorators list.
+ registerDecorator: function registerDecorator(paramSize, name) {
+ var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
+ options = this.setupHelperArgs(name, paramSize);
+
+ this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
+ },
+
+ // [invokeHelper]
+ //
+ // On stack, before: hash, inverse, program, params..., ...
+ // On stack, after: result of helper invocation
+ //
+ // Pops off the helper's parameters, invokes the helper,
+ // and pushes the helper's return value onto the stack.
+ //
+ // If the helper is not found, `helperMissing` is called.
+ invokeHelper: function invokeHelper(paramSize, name, isSimple) {
+ var nonHelper = this.popStack(),
+ helper = this.setupHelper(paramSize, name);
+
+ var possibleFunctionCalls = [];
+
+ if (isSimple) {
+ // direct call to helper
+ possibleFunctionCalls.push(helper.name);
+ }
+ // call a function from the input object
+ possibleFunctionCalls.push(nonHelper);
+ if (!this.options.strict) {
+ possibleFunctionCalls.push(this.aliasable('container.hooks.helperMissing'));
+ }
+
+ var functionLookupCode = ['(', this.itemsSeparatedBy(possibleFunctionCalls, '||'), ')'];
+ var functionCall = this.source.functionCall(functionLookupCode, 'call', helper.callParams);
+ this.push(functionCall);
+ },
+
+ itemsSeparatedBy: function itemsSeparatedBy(items, separator) {
+ var result = [];
+ result.push(items[0]);
+ for (var i = 1; i < items.length; i++) {
+ result.push(separator, items[i]);
+ }
+ return result;
+ },
+ // [invokeKnownHelper]
+ //
+ // On stack, before: hash, inverse, program, params..., ...
+ // On stack, after: result of helper invocation
+ //
+ // This operation is used when the helper is known to exist,
+ // so a `helperMissing` fallback is not required.
+ invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
+ var helper = this.setupHelper(paramSize, name);
+ this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
+ },
+
+ // [invokeAmbiguous]
+ //
+ // On stack, before: hash, inverse, program, params..., ...
+ // On stack, after: result of disambiguation
+ //
+ // This operation is used when an expression like `{{foo}}`
+ // is provided, but we don't know at compile-time whether it
+ // is a helper or a path.
+ //
+ // This operation emits more code than the other options,
+ // and can be avoided by passing the `knownHelpers` and
+ // `knownHelpersOnly` flags at compile-time.
+ invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
+ this.useRegister('helper');
+
+ var nonHelper = this.popStack();
+
+ this.emptyHash();
+ var helper = this.setupHelper(0, name, helperCall);
+
+ var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
+
+ var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
+ if (!this.options.strict) {
+ lookup[0] = '(helper = ';
+ lookup.push(' != null ? helper : ', this.aliasable('container.hooks.helperMissing'));
+ }
+
+ this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
+ },
+
+ // [invokePartial]
+ //
+ // On stack, before: context, ...
+ // On stack after: result of partial invocation
+ //
+ // This operation pops off a context, invokes a partial with that context,
+ // and pushes the result of the invocation back.
+ invokePartial: function invokePartial(isDynamic, name, indent) {
+ var params = [],
+ options = this.setupParams(name, 1, params);
+
+ if (isDynamic) {
+ name = this.popStack();
+ delete options.name;
+ }
+
+ if (indent) {
+ options.indent = JSON.stringify(indent);
+ }
+ options.helpers = 'helpers';
+ options.partials = 'partials';
+ options.decorators = 'container.decorators';
+
+ if (!isDynamic) {
+ params.unshift(this.nameLookup('partials', name, 'partial'));
+ } else {
+ params.unshift(name);
+ }
+
+ if (this.options.compat) {
+ options.depths = 'depths';
+ }
+ options = this.objectLiteral(options);
+ params.push(options);
+
+ this.push(this.source.functionCall('container.invokePartial', '', params));
+ },
+
+ // [assignToHash]
+ //
+ // On stack, before: value, ..., hash, ...
+ // On stack, after: ..., hash, ...
+ //
+ // Pops a value off the stack and assigns it to the current hash
+ assignToHash: function assignToHash(key) {
+ var value = this.popStack(),
+ context = undefined,
+ type = undefined,
+ id = undefined;
+
+ if (this.trackIds) {
+ id = this.popStack();
+ }
+ if (this.stringParams) {
+ type = this.popStack();
+ context = this.popStack();
+ }
+
+ var hash = this.hash;
+ if (context) {
+ hash.contexts[key] = context;
+ }
+ if (type) {
+ hash.types[key] = type;
+ }
+ if (id) {
+ hash.ids[key] = id;
+ }
+ hash.values[key] = value;
+ },
+
+ pushId: function pushId(type, name, child) {
+ if (type === 'BlockParam') {
+ this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
+ } else if (type === 'PathExpression') {
+ this.pushString(name);
+ } else if (type === 'SubExpression') {
+ this.pushStackLiteral('true');
+ } else {
+ this.pushStackLiteral('null');
+ }
+ },
+
+ // HELPERS
+
+ compiler: JavaScriptCompiler,
+
+ compileChildren: function compileChildren(environment, options) {
+ var children = environment.children,
+ child = undefined,
+ compiler = undefined;
+
+ for (var i = 0, l = children.length; i < l; i++) {
+ child = children[i];
+ compiler = new this.compiler(); // eslint-disable-line new-cap
+
+ var existing = this.matchExistingProgram(child);
+
+ if (existing == null) {
+ this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
+ var index = this.context.programs.length;
+ child.index = index;
+ child.name = 'program' + index;
+ this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
+ this.context.decorators[index] = compiler.decorators;
+ this.context.environments[index] = child;
+
+ this.useDepths = this.useDepths || compiler.useDepths;
+ this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
+ child.useDepths = this.useDepths;
+ child.useBlockParams = this.useBlockParams;
+ } else {
+ child.index = existing.index;
+ child.name = 'program' + existing.index;
+
+ this.useDepths = this.useDepths || existing.useDepths;
+ this.useBlockParams = this.useBlockParams || existing.useBlockParams;
+ }
+ }
+ },
+ matchExistingProgram: function matchExistingProgram(child) {
+ for (var i = 0, len = this.context.environments.length; i < len; i++) {
+ var environment = this.context.environments[i];
+ if (environment && environment.equals(child)) {
+ return environment;
+ }
+ }
+ },
+
+ programExpression: function programExpression(guid) {
+ var child = this.environment.children[guid],
+ programParams = [child.index, 'data', child.blockParams];
+
+ if (this.useBlockParams || this.useDepths) {
+ programParams.push('blockParams');
+ }
+ if (this.useDepths) {
+ programParams.push('depths');
+ }
+
+ return 'container.program(' + programParams.join(', ') + ')';
+ },
+
+ useRegister: function useRegister(name) {
+ if (!this.registers[name]) {
+ this.registers[name] = true;
+ this.registers.list.push(name);
+ }
+ },
+
+ push: function push(expr) {
+ if (!(expr instanceof Literal)) {
+ expr = this.source.wrap(expr);
+ }
+
+ this.inlineStack.push(expr);
+ return expr;
+ },
+
+ pushStackLiteral: function pushStackLiteral(item) {
+ this.push(new Literal(item));
+ },
+
+ pushSource: function pushSource(source) {
+ if (this.pendingContent) {
+ this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
+ this.pendingContent = undefined;
+ }
+
+ if (source) {
+ this.source.push(source);
+ }
+ },
+
+ replaceStack: function replaceStack(callback) {
+ var prefix = ['('],
+ stack = undefined,
+ createdStack = undefined,
+ usedLiteral = undefined;
+
+ /* istanbul ignore next */
+ if (!this.isInline()) {
+ throw new _exception2['default']('replaceStack on non-inline');
+ }
+
+ // We want to merge the inline statement into the replacement statement via ','
+ var top = this.popStack(true);
+
+ if (top instanceof Literal) {
+ // Literals do not need to be inlined
+ stack = [top.value];
+ prefix = ['(', stack];
+ usedLiteral = true;
+ } else {
+ // Get or create the current stack name for use by the inline
+ createdStack = true;
+ var _name = this.incrStack();
+
+ prefix = ['((', this.push(_name), ' = ', top, ')'];
+ stack = this.topStack();
+ }
+
+ var item = callback.call(this, stack);
+
+ if (!usedLiteral) {
+ this.popStack();
+ }
+ if (createdStack) {
+ this.stackSlot--;
+ }
+ this.push(prefix.concat(item, ')'));
+ },
+
+ incrStack: function incrStack() {
+ this.stackSlot++;
+ if (this.stackSlot > this.stackVars.length) {
+ this.stackVars.push('stack' + this.stackSlot);
+ }
+ return this.topStackName();
+ },
+ topStackName: function topStackName() {
+ return 'stack' + this.stackSlot;
+ },
+ flushInline: function flushInline() {
+ var inlineStack = this.inlineStack;
+ this.inlineStack = [];
+ for (var i = 0, len = inlineStack.length; i < len; i++) {
+ var entry = inlineStack[i];
+ /* istanbul ignore if */
+ if (entry instanceof Literal) {
+ this.compileStack.push(entry);
+ } else {
+ var stack = this.incrStack();
+ this.pushSource([stack, ' = ', entry, ';']);
+ this.compileStack.push(stack);
+ }
+ }
+ },
+ isInline: function isInline() {
+ return this.inlineStack.length;
+ },
+
+ popStack: function popStack(wrapped) {
+ var inline = this.isInline(),
+ item = (inline ? this.inlineStack : this.compileStack).pop();
+
+ if (!wrapped && item instanceof Literal) {
+ return item.value;
+ } else {
+ if (!inline) {
+ /* istanbul ignore next */
+ if (!this.stackSlot) {
+ throw new _exception2['default']('Invalid stack pop');
+ }
+ this.stackSlot--;
+ }
+ return item;
+ }
+ },
+
+ topStack: function topStack() {
+ var stack = this.isInline() ? this.inlineStack : this.compileStack,
+ item = stack[stack.length - 1];
+
+ /* istanbul ignore if */
+ if (item instanceof Literal) {
+ return item.value;
+ } else {
+ return item;
+ }
+ },
+
+ contextName: function contextName(context) {
+ if (this.useDepths && context) {
+ return 'depths[' + context + ']';
+ } else {
+ return 'depth' + context;
+ }
+ },
+
+ quotedString: function quotedString(str) {
+ return this.source.quotedString(str);
+ },
+
+ objectLiteral: function objectLiteral(obj) {
+ return this.source.objectLiteral(obj);
+ },
+
+ aliasable: function aliasable(name) {
+ var ret = this.aliases[name];
+ if (ret) {
+ ret.referenceCount++;
+ return ret;
+ }
+
+ ret = this.aliases[name] = this.source.wrap(name);
+ ret.aliasable = true;
+ ret.referenceCount = 1;
+
+ return ret;
+ },
+
+ setupHelper: function setupHelper(paramSize, name, blockHelper) {
+ var params = [],
+ paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
+ var foundHelper = this.nameLookup('helpers', name, 'helper'),
+ callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
+
+ return {
+ params: params,
+ paramsInit: paramsInit,
+ name: foundHelper,
+ callParams: [callContext].concat(params)
+ };
+ },
+
+ setupParams: function setupParams(helper, paramSize, params) {
+ var options = {},
+ contexts = [],
+ types = [],
+ ids = [],
+ objectArgs = !params,
+ param = undefined;
+
+ if (objectArgs) {
+ params = [];
+ }
+
+ options.name = this.quotedString(helper);
+ options.hash = this.popStack();
+
+ if (this.trackIds) {
+ options.hashIds = this.popStack();
+ }
+ if (this.stringParams) {
+ options.hashTypes = this.popStack();
+ options.hashContexts = this.popStack();
+ }
+
+ var inverse = this.popStack(),
+ program = this.popStack();
+
+ // Avoid setting fn and inverse if neither are set. This allows
+ // helpers to do a check for `if (options.fn)`
+ if (program || inverse) {
+ options.fn = program || 'container.noop';
+ options.inverse = inverse || 'container.noop';
+ }
+
+ // The parameters go on to the stack in order (making sure that they are evaluated in order)
+ // so we need to pop them off the stack in reverse order
+ var i = paramSize;
+ while (i--) {
+ param = this.popStack();
+ params[i] = param;
+
+ if (this.trackIds) {
+ ids[i] = this.popStack();
+ }
+ if (this.stringParams) {
+ types[i] = this.popStack();
+ contexts[i] = this.popStack();
+ }
+ }
+
+ if (objectArgs) {
+ options.args = this.source.generateArray(params);
+ }
+
+ if (this.trackIds) {
+ options.ids = this.source.generateArray(ids);
+ }
+ if (this.stringParams) {
+ options.types = this.source.generateArray(types);
+ options.contexts = this.source.generateArray(contexts);
+ }
+
+ if (this.options.data) {
+ options.data = 'data';
+ }
+ if (this.useBlockParams) {
+ options.blockParams = 'blockParams';
+ }
+ return options;
+ },
+
+ setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
+ var options = this.setupParams(helper, paramSize, params);
+ options.loc = JSON.stringify(this.source.currentLocation);
+ options = this.objectLiteral(options);
+ if (useRegister) {
+ this.useRegister('options');
+ params.push('options');
+ return ['options=', options];
+ } else if (params) {
+ params.push(options);
+ return '';
+ } else {
+ return options;
+ }
+ }
+ };
+
+ (function () {
+ var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' ');
+
+ var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
+
+ for (var i = 0, l = reservedWords.length; i < l; i++) {
+ compilerWords[reservedWords[i]] = true;
+ }
+ })();
+
+ /**
+ * @deprecated May be removed in the next major version
+ */
+ JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
+ return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
+ };
+
+ function strictLookup(requireTerminal, compiler, parts, type) {
+ var stack = compiler.popStack(),
+ i = 0,
+ len = parts.length;
+ if (requireTerminal) {
+ len--;
+ }
+
+ for (; i < len; i++) {
+ stack = compiler.nameLookup(stack, parts[i], type);
+ }
+
+ if (requireTerminal) {
+ return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ', ', JSON.stringify(compiler.source.currentLocation), ' )'];
+ } else {
+ return stack;
+ }
+ }
+
+ exports['default'] = JavaScriptCompiler;
+ module.exports = exports['default'];
+
+} (javascriptCompiler, javascriptCompilerExports));
+
+(function (module, exports) {
+
+ exports.__esModule = true;
+ // istanbul ignore next
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var _handlebarsRuntime = handlebars_runtimeExports;
+
+ var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
+
+ // Compiler imports
+
+ var _handlebarsCompilerAst = astExports;
+
+ var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
+
+ var _handlebarsCompilerBase = base;
+
+ var _handlebarsCompilerCompiler = compiler;
+
+ var _handlebarsCompilerJavascriptCompiler = javascriptCompilerExports;
+
+ var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
+
+ var _handlebarsCompilerVisitor = visitorExports;
+
+ var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
+
+ var _handlebarsNoConflict = noConflictExports;
+
+ var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
+
+ var _create = _handlebarsRuntime2['default'].create;
+ function create() {
+ var hb = _create();
+
+ hb.compile = function (input, options) {
+ return _handlebarsCompilerCompiler.compile(input, options, hb);
+ };
+ hb.precompile = function (input, options) {
+ return _handlebarsCompilerCompiler.precompile(input, options, hb);
+ };
+
+ hb.AST = _handlebarsCompilerAst2['default'];
+ hb.Compiler = _handlebarsCompilerCompiler.Compiler;
+ hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
+ hb.Parser = _handlebarsCompilerBase.parser;
+ hb.parse = _handlebarsCompilerBase.parse;
+ hb.parseWithoutProcessing = _handlebarsCompilerBase.parseWithoutProcessing;
+
+ return hb;
+ }
+
+ var inst = create();
+ inst.create = create;
+
+ _handlebarsNoConflict2['default'](inst);
+
+ inst.Visitor = _handlebarsCompilerVisitor2['default'];
+
+ inst['default'] = inst;
+
+ exports['default'] = inst;
+ module.exports = exports['default'];
+
+} (handlebars$1, handlebarsExports));
+
+var printer$1 = {};
+
+/* eslint-disable new-cap */
+
+printer$1.__esModule = true;
+printer$1.print = print;
+printer$1.PrintVisitor = PrintVisitor;
+// istanbul ignore next
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+var _visitor = visitorExports;
+
+var _visitor2 = _interopRequireDefault(_visitor);
+
+function print(ast) {
+ return new PrintVisitor().accept(ast);
+}
+
+function PrintVisitor() {
+ this.padding = 0;
+}
+
+PrintVisitor.prototype = new _visitor2['default']();
+
+PrintVisitor.prototype.pad = function (string) {
+ var out = '';
+
+ for (var i = 0, l = this.padding; i < l; i++) {
+ out += ' ';
+ }
+
+ out += string + '\n';
+ return out;
+};
+
+PrintVisitor.prototype.Program = function (program) {
+ var out = '',
+ body = program.body,
+ i = undefined,
+ l = undefined;
+
+ if (program.blockParams) {
+ var blockParams = 'BLOCK PARAMS: [';
+ for (i = 0, l = program.blockParams.length; i < l; i++) {
+ blockParams += ' ' + program.blockParams[i];
+ }
+ blockParams += ' ]';
+ out += this.pad(blockParams);
+ }
+
+ for (i = 0, l = body.length; i < l; i++) {
+ out += this.accept(body[i]);
+ }
+
+ this.padding--;
+
+ return out;
+};
+
+PrintVisitor.prototype.MustacheStatement = function (mustache) {
+ return this.pad('{{ ' + this.SubExpression(mustache) + ' }}');
+};
+PrintVisitor.prototype.Decorator = function (mustache) {
+ return this.pad('{{ DIRECTIVE ' + this.SubExpression(mustache) + ' }}');
+};
+
+PrintVisitor.prototype.BlockStatement = PrintVisitor.prototype.DecoratorBlock = function (block) {
+ var out = '';
+
+ out += this.pad((block.type === 'DecoratorBlock' ? 'DIRECTIVE ' : '') + 'BLOCK:');
+ this.padding++;
+ out += this.pad(this.SubExpression(block));
+ if (block.program) {
+ out += this.pad('PROGRAM:');
+ this.padding++;
+ out += this.accept(block.program);
+ this.padding--;
+ }
+ if (block.inverse) {
+ if (block.program) {
+ this.padding++;
+ }
+ out += this.pad('{{^}}');
+ this.padding++;
+ out += this.accept(block.inverse);
+ this.padding--;
+ if (block.program) {
+ this.padding--;
+ }
+ }
+ this.padding--;
+
+ return out;
+};
+
+PrintVisitor.prototype.PartialStatement = function (partial) {
+ var content = 'PARTIAL:' + partial.name.original;
+ if (partial.params[0]) {
+ content += ' ' + this.accept(partial.params[0]);
+ }
+ if (partial.hash) {
+ content += ' ' + this.accept(partial.hash);
+ }
+ return this.pad('{{> ' + content + ' }}');
+};
+PrintVisitor.prototype.PartialBlockStatement = function (partial) {
+ var content = 'PARTIAL BLOCK:' + partial.name.original;
+ if (partial.params[0]) {
+ content += ' ' + this.accept(partial.params[0]);
+ }
+ if (partial.hash) {
+ content += ' ' + this.accept(partial.hash);
+ }
+
+ content += ' ' + this.pad('PROGRAM:');
+ this.padding++;
+ content += this.accept(partial.program);
+ this.padding--;
+
+ return this.pad('{{> ' + content + ' }}');
+};
+
+PrintVisitor.prototype.ContentStatement = function (content) {
+ return this.pad("CONTENT[ '" + content.value + "' ]");
+};
+
+PrintVisitor.prototype.CommentStatement = function (comment) {
+ return this.pad("{{! '" + comment.value + "' }}");
+};
+
+PrintVisitor.prototype.SubExpression = function (sexpr) {
+ var params = sexpr.params,
+ paramStrings = [],
+ hash = undefined;
+
+ for (var i = 0, l = params.length; i < l; i++) {
+ paramStrings.push(this.accept(params[i]));
+ }
+
+ params = '[' + paramStrings.join(', ') + ']';
+
+ hash = sexpr.hash ? ' ' + this.accept(sexpr.hash) : '';
+
+ return this.accept(sexpr.path) + ' ' + params + hash;
+};
+
+PrintVisitor.prototype.PathExpression = function (id) {
+ var path = id.parts.join('/');
+ return (id.data ? '@' : '') + 'PATH:' + path;
+};
+
+PrintVisitor.prototype.StringLiteral = function (string) {
+ return '"' + string.value + '"';
+};
+
+PrintVisitor.prototype.NumberLiteral = function (number) {
+ return 'NUMBER{' + number.value + '}';
+};
+
+PrintVisitor.prototype.BooleanLiteral = function (bool) {
+ return 'BOOLEAN{' + bool.value + '}';
+};
+
+PrintVisitor.prototype.UndefinedLiteral = function () {
+ return 'UNDEFINED';
+};
+
+PrintVisitor.prototype.NullLiteral = function () {
+ return 'NULL';
+};
+
+PrintVisitor.prototype.Hash = function (hash) {
+ var pairs = hash.pairs,
+ joinedPairs = [];
+
+ for (var i = 0, l = pairs.length; i < l; i++) {
+ joinedPairs.push(this.accept(pairs[i]));
+ }
+
+ return 'HASH{' + joinedPairs.join(', ') + '}';
+};
+PrintVisitor.prototype.HashPair = function (pair) {
+ return pair.key + '=' + this.accept(pair.value);
+};
+
+// USAGE:
+// var handlebars = require('handlebars');
+/* eslint-disable no-var */
+
+// var local = handlebars.create();
+
+var handlebars = handlebarsExports['default'];
+
+var printer = printer$1;
+handlebars.PrintVisitor = printer.PrintVisitor;
+handlebars.print = printer.print;
+
+var lib$1 = handlebars;
+
+// Publish a Node.js require() handler for .handlebars and .hbs files
+function extension(module, filename) {
+ var fs = require$$0$e;
+ var templateString = fs.readFileSync(filename, 'utf8');
+ module.exports = handlebars.compile(templateString);
+}
+/* istanbul ignore else */
+if (typeof commonjsRequire !== 'undefined' && commonjsRequire.extensions) {
+ commonjsRequire.extensions['.handlebars'] = extension;
+ commonjsRequire.extensions['.hbs'] = extension;
+}
+
+var constants$2 = require$$0$m;
+
+var origCwd = process.cwd;
+var cwd = null;
+
+var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
+
+process.cwd = function() {
+ if (!cwd)
+ cwd = origCwd.call(process);
+ return cwd
+};
+try {
+ process.cwd();
+} catch (er) {}
+
+// This check is needed until node.js 12 is required
+if (typeof process.chdir === 'function') {
+ var chdir = process.chdir;
+ process.chdir = function (d) {
+ cwd = null;
+ chdir.call(process, d);
+ };
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
+}
+
+var polyfills$1 = patch$1;
+
+function patch$1 (fs) {
+ // (re-)implement some things that are known busted or missing.
+
+ // lchmod, broken prior to 0.6.2
+ // back-port the fix here.
+ if (constants$2.hasOwnProperty('O_SYMLINK') &&
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
+ patchLchmod(fs);
+ }
+
+ // lutimes implementation, or no-op
+ if (!fs.lutimes) {
+ patchLutimes(fs);
+ }
+
+ // https://github.com/isaacs/node-graceful-fs/issues/4
+ // Chown should not fail on einval or eperm if non-root.
+ // It should not fail on enosys ever, as this just indicates
+ // that a fs doesn't support the intended operation.
+
+ fs.chown = chownFix(fs.chown);
+ fs.fchown = chownFix(fs.fchown);
+ fs.lchown = chownFix(fs.lchown);
+
+ fs.chmod = chmodFix(fs.chmod);
+ fs.fchmod = chmodFix(fs.fchmod);
+ fs.lchmod = chmodFix(fs.lchmod);
+
+ fs.chownSync = chownFixSync(fs.chownSync);
+ fs.fchownSync = chownFixSync(fs.fchownSync);
+ fs.lchownSync = chownFixSync(fs.lchownSync);
+
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
+
+ fs.stat = statFix(fs.stat);
+ fs.fstat = statFix(fs.fstat);
+ fs.lstat = statFix(fs.lstat);
+
+ fs.statSync = statFixSync(fs.statSync);
+ fs.fstatSync = statFixSync(fs.fstatSync);
+ fs.lstatSync = statFixSync(fs.lstatSync);
+
+ // if lchmod/lchown do not exist, then make them no-ops
+ if (fs.chmod && !fs.lchmod) {
+ fs.lchmod = function (path, mode, cb) {
+ if (cb) process.nextTick(cb);
+ };
+ fs.lchmodSync = function () {};
+ }
+ if (fs.chown && !fs.lchown) {
+ fs.lchown = function (path, uid, gid, cb) {
+ if (cb) process.nextTick(cb);
+ };
+ fs.lchownSync = function () {};
+ }
+
+ // on Windows, A/V software can lock the directory, causing this
+ // to fail with an EACCES or EPERM if the directory contains newly
+ // created files. Try again on failure, for up to 60 seconds.
+
+ // Set the timeout this long because some Windows Anti-Virus, such as Parity
+ // bit9, may lock files for up to a minute, causing npm package install
+ // failures. Also, take care to yield the scheduler. Windows scheduling gives
+ // CPU to a busy looping process, which can cause the program causing the lock
+ // contention to be starved of CPU by node, so the contention doesn't resolve.
+ if (platform === "win32") {
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
+ : (function (fs$rename) {
+ function rename (from, to, cb) {
+ var start = Date.now();
+ var backoff = 0;
+ fs$rename(from, to, function CB (er) {
+ if (er
+ && (er.code === "EACCES" || er.code === "EPERM")
+ && Date.now() - start < 60000) {
+ setTimeout(function() {
+ fs.stat(to, function (stater, st) {
+ if (stater && stater.code === "ENOENT")
+ fs$rename(from, to, CB);
+ else
+ cb(er);
+ });
+ }, backoff);
+ if (backoff < 100)
+ backoff += 10;
+ return;
+ }
+ if (cb) cb(er);
+ });
+ }
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
+ return rename
+ })(fs.rename);
+ }
+
+ // if read() returns EAGAIN, then just try it again.
+ fs.read = typeof fs.read !== 'function' ? fs.read
+ : (function (fs$read) {
+ function read (fd, buffer, offset, length, position, callback_) {
+ var callback;
+ if (callback_ && typeof callback_ === 'function') {
+ var eagCounter = 0;
+ callback = function (er, _, __) {
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
+ eagCounter ++;
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
+ }
+ callback_.apply(this, arguments);
+ };
+ }
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
+ }
+
+ // This ensures `util.promisify` works as it does for native `fs.read`.
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
+ return read
+ })(fs.read);
+
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
+ var eagCounter = 0;
+ while (true) {
+ try {
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
+ } catch (er) {
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
+ eagCounter ++;
+ continue
+ }
+ throw er
+ }
+ }
+ }})(fs.readSync);
+
+ function patchLchmod (fs) {
+ fs.lchmod = function (path, mode, callback) {
+ fs.open( path
+ , constants$2.O_WRONLY | constants$2.O_SYMLINK
+ , mode
+ , function (err, fd) {
+ if (err) {
+ if (callback) callback(err);
+ return
+ }
+ // prefer to return the chmod error, if one occurs,
+ // but still try to close, and report closing errors if they occur.
+ fs.fchmod(fd, mode, function (err) {
+ fs.close(fd, function(err2) {
+ if (callback) callback(err || err2);
+ });
+ });
+ });
+ };
+
+ fs.lchmodSync = function (path, mode) {
+ var fd = fs.openSync(path, constants$2.O_WRONLY | constants$2.O_SYMLINK, mode);
+
+ // prefer to return the chmod error, if one occurs,
+ // but still try to close, and report closing errors if they occur.
+ var threw = true;
+ var ret;
+ try {
+ ret = fs.fchmodSync(fd, mode);
+ threw = false;
+ } finally {
+ if (threw) {
+ try {
+ fs.closeSync(fd);
+ } catch (er) {}
+ } else {
+ fs.closeSync(fd);
+ }
+ }
+ return ret
+ };
+ }
+
+ function patchLutimes (fs) {
+ if (constants$2.hasOwnProperty("O_SYMLINK") && fs.futimes) {
+ fs.lutimes = function (path, at, mt, cb) {
+ fs.open(path, constants$2.O_SYMLINK, function (er, fd) {
+ if (er) {
+ if (cb) cb(er);
+ return
+ }
+ fs.futimes(fd, at, mt, function (er) {
+ fs.close(fd, function (er2) {
+ if (cb) cb(er || er2);
+ });
+ });
+ });
+ };
+
+ fs.lutimesSync = function (path, at, mt) {
+ var fd = fs.openSync(path, constants$2.O_SYMLINK);
+ var ret;
+ var threw = true;
+ try {
+ ret = fs.futimesSync(fd, at, mt);
+ threw = false;
+ } finally {
+ if (threw) {
+ try {
+ fs.closeSync(fd);
+ } catch (er) {}
+ } else {
+ fs.closeSync(fd);
+ }
+ }
+ return ret
+ };
+
+ } else if (fs.futimes) {
+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
+ fs.lutimesSync = function () {};
+ }
+ }
+
+ function chmodFix (orig) {
+ if (!orig) return orig
+ return function (target, mode, cb) {
+ return orig.call(fs, target, mode, function (er) {
+ if (chownErOk(er)) er = null;
+ if (cb) cb.apply(this, arguments);
+ })
+ }
+ }
+
+ function chmodFixSync (orig) {
+ if (!orig) return orig
+ return function (target, mode) {
+ try {
+ return orig.call(fs, target, mode)
+ } catch (er) {
+ if (!chownErOk(er)) throw er
+ }
+ }
+ }
+
+
+ function chownFix (orig) {
+ if (!orig) return orig
+ return function (target, uid, gid, cb) {
+ return orig.call(fs, target, uid, gid, function (er) {
+ if (chownErOk(er)) er = null;
+ if (cb) cb.apply(this, arguments);
+ })
+ }
+ }
+
+ function chownFixSync (orig) {
+ if (!orig) return orig
+ return function (target, uid, gid) {
+ try {
+ return orig.call(fs, target, uid, gid)
+ } catch (er) {
+ if (!chownErOk(er)) throw er
+ }
+ }
+ }
+
+ function statFix (orig) {
+ if (!orig) return orig
+ // Older versions of Node erroneously returned signed integers for
+ // uid + gid.
+ return function (target, options, cb) {
+ if (typeof options === 'function') {
+ cb = options;
+ options = null;
+ }
+ function callback (er, stats) {
+ if (stats) {
+ if (stats.uid < 0) stats.uid += 0x100000000;
+ if (stats.gid < 0) stats.gid += 0x100000000;
+ }
+ if (cb) cb.apply(this, arguments);
+ }
+ return options ? orig.call(fs, target, options, callback)
+ : orig.call(fs, target, callback)
+ }
+ }
+
+ function statFixSync (orig) {
+ if (!orig) return orig
+ // Older versions of Node erroneously returned signed integers for
+ // uid + gid.
+ return function (target, options) {
+ var stats = options ? orig.call(fs, target, options)
+ : orig.call(fs, target);
+ if (stats) {
+ if (stats.uid < 0) stats.uid += 0x100000000;
+ if (stats.gid < 0) stats.gid += 0x100000000;
+ }
+ return stats;
+ }
+ }
+
+ // ENOSYS means that the fs doesn't support the op. Just ignore
+ // that, because it doesn't matter.
+ //
+ // if there's no getuid, or if getuid() is something other
+ // than 0, and the error is EINVAL or EPERM, then just ignore
+ // it.
+ //
+ // This specific case is a silent failure in cp, install, tar,
+ // and most other unix tools that manage permissions.
+ //
+ // When running as root, or if other types of errors are
+ // encountered, then it's strict.
+ function chownErOk (er) {
+ if (!er)
+ return true
+
+ if (er.code === "ENOSYS")
+ return true
+
+ var nonroot = !process.getuid || process.getuid() !== 0;
+ if (nonroot) {
+ if (er.code === "EINVAL" || er.code === "EPERM")
+ return true
+ }
+
+ return false
+ }
+}
+
+var Stream = Stream$2.Stream;
+
+var legacyStreams = legacy$1;
+
+function legacy$1 (fs) {
+ return {
+ ReadStream: ReadStream,
+ WriteStream: WriteStream
+ }
+
+ function ReadStream (path, options) {
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
+
+ Stream.call(this);
+
+ var self = this;
+
+ this.path = path;
+ this.fd = null;
+ this.readable = true;
+ this.paused = false;
+
+ this.flags = 'r';
+ this.mode = 438; /*=0666*/
+ this.bufferSize = 64 * 1024;
+
+ options = options || {};
+
+ // Mixin options into this
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length; index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
+
+ if (this.encoding) this.setEncoding(this.encoding);
+
+ if (this.start !== undefined) {
+ if ('number' !== typeof this.start) {
+ throw TypeError('start must be a Number');
+ }
+ if (this.end === undefined) {
+ this.end = Infinity;
+ } else if ('number' !== typeof this.end) {
+ throw TypeError('end must be a Number');
+ }
+
+ if (this.start > this.end) {
+ throw new Error('start must be <= end');
+ }
+
+ this.pos = this.start;
+ }
+
+ if (this.fd !== null) {
+ process.nextTick(function() {
+ self._read();
+ });
+ return;
+ }
+
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
+ if (err) {
+ self.emit('error', err);
+ self.readable = false;
+ return;
+ }
+
+ self.fd = fd;
+ self.emit('open', fd);
+ self._read();
+ });
+ }
+
+ function WriteStream (path, options) {
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
+
+ Stream.call(this);
+
+ this.path = path;
+ this.fd = null;
+ this.writable = true;
+
+ this.flags = 'w';
+ this.encoding = 'binary';
+ this.mode = 438; /*=0666*/
+ this.bytesWritten = 0;
+
+ options = options || {};
+
+ // Mixin options into this
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length; index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
+
+ if (this.start !== undefined) {
+ if ('number' !== typeof this.start) {
+ throw TypeError('start must be a Number');
+ }
+ if (this.start < 0) {
+ throw new Error('start must be >= zero');
+ }
+
+ this.pos = this.start;
+ }
+
+ this.busy = false;
+ this._queue = [];
+
+ if (this.fd === null) {
+ this._open = fs.open;
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
+ this.flush();
+ }
+ }
+}
+
+var clone_1 = clone$2;
+
+var getPrototypeOf = Object.getPrototypeOf || function (obj) {
+ return obj.__proto__
+};
+
+function clone$2 (obj) {
+ if (obj === null || typeof obj !== 'object')
+ return obj
+
+ if (obj instanceof Object)
+ var copy = { __proto__: getPrototypeOf(obj) };
+ else
+ var copy = Object.create(null);
+
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
+ });
+
+ return copy
+}
+
+var fs$g = require$$0$e;
+var polyfills = polyfills$1;
+var legacy = legacyStreams;
+var clone$1 = clone_1;
+
+var util$4 = require$$1$7;
+
+/* istanbul ignore next - node 0.x polyfill */
+var gracefulQueue;
+var previousSymbol;
+
+/* istanbul ignore else - node 0.x polyfill */
+if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
+ gracefulQueue = Symbol.for('graceful-fs.queue');
+ // This is used in testing by future versions
+ previousSymbol = Symbol.for('graceful-fs.previous');
+} else {
+ gracefulQueue = '___graceful-fs.queue';
+ previousSymbol = '___graceful-fs.previous';
+}
+
+function noop$4 () {}
+
+function publishQueue(context, queue) {
+ Object.defineProperty(context, gracefulQueue, {
+ get: function() {
+ return queue
+ }
+ });
+}
+
+var debug$1 = noop$4;
+if (util$4.debuglog)
+ debug$1 = util$4.debuglog('gfs4');
+else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
+ debug$1 = function() {
+ var m = util$4.format.apply(util$4, arguments);
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
+ console.error(m);
+ };
+
+// Once time initialization
+if (!fs$g[gracefulQueue]) {
+ // This queue can be shared by multiple loaded instances
+ var queue = commonjsGlobal[gracefulQueue] || [];
+ publishQueue(fs$g, queue);
+
+ // Patch fs.close/closeSync to shared queue version, because we need
+ // to retry() whenever a close happens *anywhere* in the program.
+ // This is essential when multiple graceful-fs instances are
+ // in play at the same time.
+ fs$g.close = (function (fs$close) {
+ function close (fd, cb) {
+ return fs$close.call(fs$g, fd, function (err) {
+ // This function uses the graceful-fs shared queue
+ if (!err) {
+ resetQueue();
+ }
+
+ if (typeof cb === 'function')
+ cb.apply(this, arguments);
+ })
+ }
+
+ Object.defineProperty(close, previousSymbol, {
+ value: fs$close
+ });
+ return close
+ })(fs$g.close);
+
+ fs$g.closeSync = (function (fs$closeSync) {
+ function closeSync (fd) {
+ // This function uses the graceful-fs shared queue
+ fs$closeSync.apply(fs$g, arguments);
+ resetQueue();
+ }
+
+ Object.defineProperty(closeSync, previousSymbol, {
+ value: fs$closeSync
+ });
+ return closeSync
+ })(fs$g.closeSync);
+
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
+ process.on('exit', function() {
+ debug$1(fs$g[gracefulQueue]);
+ require$$5$2.equal(fs$g[gracefulQueue].length, 0);
+ });
+ }
+}
+
+if (!commonjsGlobal[gracefulQueue]) {
+ publishQueue(commonjsGlobal, fs$g[gracefulQueue]);
+}
+
+var gracefulFs = patch(clone$1(fs$g));
+if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$g.__patched) {
+ gracefulFs = patch(fs$g);
+ fs$g.__patched = true;
+}
+
+function patch (fs) {
+ // Everything that references the open() function needs to be in here
+ polyfills(fs);
+ fs.gracefulify = patch;
+
+ fs.createReadStream = createReadStream;
+ fs.createWriteStream = createWriteStream;
+ var fs$readFile = fs.readFile;
+ fs.readFile = readFile;
+ function readFile (path, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null;
+
+ return go$readFile(path, options, cb)
+
+ function go$readFile (path, options, cb, startTime) {
+ return fs$readFile(path, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments);
+ }
+ })
+ }
+ }
+
+ var fs$writeFile = fs.writeFile;
+ fs.writeFile = writeFile;
+ function writeFile (path, data, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null;
+
+ return go$writeFile(path, data, options, cb)
+
+ function go$writeFile (path, data, options, cb, startTime) {
+ return fs$writeFile(path, data, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments);
+ }
+ })
+ }
+ }
+
+ var fs$appendFile = fs.appendFile;
+ if (fs$appendFile)
+ fs.appendFile = appendFile;
+ function appendFile (path, data, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null;
+
+ return go$appendFile(path, data, options, cb)
+
+ function go$appendFile (path, data, options, cb, startTime) {
+ return fs$appendFile(path, data, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments);
+ }
+ })
+ }
+ }
+
+ var fs$copyFile = fs.copyFile;
+ if (fs$copyFile)
+ fs.copyFile = copyFile;
+ function copyFile (src, dest, flags, cb) {
+ if (typeof flags === 'function') {
+ cb = flags;
+ flags = 0;
+ }
+ return go$copyFile(src, dest, flags, cb)
+
+ function go$copyFile (src, dest, flags, cb, startTime) {
+ return fs$copyFile(src, dest, flags, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments);
+ }
+ })
+ }
+ }
+
+ var fs$readdir = fs.readdir;
+ fs.readdir = readdir;
+ var noReaddirOptionVersions = /^v[0-5]\./;
+ function readdir (path, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null;
+
+ var go$readdir = noReaddirOptionVersions.test(process.version)
+ ? function go$readdir (path, options, cb, startTime) {
+ return fs$readdir(path, fs$readdirCallback(
+ path, options, cb, startTime
+ ))
+ }
+ : function go$readdir (path, options, cb, startTime) {
+ return fs$readdir(path, options, fs$readdirCallback(
+ path, options, cb, startTime
+ ))
+ };
+
+ return go$readdir(path, options, cb)
+
+ function fs$readdirCallback (path, options, cb, startTime) {
+ return function (err, files) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([
+ go$readdir,
+ [path, options, cb],
+ err,
+ startTime || Date.now(),
+ Date.now()
+ ]);
+ else {
+ if (files && files.sort)
+ files.sort();
+
+ if (typeof cb === 'function')
+ cb.call(this, err, files);
+ }
+ }
+ }
+ }
+
+ if (process.version.substr(0, 4) === 'v0.8') {
+ var legStreams = legacy(fs);
+ ReadStream = legStreams.ReadStream;
+ WriteStream = legStreams.WriteStream;
+ }
+
+ var fs$ReadStream = fs.ReadStream;
+ if (fs$ReadStream) {
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
+ ReadStream.prototype.open = ReadStream$open;
+ }
+
+ var fs$WriteStream = fs.WriteStream;
+ if (fs$WriteStream) {
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
+ WriteStream.prototype.open = WriteStream$open;
+ }
+
+ Object.defineProperty(fs, 'ReadStream', {
+ get: function () {
+ return ReadStream
+ },
+ set: function (val) {
+ ReadStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(fs, 'WriteStream', {
+ get: function () {
+ return WriteStream
+ },
+ set: function (val) {
+ WriteStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+
+ // legacy names
+ var FileReadStream = ReadStream;
+ Object.defineProperty(fs, 'FileReadStream', {
+ get: function () {
+ return FileReadStream
+ },
+ set: function (val) {
+ FileReadStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ var FileWriteStream = WriteStream;
+ Object.defineProperty(fs, 'FileWriteStream', {
+ get: function () {
+ return FileWriteStream
+ },
+ set: function (val) {
+ FileWriteStream = val;
+ },
+ enumerable: true,
+ configurable: true
+ });
+
+ function ReadStream (path, options) {
+ if (this instanceof ReadStream)
+ return fs$ReadStream.apply(this, arguments), this
+ else
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
+ }
+
+ function ReadStream$open () {
+ var that = this;
+ open(that.path, that.flags, that.mode, function (err, fd) {
+ if (err) {
+ if (that.autoClose)
+ that.destroy();
+
+ that.emit('error', err);
+ } else {
+ that.fd = fd;
+ that.emit('open', fd);
+ that.read();
+ }
+ });
+ }
+
+ function WriteStream (path, options) {
+ if (this instanceof WriteStream)
+ return fs$WriteStream.apply(this, arguments), this
+ else
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
+ }
+
+ function WriteStream$open () {
+ var that = this;
+ open(that.path, that.flags, that.mode, function (err, fd) {
+ if (err) {
+ that.destroy();
+ that.emit('error', err);
+ } else {
+ that.fd = fd;
+ that.emit('open', fd);
+ }
+ });
+ }
+
+ function createReadStream (path, options) {
+ return new fs.ReadStream(path, options)
+ }
+
+ function createWriteStream (path, options) {
+ return new fs.WriteStream(path, options)
+ }
+
+ var fs$open = fs.open;
+ fs.open = open;
+ function open (path, flags, mode, cb) {
+ if (typeof mode === 'function')
+ cb = mode, mode = null;
+
+ return go$open(path, flags, mode, cb)
+
+ function go$open (path, flags, mode, cb, startTime) {
+ return fs$open(path, flags, mode, function (err, fd) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]);
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments);
+ }
+ })
+ }
+ }
+
+ return fs
+}
+
+function enqueue (elem) {
+ debug$1('ENQUEUE', elem[0].name, elem[1]);
+ fs$g[gracefulQueue].push(elem);
+ retry();
+}
+
+// keep track of the timeout between retry() calls
+var retryTimer;
+
+// reset the startTime and lastTime to now
+// this resets the start of the 60 second overall timeout as well as the
+// delay between attempts so that we'll retry these jobs sooner
+function resetQueue () {
+ var now = Date.now();
+ for (var i = 0; i < fs$g[gracefulQueue].length; ++i) {
+ // entries that are only a length of 2 are from an older version, don't
+ // bother modifying those since they'll be retried anyway.
+ if (fs$g[gracefulQueue][i].length > 2) {
+ fs$g[gracefulQueue][i][3] = now; // startTime
+ fs$g[gracefulQueue][i][4] = now; // lastTime
+ }
+ }
+ // call retry to make sure we're actively processing the queue
+ retry();
+}
+
+function retry () {
+ // clear the timer and remove it to help prevent unintended concurrency
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+
+ if (fs$g[gracefulQueue].length === 0)
+ return
+
+ var elem = fs$g[gracefulQueue].shift();
+ var fn = elem[0];
+ var args = elem[1];
+ // these items may be unset if they were added by an older graceful-fs
+ var err = elem[2];
+ var startTime = elem[3];
+ var lastTime = elem[4];
+
+ // if we don't have a startTime we have no way of knowing if we've waited
+ // long enough, so go ahead and retry this item now
+ if (startTime === undefined) {
+ debug$1('RETRY', fn.name, args);
+ fn.apply(null, args);
+ } else if (Date.now() - startTime >= 60000) {
+ // it's been more than 60 seconds total, bail now
+ debug$1('TIMEOUT', fn.name, args);
+ var cb = args.pop();
+ if (typeof cb === 'function')
+ cb.call(null, err);
+ } else {
+ // the amount of time between the last attempt and right now
+ var sinceAttempt = Date.now() - lastTime;
+ // the amount of time between when we first tried, and when we last tried
+ // rounded up to at least 1
+ var sinceStart = Math.max(lastTime - startTime, 1);
+ // backoff. wait longer than the total time we've been retrying, but only
+ // up to a maximum of 100ms
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
+ // it's been long enough since the last retry, do it again
+ if (sinceAttempt >= desiredDelay) {
+ debug$1('RETRY', fn.name, args);
+ fn.apply(null, args.concat([startTime]));
+ } else {
+ // if we can't do this job yet, push it to the end of the queue
+ // and let the next iteration check again
+ fs$g[gracefulQueue].push(elem);
+ }
+ }
+
+ // schedule our next run if one isn't already scheduled
+ if (retryTimer === undefined) {
+ retryTimer = setTimeout(retry, 0);
+ }
+}
+
+var old$1 = {};
+
+// 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 pathModule = require$$0$c;
+var isWindows$1 = process.platform === 'win32';
+var fs$f = require$$0$e;
+
+// JavaScript implementation of realpath, ported from node pre-v6
+
+var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
+
+function rethrow() {
+ // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
+ // is fairly slow to generate.
+ var callback;
+ if (DEBUG) {
+ var backtrace = new Error;
+ callback = debugCallback;
+ } else
+ callback = missingCallback;
+
+ return callback;
+
+ function debugCallback(err) {
+ if (err) {
+ backtrace.message = err.message;
+ err = backtrace;
+ missingCallback(err);
+ }
+ }
+
+ function missingCallback(err) {
+ if (err) {
+ if (process.throwDeprecation)
+ throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
+ else if (!process.noDeprecation) {
+ var msg = 'fs: missing callback ' + (err.stack || err.message);
+ if (process.traceDeprecation)
+ console.trace(msg);
+ else
+ console.error(msg);
+ }
+ }
+ }
+}
+
+function maybeCallback(cb) {
+ return typeof cb === 'function' ? cb : rethrow();
+}
+
+pathModule.normalize;
+
+// Regexp that finds the next partion of a (partial) path
+// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
+if (isWindows$1) {
+ var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
+} else {
+ var nextPartRe = /(.*?)(?:[\/]+|$)/g;
+}
+
+// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
+if (isWindows$1) {
+ var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
+} else {
+ var splitRootRe = /^[\/]*/;
+}
+
+old$1.realpathSync = function realpathSync(p, cache) {
+ // make p is absolute
+ p = pathModule.resolve(p);
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+ return cache[p];
+ }
+
+ var original = p,
+ seenLinks = {},
+ knownHard = {};
+
+ // current character position in p
+ var pos;
+ // the partial path so far, including a trailing slash if any
+ var current;
+ // the partial path without a trailing slash (except when pointing at a root)
+ var base;
+ // the partial path scanned in the previous round, with slash
+ var previous;
+
+ start();
+
+ function start() {
+ // Skip over roots
+ var m = splitRootRe.exec(p);
+ pos = m[0].length;
+ current = m[0];
+ base = m[0];
+ previous = '';
+
+ // On windows, check that the root exists. On unix there is no need.
+ if (isWindows$1 && !knownHard[base]) {
+ fs$f.lstatSync(base);
+ knownHard[base] = true;
+ }
+ }
+
+ // walk down the path, swapping out linked pathparts for their real
+ // values
+ // NB: p.length changes.
+ while (pos < p.length) {
+ // find the next part
+ nextPartRe.lastIndex = pos;
+ var result = nextPartRe.exec(p);
+ previous = current;
+ current += result[0];
+ base = previous + result[1];
+ pos = nextPartRe.lastIndex;
+
+ // continue if not a symlink
+ if (knownHard[base] || (cache && cache[base] === base)) {
+ continue;
+ }
+
+ var resolvedLink;
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+ // some known symbolic link. no need to stat again.
+ resolvedLink = cache[base];
+ } else {
+ var stat = fs$f.lstatSync(base);
+ if (!stat.isSymbolicLink()) {
+ knownHard[base] = true;
+ if (cache) cache[base] = base;
+ continue;
+ }
+
+ // read the link if it wasn't read before
+ // dev/ino always return 0 on windows, so skip the check.
+ var linkTarget = null;
+ if (!isWindows$1) {
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+ if (seenLinks.hasOwnProperty(id)) {
+ linkTarget = seenLinks[id];
+ }
+ }
+ if (linkTarget === null) {
+ fs$f.statSync(base);
+ linkTarget = fs$f.readlinkSync(base);
+ }
+ resolvedLink = pathModule.resolve(previous, linkTarget);
+ // track this, if given a cache.
+ if (cache) cache[base] = resolvedLink;
+ if (!isWindows$1) seenLinks[id] = linkTarget;
+ }
+
+ // resolve the link, then start over
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
+ start();
+ }
+
+ if (cache) cache[original] = p;
+
+ return p;
+};
+
+
+old$1.realpath = function realpath(p, cache, cb) {
+ if (typeof cb !== 'function') {
+ cb = maybeCallback(cache);
+ cache = null;
+ }
+
+ // make p is absolute
+ p = pathModule.resolve(p);
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
+ return process.nextTick(cb.bind(null, null, cache[p]));
+ }
+
+ var original = p,
+ seenLinks = {},
+ knownHard = {};
+
+ // current character position in p
+ var pos;
+ // the partial path so far, including a trailing slash if any
+ var current;
+ // the partial path without a trailing slash (except when pointing at a root)
+ var base;
+ // the partial path scanned in the previous round, with slash
+ var previous;
+
+ start();
+
+ function start() {
+ // Skip over roots
+ var m = splitRootRe.exec(p);
+ pos = m[0].length;
+ current = m[0];
+ base = m[0];
+ previous = '';
+
+ // On windows, check that the root exists. On unix there is no need.
+ if (isWindows$1 && !knownHard[base]) {
+ fs$f.lstat(base, function(err) {
+ if (err) return cb(err);
+ knownHard[base] = true;
+ LOOP();
+ });
+ } else {
+ process.nextTick(LOOP);
+ }
+ }
+
+ // walk down the path, swapping out linked pathparts for their real
+ // values
+ function LOOP() {
+ // stop if scanned past end of path
+ if (pos >= p.length) {
+ if (cache) cache[original] = p;
+ return cb(null, p);
+ }
+
+ // find the next part
+ nextPartRe.lastIndex = pos;
+ var result = nextPartRe.exec(p);
+ previous = current;
+ current += result[0];
+ base = previous + result[1];
+ pos = nextPartRe.lastIndex;
+
+ // continue if not a symlink
+ if (knownHard[base] || (cache && cache[base] === base)) {
+ return process.nextTick(LOOP);
+ }
+
+ if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
+ // known symbolic link. no need to stat again.
+ return gotResolvedLink(cache[base]);
+ }
+
+ return fs$f.lstat(base, gotStat);
+ }
+
+ function gotStat(err, stat) {
+ if (err) return cb(err);
+
+ // if not a symlink, skip to the next path part
+ if (!stat.isSymbolicLink()) {
+ knownHard[base] = true;
+ if (cache) cache[base] = base;
+ return process.nextTick(LOOP);
+ }
+
+ // stat & read the link if not read before
+ // call gotTarget as soon as the link target is known
+ // dev/ino always return 0 on windows, so skip the check.
+ if (!isWindows$1) {
+ var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
+ if (seenLinks.hasOwnProperty(id)) {
+ return gotTarget(null, seenLinks[id], base);
+ }
+ }
+ fs$f.stat(base, function(err) {
+ if (err) return cb(err);
+
+ fs$f.readlink(base, function(err, target) {
+ if (!isWindows$1) seenLinks[id] = target;
+ gotTarget(err, target);
+ });
+ });
+ }
+
+ function gotTarget(err, target, base) {
+ if (err) return cb(err);
+
+ var resolvedLink = pathModule.resolve(previous, target);
+ if (cache) cache[base] = resolvedLink;
+ gotResolvedLink(resolvedLink);
+ }
+
+ function gotResolvedLink(resolvedLink) {
+ // resolve the link, then start over
+ p = pathModule.resolve(resolvedLink, p.slice(pos));
+ start();
+ }
+};
+
+var fs_realpath = realpath;
+realpath.realpath = realpath;
+realpath.sync = realpathSync;
+realpath.realpathSync = realpathSync;
+realpath.monkeypatch = monkeypatch;
+realpath.unmonkeypatch = unmonkeypatch;
+
+var fs$e = require$$0$e;
+var origRealpath = fs$e.realpath;
+var origRealpathSync = fs$e.realpathSync;
+
+var version$7 = process.version;
+var ok = /^v[0-5]\./.test(version$7);
+var old = old$1;
+
+function newError (er) {
+ return er && er.syscall === 'realpath' && (
+ er.code === 'ELOOP' ||
+ er.code === 'ENOMEM' ||
+ er.code === 'ENAMETOOLONG'
+ )
+}
+
+function realpath (p, cache, cb) {
+ if (ok) {
+ return origRealpath(p, cache, cb)
+ }
+
+ if (typeof cache === 'function') {
+ cb = cache;
+ cache = null;
+ }
+ origRealpath(p, cache, function (er, result) {
+ if (newError(er)) {
+ old.realpath(p, cache, cb);
+ } else {
+ cb(er, result);
+ }
+ });
+}
+
+function realpathSync (p, cache) {
+ if (ok) {
+ return origRealpathSync(p, cache)
+ }
+
+ try {
+ return origRealpathSync(p, cache)
+ } catch (er) {
+ if (newError(er)) {
+ return old.realpathSync(p, cache)
+ } else {
+ throw er
+ }
+ }
+}
+
+function monkeypatch () {
+ fs$e.realpath = realpath;
+ fs$e.realpathSync = realpathSync;
+}
+
+function unmonkeypatch () {
+ fs$e.realpath = origRealpath;
+ fs$e.realpathSync = origRealpathSync;
+}
+
+const isWindows = typeof process === 'object' &&
+ process &&
+ process.platform === 'win32';
+var path$h = isWindows ? { sep: '\\' } : { sep: '/' };
+
+var balancedMatch = balanced$1;
+function balanced$1(a, b, str) {
+ if (a instanceof RegExp) a = maybeMatch(a, str);
+ if (b instanceof RegExp) b = maybeMatch(b, str);
+
+ var r = range$1(a, b, str);
+
+ return r && {
+ start: r[0],
+ end: r[1],
+ pre: str.slice(0, r[0]),
+ body: str.slice(r[0] + a.length, r[1]),
+ post: str.slice(r[1] + b.length)
+ };
+}
+
+function maybeMatch(reg, str) {
+ var m = str.match(reg);
+ return m ? m[0] : null;
+}
+
+balanced$1.range = range$1;
+function range$1(a, b, str) {
+ var begs, beg, left, right, result;
+ var ai = str.indexOf(a);
+ var bi = str.indexOf(b, ai + 1);
+ var i = ai;
+
+ if (ai >= 0 && bi > 0) {
+ if(a===b) {
+ return [ai, bi];
+ }
+ begs = [];
+ left = str.length;
+
+ while (i >= 0 && !result) {
+ if (i == ai) {
+ begs.push(i);
+ ai = str.indexOf(a, i + 1);
+ } else if (begs.length == 1) {
+ result = [ begs.pop(), bi ];
+ } else {
+ beg = begs.pop();
+ if (beg < left) {
+ left = beg;
+ right = bi;
+ }
+
+ bi = str.indexOf(b, i + 1);
+ }
+
+ i = ai < bi && ai >= 0 ? ai : bi;
+ }
+
+ if (begs.length) {
+ result = [ left, right ];
+ }
+ }
+
+ return result;
+}
+
+var balanced = balancedMatch;
+
+var braceExpansion = expandTop;
+
+var escSlash = '\0SLASH'+Math.random()+'\0';
+var escOpen = '\0OPEN'+Math.random()+'\0';
+var escClose = '\0CLOSE'+Math.random()+'\0';
+var escComma = '\0COMMA'+Math.random()+'\0';
+var escPeriod = '\0PERIOD'+Math.random()+'\0';
+
+function numeric(str) {
+ return parseInt(str, 10) == str
+ ? parseInt(str, 10)
+ : str.charCodeAt(0);
+}
+
+function escapeBraces(str) {
+ return str.split('\\\\').join(escSlash)
+ .split('\\{').join(escOpen)
+ .split('\\}').join(escClose)
+ .split('\\,').join(escComma)
+ .split('\\.').join(escPeriod);
+}
+
+function unescapeBraces(str) {
+ return str.split(escSlash).join('\\')
+ .split(escOpen).join('{')
+ .split(escClose).join('}')
+ .split(escComma).join(',')
+ .split(escPeriod).join('.');
+}
+
+
+// Basically just str.split(","), but handling cases
+// where we have nested braced sections, which should be
+// treated as individual members, like {a,{b,c},d}
+function parseCommaParts(str) {
+ if (!str)
+ return [''];
+
+ var parts = [];
+ var m = balanced('{', '}', str);
+
+ if (!m)
+ return str.split(',');
+
+ var pre = m.pre;
+ var body = m.body;
+ var post = m.post;
+ var p = pre.split(',');
+
+ p[p.length-1] += '{' + body + '}';
+ var postParts = parseCommaParts(post);
+ if (post.length) {
+ p[p.length-1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
+
+ parts.push.apply(parts, p);
+
+ return parts;
+}
+
+function expandTop(str) {
+ if (!str)
+ return [];
+
+ // I don't know why Bash 4.3 does this, but it does.
+ // Anything starting with {} will have the first two bytes preserved
+ // but *only* at the top level, so {},a}b will not expand to anything,
+ // but a{},b}c will be expanded to [a}c,abc].
+ // One could argue that this is a bug in Bash, but since the goal of
+ // this module is to match Bash's rules, we escape a leading {}
+ if (str.substr(0, 2) === '{}') {
+ str = '\\{\\}' + str.substr(2);
+ }
+
+ return expand$1(escapeBraces(str), true).map(unescapeBraces);
+}
+
+function embrace(str) {
+ return '{' + str + '}';
+}
+function isPadded(el) {
+ return /^-?0\d/.test(el);
+}
+
+function lte(i, y) {
+ return i <= y;
+}
+function gte(i, y) {
+ return i >= y;
+}
+
+function expand$1(str, isTop) {
+ var expansions = [];
+
+ var m = balanced('{', '}', str);
+ if (!m) return [str];
+
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
+ var pre = m.pre;
+ var post = m.post.length
+ ? expand$1(m.post, false)
+ : [''];
+
+ if (/\$$/.test(m.pre)) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre+ '{' + m.body + '}' + post[k];
+ expansions.push(expansion);
+ }
+ } else {
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ var isSequence = isNumericSequence || isAlphaSequence;
+ var isOptions = m.body.indexOf(',') >= 0;
+ if (!isSequence && !isOptions) {
+ // {a},b}
+ if (m.post.match(/,.*\}/)) {
+ str = m.pre + '{' + m.body + escClose + m.post;
+ return expand$1(str);
+ }
+ return [str];
+ }
+
+ var n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ } else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1) {
+ // x{{a,b}}y ==> x{a}y x{b}y
+ n = expand$1(n[0], false).map(embrace);
+ if (n.length === 1) {
+ return post.map(function(p) {
+ return m.pre + n[0] + p;
+ });
+ }
+ }
+ }
+
+ // at this point, n is the parts, and we know it's not a comma set
+ // with a single entry.
+ var N;
+
+ if (isSequence) {
+ var x = numeric(n[0]);
+ var y = numeric(n[1]);
+ var width = Math.max(n[0].length, n[1].length);
+ var incr = n.length == 3
+ ? Math.abs(numeric(n[2]))
+ : 1;
+ var test = lte;
+ var reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
+ }
+ var pad = n.some(isPadded);
+
+ N = [];
+
+ for (var i = x; test(i, y); i += incr) {
+ var c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === '\\')
+ c = '';
+ } else {
+ c = String(i);
+ if (pad) {
+ var need = width - c.length;
+ if (need > 0) {
+ var z = new Array(need + 1).join('0');
+ if (i < 0)
+ c = '-' + z + c.slice(1);
+ else
+ c = z + c;
+ }
+ }
+ }
+ N.push(c);
+ }
+ } else {
+ N = [];
+
+ for (var j = 0; j < n.length; j++) {
+ N.push.apply(N, expand$1(n[j], false));
+ }
+ }
+
+ for (var j = 0; j < N.length; j++) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion)
+ expansions.push(expansion);
+ }
+ }
+ }
+
+ return expansions;
+}
+
+const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => {
+ assertValidPattern(pattern);
+
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false
+ }
+
+ return new Minimatch$1(pattern, options).match(p)
+};
+
+var minimatch_1 = minimatch$1;
+
+const path$g = path$h;
+minimatch$1.sep = path$g.sep;
+
+const GLOBSTAR = Symbol('globstar **');
+minimatch$1.GLOBSTAR = GLOBSTAR;
+const expand = braceExpansion;
+
+const plTypes = {
+ '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
+ '?': { open: '(?:', close: ')?' },
+ '+': { open: '(?:', close: ')+' },
+ '*': { open: '(?:', close: ')*' },
+ '@': { open: '(?:', close: ')' }
+};
+
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+const qmark = '[^/]';
+
+// * => any number of characters
+const star = qmark + '*?';
+
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
+
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
+
+// "abc" -> { a:true, b:true, c:true }
+const charSet = s => s.split('').reduce((set, c) => {
+ set[c] = true;
+ return set
+}, {});
+
+// characters that need to be escaped in RegExp.
+const reSpecials = charSet('().*{}+?[]^$\\!');
+
+// characters that indicate we have to add the pattern start
+const addPatternStartSet = charSet('[.(');
+
+// normalizes slashes.
+const slashSplit = /\/+/;
+
+minimatch$1.filter = (pattern, options = {}) =>
+ (p, i, list) => minimatch$1(p, pattern, options);
+
+const ext = (a, b = {}) => {
+ const t = {};
+ Object.keys(a).forEach(k => t[k] = a[k]);
+ Object.keys(b).forEach(k => t[k] = b[k]);
+ return t
+};
+
+minimatch$1.defaults = def => {
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+ return minimatch$1
+ }
+
+ const orig = minimatch$1;
+
+ const m = (p, pattern, options) => orig(p, pattern, ext(def, options));
+ m.Minimatch = class Minimatch extends orig.Minimatch {
+ constructor (pattern, options) {
+ super(pattern, ext(def, options));
+ }
+ };
+ m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch;
+ m.filter = (pattern, options) => orig.filter(pattern, ext(def, options));
+ m.defaults = options => orig.defaults(ext(def, options));
+ m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options));
+ m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options));
+ m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options));
+
+ return m
+};
+
+
+
+
+
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options);
+
+const braceExpand = (pattern, options = {}) => {
+ assertValidPattern(pattern);
+
+ // Thanks to Yeting Li for
+ // improving this regexp to avoid a ReDOS vulnerability.
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+ // shortcut. no need to expand.
+ return [pattern]
+ }
+
+ return expand(pattern)
+};
+
+const MAX_PATTERN_LENGTH = 1024 * 64;
+const assertValidPattern = pattern => {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('invalid pattern')
+ }
+
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError('pattern is too long')
+ }
+};
+
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion. Otherwise, any series
+// of * is equivalent to a single *. Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+const SUBPARSE = Symbol('subparse');
+
+minimatch$1.makeRe = (pattern, options) =>
+ new Minimatch$1(pattern, options || {}).makeRe();
+
+minimatch$1.match = (list, pattern, options = {}) => {
+ const mm = new Minimatch$1(pattern, options);
+ list = list.filter(f => mm.match(f));
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern);
+ }
+ return list
+};
+
+// replace stuff like \* with *
+const globUnescape = s => s.replace(/\\(.)/g, '$1');
+const charUnescape = s => s.replace(/\\([^-\]])/g, '$1');
+const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&');
+
+let Minimatch$1 = class Minimatch {
+ constructor (pattern, options) {
+ assertValidPattern(pattern);
+
+ if (!options) options = {};
+
+ this.options = options;
+ this.set = [];
+ this.pattern = pattern;
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
+ options.allowWindowsEscape === false;
+ if (this.windowsPathsNoEscape) {
+ this.pattern = this.pattern.replace(/\\/g, '/');
+ }
+ this.regexp = null;
+ this.negate = false;
+ this.comment = false;
+ this.empty = false;
+ this.partial = !!options.partial;
+
+ // make the set of regexps etc.
+ this.make();
+ }
+
+ debug () {}
+
+ make () {
+ const pattern = this.pattern;
+ const options = this.options;
+
+ // empty patterns and comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ this.comment = true;
+ return
+ }
+ if (!pattern) {
+ this.empty = true;
+ return
+ }
+
+ // step 1: figure out negation, etc.
+ this.parseNegate();
+
+ // step 2: expand braces
+ let set = this.globSet = this.braceExpand();
+
+ if (options.debug) this.debug = (...args) => console.error(...args);
+
+ this.debug(this.pattern, set);
+
+ // step 3: now we have a set, so turn each one into a series of path-portion
+ // matching patterns.
+ // These will be regexps, except in the case of "**", which is
+ // set to the GLOBSTAR object for globstar behavior,
+ // and will not contain any / characters
+ set = this.globParts = set.map(s => s.split(slashSplit));
+
+ this.debug(this.pattern, set);
+
+ // glob --> regexps
+ set = set.map((s, si, set) => s.map(this.parse, this));
+
+ this.debug(this.pattern, set);
+
+ // filter out everything that didn't compile properly.
+ set = set.filter(s => s.indexOf(false) === -1);
+
+ this.debug(this.pattern, set);
+
+ this.set = set;
+ }
+
+ parseNegate () {
+ if (this.options.nonegate) return
+
+ const pattern = this.pattern;
+ let negate = false;
+ let negateOffset = 0;
+
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+ negate = !negate;
+ negateOffset++;
+ }
+
+ if (negateOffset) this.pattern = pattern.slice(negateOffset);
+ this.negate = negate;
+ }
+
+ // set partial to true to test if, for example,
+ // "/a/b" matches the start of "/*/b/*/d"
+ // Partial means, if you run out of file before you run
+ // out of pattern, then that's fine, as long as all
+ // the parts match.
+ matchOne (file, pattern, partial) {
+ var options = this.options;
+
+ this.debug('matchOne',
+ { 'this': this, file: file, pattern: pattern });
+
+ this.debug('matchOne', file.length, pattern.length);
+
+ for (var fi = 0,
+ pi = 0,
+ fl = file.length,
+ pl = pattern.length
+ ; (fi < fl) && (pi < pl)
+ ; fi++, pi++) {
+ this.debug('matchOne loop');
+ var p = pattern[pi];
+ var f = file[fi];
+
+ this.debug(pattern, p, f);
+
+ // should be impossible.
+ // some invalid regexp stuff in the set.
+ /* istanbul ignore if */
+ if (p === false) return false
+
+ if (p === GLOBSTAR) {
+ this.debug('GLOBSTAR', [pattern, p, f]);
+
+ // "**"
+ // a/**/b/**/c would match the following:
+ // a/b/x/y/z/c
+ // a/x/y/z/b/c
+ // a/b/x/b/x/c
+ // a/b/c
+ // To do this, take the rest of the pattern after
+ // the **, and see if it would match the file remainder.
+ // If so, return success.
+ // If not, the ** "swallows" a segment, and try again.
+ // This is recursively awful.
+ //
+ // a/**/b/**/c matching a/b/x/y/z/c
+ // - a matches a
+ // - doublestar
+ // - matchOne(b/x/y/z/c, b/**/c)
+ // - b matches b
+ // - doublestar
+ // - matchOne(x/y/z/c, c) -> no
+ // - matchOne(y/z/c, c) -> no
+ // - matchOne(z/c, c) -> no
+ // - matchOne(c, c) yes, hit
+ var fr = fi;
+ var pr = pi + 1;
+ if (pr === pl) {
+ this.debug('** at the end');
+ // a ** at the end will just swallow the rest.
+ // We have found a match.
+ // however, it will not swallow /.x, unless
+ // options.dot is set.
+ // . and .. are *never* matched by **, for explosively
+ // exponential reasons.
+ for (; fi < fl; fi++) {
+ if (file[fi] === '.' || file[fi] === '..' ||
+ (!options.dot && file[fi].charAt(0) === '.')) return false
+ }
+ return true
+ }
+
+ // ok, let's see if we can swallow whatever we can.
+ while (fr < fl) {
+ var swallowee = file[fr];
+
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+
+ // XXX remove this slice. Just pass the start index.
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+ this.debug('globstar found match!', fr, fl, swallowee);
+ // found a match.
+ return true
+ } else {
+ // can't swallow "." or ".." ever.
+ // can only swallow ".foo" when explicitly asked.
+ if (swallowee === '.' || swallowee === '..' ||
+ (!options.dot && swallowee.charAt(0) === '.')) {
+ this.debug('dot detected!', file, fr, pattern, pr);
+ break
+ }
+
+ // ** swallows a segment, and continue.
+ this.debug('globstar swallow a segment, and continue');
+ fr++;
+ }
+ }
+
+ // no match was found.
+ // However, in partial mode, we can't say this is necessarily over.
+ // If there's more *pattern* left, then
+ /* istanbul ignore if */
+ if (partial) {
+ // ran out of file
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+ if (fr === fl) return true
+ }
+ return false
+ }
+
+ // something other than **
+ // non-magic patterns just have to match exactly
+ // patterns with magic have been turned into regexps.
+ var hit;
+ if (typeof p === 'string') {
+ hit = f === p;
+ this.debug('string match', p, f, hit);
+ } else {
+ hit = f.match(p);
+ this.debug('pattern match', p, f, hit);
+ }
+
+ if (!hit) return false
+ }
+
+ // Note: ending in / means that we'll get a final ""
+ // at the end of the pattern. This can only match a
+ // corresponding "" at the end of the file.
+ // If the file ends in /, then it can only match a
+ // a pattern that ends in /, unless the pattern just
+ // doesn't have any more for it. But, a/b/ should *not*
+ // match "a/b/*", even though "" matches against the
+ // [^/]*? pattern, except in partial mode, where it might
+ // simply not be reached yet.
+ // However, a/b/ should still satisfy a/*
+
+ // now either we fell off the end of the pattern, or we're done.
+ if (fi === fl && pi === pl) {
+ // ran out of pattern and filename at the same time.
+ // an exact hit!
+ return true
+ } else if (fi === fl) {
+ // ran out of file, but still had pattern left.
+ // this is ok if we're doing the match as part of
+ // a glob fs traversal.
+ return partial
+ } else /* istanbul ignore else */ if (pi === pl) {
+ // ran out of pattern, still have file left.
+ // this is only acceptable if we're on the very last
+ // empty segment of a file with a trailing slash.
+ // a/* should match a/b/
+ return (fi === fl - 1) && (file[fi] === '')
+ }
+
+ // should be unreachable.
+ /* istanbul ignore next */
+ throw new Error('wtf?')
+ }
+
+ braceExpand () {
+ return braceExpand(this.pattern, this.options)
+ }
+
+ parse (pattern, isSub) {
+ assertValidPattern(pattern);
+
+ const options = this.options;
+
+ // shortcuts
+ if (pattern === '**') {
+ if (!options.noglobstar)
+ return GLOBSTAR
+ else
+ pattern = '*';
+ }
+ if (pattern === '') return ''
+
+ let re = '';
+ let hasMagic = false;
+ let escaping = false;
+ // ? => one single character
+ const patternListStack = [];
+ const negativeLists = [];
+ let stateChar;
+ let inClass = false;
+ let reClassStart = -1;
+ let classStart = -1;
+ let cs;
+ let pl;
+ let sp;
+ // . and .. never match anything that doesn't start with .,
+ // even when options.dot is set. However, if the pattern
+ // starts with ., then traversal patterns can match.
+ let dotTravAllowed = pattern.charAt(0) === '.';
+ let dotFileAllowed = options.dot || dotTravAllowed;
+ const patternStart = () =>
+ dotTravAllowed
+ ? ''
+ : dotFileAllowed
+ ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))'
+ : '(?!\\.)';
+ const subPatternStart = (p) =>
+ p.charAt(0) === '.'
+ ? ''
+ : options.dot
+ ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))'
+ : '(?!\\.)';
+
+
+ const clearStateChar = () => {
+ if (stateChar) {
+ // we had some state-tracking character
+ // that wasn't consumed by this pass.
+ switch (stateChar) {
+ case '*':
+ re += star;
+ hasMagic = true;
+ break
+ case '?':
+ re += qmark;
+ hasMagic = true;
+ break
+ default:
+ re += '\\' + stateChar;
+ break
+ }
+ this.debug('clearStateChar %j %j', stateChar, re);
+ stateChar = false;
+ }
+ };
+
+ for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
+ this.debug('%s\t%s %s %j', pattern, i, re, c);
+
+ // skip over any that are escaped.
+ if (escaping) {
+ /* istanbul ignore next - completely not allowed, even escaped. */
+ if (c === '/') {
+ return false
+ }
+
+ if (reSpecials[c]) {
+ re += '\\';
+ }
+ re += c;
+ escaping = false;
+ continue
+ }
+
+ switch (c) {
+ /* istanbul ignore next */
+ case '/': {
+ // Should already be path-split by now.
+ return false
+ }
+
+ case '\\':
+ if (inClass && pattern.charAt(i + 1) === '-') {
+ re += c;
+ continue
+ }
+
+ clearStateChar();
+ escaping = true;
+ continue
+
+ // the various stateChar values
+ // for the "extglob" stuff.
+ case '?':
+ case '*':
+ case '+':
+ case '@':
+ case '!':
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
+
+ // all of those are literals inside a class, except that
+ // the glob [!a] means [^a] in regexp
+ if (inClass) {
+ this.debug(' in class');
+ if (c === '!' && i === classStart + 1) c = '^';
+ re += c;
+ continue
+ }
+
+ // if we already have a stateChar, then it means
+ // that there was something like ** or +? in there.
+ // Handle the stateChar, then proceed with this one.
+ this.debug('call clearStateChar %j', stateChar);
+ clearStateChar();
+ stateChar = c;
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
+ // just clear the statechar *now*, rather than even diving into
+ // the patternList stuff.
+ if (options.noext) clearStateChar();
+ continue
+
+ case '(': {
+ if (inClass) {
+ re += '(';
+ continue
+ }
+
+ if (!stateChar) {
+ re += '\\(';
+ continue
+ }
+
+ const plEntry = {
+ type: stateChar,
+ start: i - 1,
+ reStart: re.length,
+ open: plTypes[stateChar].open,
+ close: plTypes[stateChar].close,
+ };
+ this.debug(this.pattern, '\t', plEntry);
+ patternListStack.push(plEntry);
+ // negation is (?:(?!(?:js)(?:))[^/]*)
+ re += plEntry.open;
+ // next entry starts with a dot maybe?
+ if (plEntry.start === 0 && plEntry.type !== '!') {
+ dotTravAllowed = true;
+ re += subPatternStart(pattern.slice(i + 1));
+ }
+ this.debug('plType %j %j', stateChar, re);
+ stateChar = false;
+ continue
+ }
+
+ case ')': {
+ const plEntry = patternListStack[patternListStack.length - 1];
+ if (inClass || !plEntry) {
+ re += '\\)';
+ continue
+ }
+ patternListStack.pop();
+
+ // closing an extglob
+ clearStateChar();
+ hasMagic = true;
+ pl = plEntry;
+ // negation is (?:(?!js)[^/]*)
+ // The others are (?:)
+ re += pl.close;
+ if (pl.type === '!') {
+ negativeLists.push(Object.assign(pl, { reEnd: re.length }));
+ }
+ continue
+ }
+
+ case '|': {
+ const plEntry = patternListStack[patternListStack.length - 1];
+ if (inClass || !plEntry) {
+ re += '\\|';
+ continue
+ }
+
+ clearStateChar();
+ re += '|';
+ // next subpattern can start with a dot?
+ if (plEntry.start === 0 && plEntry.type !== '!') {
+ dotTravAllowed = true;
+ re += subPatternStart(pattern.slice(i + 1));
+ }
+ continue
+ }
+
+ // these are mostly the same in regexp and glob
+ case '[':
+ // swallow any state-tracking char before the [
+ clearStateChar();
+
+ if (inClass) {
+ re += '\\' + c;
+ continue
+ }
+
+ inClass = true;
+ classStart = i;
+ reClassStart = re.length;
+ re += c;
+ continue
+
+ case ']':
+ // a right bracket shall lose its special
+ // meaning and represent itself in
+ // a bracket expression if it occurs
+ // first in the list. -- POSIX.2 2.8.3.2
+ if (i === classStart + 1 || !inClass) {
+ re += '\\' + c;
+ continue
+ }
+
+ // split where the last [ was, make sure we don't have
+ // an invalid re. if so, re-walk the contents of the
+ // would-be class to re-translate any characters that
+ // were passed through as-is
+ // TODO: It would probably be faster to determine this
+ // without a try/catch and a new RegExp, but it's tricky
+ // to do safely. For now, this is safe and works.
+ cs = pattern.substring(classStart + 1, i);
+ try {
+ RegExp('[' + braExpEscape(charUnescape(cs)) + ']');
+ // looks good, finish up the class.
+ re += c;
+ } catch (er) {
+ // out of order ranges in JS are errors, but in glob syntax,
+ // they're just a range that matches nothing.
+ re = re.substring(0, reClassStart) + '(?:$.)'; // match nothing ever
+ }
+ hasMagic = true;
+ inClass = false;
+ continue
+
+ default:
+ // swallow any state char that wasn't consumed
+ clearStateChar();
+
+ if (reSpecials[c] && !(c === '^' && inClass)) {
+ re += '\\';
+ }
+
+ re += c;
+ break
+
+ } // switch
+ } // for
+
+ // handle the case where we left a class open.
+ // "[abc" is valid, equivalent to "\[abc"
+ if (inClass) {
+ // split where the last [ was, and escape it
+ // this is a huge pita. We now have to re-walk
+ // the contents of the would-be class to re-translate
+ // any characters that were passed through as-is
+ cs = pattern.slice(classStart + 1);
+ sp = this.parse(cs, SUBPARSE);
+ re = re.substring(0, reClassStart) + '\\[' + sp[0];
+ hasMagic = hasMagic || sp[1];
+ }
+
+ // handle the case where we had a +( thing at the *end*
+ // of the pattern.
+ // each pattern list stack adds 3 chars, and we need to go through
+ // and escape any | chars that were passed through as-is for the regexp.
+ // Go through and escape them, taking care not to double-escape any
+ // | chars that were already escaped.
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+ let tail;
+ tail = re.slice(pl.reStart + pl.open.length);
+ this.debug('setting tail', re, pl);
+ // maybe some even number of \, then maybe 1 \, followed by a |
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
+ /* istanbul ignore else - should already be done */
+ if (!$2) {
+ // the | isn't already escaped, so escape it.
+ $2 = '\\';
+ }
+
+ // need to escape all those slashes *again*, without escaping the
+ // one that we need for escaping the | character. As it works out,
+ // escaping an even number of slashes can be done by simply repeating
+ // it exactly after itself. That's why this trick works.
+ //
+ // I am sorry that you have to see this.
+ return $1 + $1 + $2 + '|'
+ });
+
+ this.debug('tail=%j\n %s', tail, tail, pl, re);
+ const t = pl.type === '*' ? star
+ : pl.type === '?' ? qmark
+ : '\\' + pl.type;
+
+ hasMagic = true;
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail;
+ }
+
+ // handle trailing things that only matter at the very end.
+ clearStateChar();
+ if (escaping) {
+ // trailing \\
+ re += '\\\\';
+ }
+
+ // only need to apply the nodot start if the re starts with
+ // something that could conceivably capture a dot
+ const addPatternStart = addPatternStartSet[re.charAt(0)];
+
+ // Hack to work around lack of negative lookbehind in JS
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+ // like 'a.xyz.yz' doesn't match. So, the first negative
+ // lookahead, has to look ALL the way ahead, to the end of
+ // the pattern.
+ for (let n = negativeLists.length - 1; n > -1; n--) {
+ const nl = negativeLists[n];
+
+ const nlBefore = re.slice(0, nl.reStart);
+ const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
+ let nlAfter = re.slice(nl.reEnd);
+ const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
+
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
+ // mean that we should *not* include the ) in the bit that is considered
+ // "after" the negated section.
+ const closeParensBefore = nlBefore.split(')').length;
+ const openParensBefore = nlBefore.split('(').length - closeParensBefore;
+ let cleanAfter = nlAfter;
+ for (let i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
+ }
+ nlAfter = cleanAfter;
+
+ const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '';
+
+ re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
+ }
+
+ // if the re is not "" at this point, then we need to make sure
+ // it doesn't match against an empty path part.
+ // Otherwise a/* will match a/, which it should not.
+ if (re !== '' && hasMagic) {
+ re = '(?=.)' + re;
+ }
+
+ if (addPatternStart) {
+ re = patternStart() + re;
+ }
+
+ // parsing just a piece of a larger pattern.
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic]
+ }
+
+ // if it's nocase, and the lcase/uppercase don't match, it's magic
+ if (options.nocase && !hasMagic) {
+ hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
+ }
+
+ // skip the regexp for non-magical patterns
+ // unescape anything in it, though, so that it'll be
+ // an exact match against a file etc.
+ if (!hasMagic) {
+ return globUnescape(pattern)
+ }
+
+ const flags = options.nocase ? 'i' : '';
+ try {
+ return Object.assign(new RegExp('^' + re + '$', flags), {
+ _glob: pattern,
+ _src: re,
+ })
+ } catch (er) /* istanbul ignore next - should be impossible */ {
+ // If it was an invalid regular expression, then it can't match
+ // anything. This trick looks for a character after the end of
+ // the string, which is of course impossible, except in multi-line
+ // mode, but it's not a /m regex.
+ return new RegExp('$.')
+ }
+ }
+
+ makeRe () {
+ if (this.regexp || this.regexp === false) return this.regexp
+
+ // at this point, this.set is a 2d array of partial
+ // pattern strings, or "**".
+ //
+ // It's better to use .match(). This function shouldn't
+ // be used, really, but it's pretty convenient sometimes,
+ // when you just want to work with a regex.
+ const set = this.set;
+
+ if (!set.length) {
+ this.regexp = false;
+ return this.regexp
+ }
+ const options = this.options;
+
+ const twoStar = options.noglobstar ? star
+ : options.dot ? twoStarDot
+ : twoStarNoDot;
+ const flags = options.nocase ? 'i' : '';
+
+ // coalesce globstars and regexpify non-globstar patterns
+ // if it's the only item, then we just do one twoStar
+ // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
+ // if it's the last, append (\/twoStar|) to previous
+ // if it's in the middle, append (\/|\/twoStar\/) to previous
+ // then filter out GLOBSTAR symbols
+ let re = set.map(pattern => {
+ pattern = pattern.map(p =>
+ typeof p === 'string' ? regExpEscape(p)
+ : p === GLOBSTAR ? GLOBSTAR
+ : p._src
+ ).reduce((set, p) => {
+ if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
+ set.push(p);
+ }
+ return set
+ }, []);
+ pattern.forEach((p, i) => {
+ if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {
+ return
+ }
+ if (i === 0) {
+ if (pattern.length > 1) {
+ pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1];
+ } else {
+ pattern[i] = twoStar;
+ }
+ } else if (i === pattern.length - 1) {
+ pattern[i-1] += '(?:\\\/|' + twoStar + ')?';
+ } else {
+ pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1];
+ pattern[i+1] = GLOBSTAR;
+ }
+ });
+ return pattern.filter(p => p !== GLOBSTAR).join('/')
+ }).join('|');
+
+ // must match entire pattern
+ // ending in a * or ** will make it less strict.
+ re = '^(?:' + re + ')$';
+
+ // can match anything, as long as it's not this.
+ if (this.negate) re = '^(?!' + re + ').*$';
+
+ try {
+ this.regexp = new RegExp(re, flags);
+ } catch (ex) /* istanbul ignore next - should be impossible */ {
+ this.regexp = false;
+ }
+ return this.regexp
+ }
+
+ match (f, partial = this.partial) {
+ this.debug('match', f, this.pattern);
+ // short-circuit in the case of busted things.
+ // comments, etc.
+ if (this.comment) return false
+ if (this.empty) return f === ''
+
+ if (f === '/' && partial) return true
+
+ const options = this.options;
+
+ // windows: need to use /, not \
+ if (path$g.sep !== '/') {
+ f = f.split(path$g.sep).join('/');
+ }
+
+ // treat the test path as a set of pathparts.
+ f = f.split(slashSplit);
+ this.debug(this.pattern, 'split', f);
+
+ // just ONE of the pattern sets in this.set needs to match
+ // in order for it to be valid. If negating, then just one
+ // match means that we have failed.
+ // Either way, return on the first hit.
+
+ const set = this.set;
+ this.debug(this.pattern, 'set', set);
+
+ // Find the basename of the path by looking for the last non-empty segment
+ let filename;
+ for (let i = f.length - 1; i >= 0; i--) {
+ filename = f[i];
+ if (filename) break
+ }
+
+ for (let i = 0; i < set.length; i++) {
+ const pattern = set[i];
+ let file = f;
+ if (options.matchBase && pattern.length === 1) {
+ file = [filename];
+ }
+ const hit = this.matchOne(file, pattern, partial);
+ if (hit) {
+ if (options.flipNegate) return true
+ return !this.negate
+ }
+ }
+
+ // didn't get any hits. this is success if it's a negative
+ // pattern, failure otherwise.
+ if (options.flipNegate) return false
+ return this.negate
+ }
+
+ static defaults (def) {
+ return minimatch$1.defaults(def).Minimatch
+ }
+};
+
+minimatch$1.Minimatch = Minimatch$1;
+
+var common$7 = {};
+
+common$7.setopts = setopts;
+common$7.ownProp = ownProp;
+common$7.makeAbs = makeAbs;
+common$7.finish = finish;
+common$7.mark = mark$1;
+common$7.isIgnored = isIgnored;
+common$7.childrenIgnored = childrenIgnored;
+
+function ownProp (obj, field) {
+ return Object.prototype.hasOwnProperty.call(obj, field)
+}
+
+var fs$d = require$$0$e;
+var path$f = require$$0$c;
+var minimatch = minimatch_1;
+var isAbsolute$1 = require$$0$c.isAbsolute;
+var Minimatch = minimatch.Minimatch;
+
+function alphasort (a, b) {
+ return a.localeCompare(b, 'en')
+}
+
+function setupIgnores (self, options) {
+ self.ignore = options.ignore || [];
+
+ if (!Array.isArray(self.ignore))
+ self.ignore = [self.ignore];
+
+ if (self.ignore.length) {
+ self.ignore = self.ignore.map(ignoreMap);
+ }
+}
+
+// ignore patterns are always in dot:true mode.
+function ignoreMap (pattern) {
+ var gmatcher = null;
+ if (pattern.slice(-3) === '/**') {
+ var gpattern = pattern.replace(/(\/\*\*)+$/, '');
+ gmatcher = new Minimatch(gpattern, { dot: true });
+ }
+
+ return {
+ matcher: new Minimatch(pattern, { dot: true }),
+ gmatcher: gmatcher
+ }
+}
+
+function setopts (self, pattern, options) {
+ if (!options)
+ options = {};
+
+ // base-matching: just use globstar for that.
+ if (options.matchBase && -1 === pattern.indexOf("/")) {
+ if (options.noglobstar) {
+ throw new Error("base matching requires globstar")
+ }
+ pattern = "**/" + pattern;
+ }
+
+ self.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
+ options.allowWindowsEscape === false;
+ if (self.windowsPathsNoEscape) {
+ pattern = pattern.replace(/\\/g, '/');
+ }
+
+ self.silent = !!options.silent;
+ self.pattern = pattern;
+ self.strict = options.strict !== false;
+ self.realpath = !!options.realpath;
+ self.realpathCache = options.realpathCache || Object.create(null);
+ self.follow = !!options.follow;
+ self.dot = !!options.dot;
+ self.mark = !!options.mark;
+ self.nodir = !!options.nodir;
+ if (self.nodir)
+ self.mark = true;
+ self.sync = !!options.sync;
+ self.nounique = !!options.nounique;
+ self.nonull = !!options.nonull;
+ self.nosort = !!options.nosort;
+ self.nocase = !!options.nocase;
+ self.stat = !!options.stat;
+ self.noprocess = !!options.noprocess;
+ self.absolute = !!options.absolute;
+ self.fs = options.fs || fs$d;
+
+ self.maxLength = options.maxLength || Infinity;
+ self.cache = options.cache || Object.create(null);
+ self.statCache = options.statCache || Object.create(null);
+ self.symlinks = options.symlinks || Object.create(null);
+
+ setupIgnores(self, options);
+
+ self.changedCwd = false;
+ var cwd = process.cwd();
+ if (!ownProp(options, "cwd"))
+ self.cwd = path$f.resolve(cwd);
+ else {
+ self.cwd = path$f.resolve(options.cwd);
+ self.changedCwd = self.cwd !== cwd;
+ }
+
+ self.root = options.root || path$f.resolve(self.cwd, "/");
+ self.root = path$f.resolve(self.root);
+
+ // TODO: is an absolute `cwd` supposed to be resolved against `root`?
+ // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
+ self.cwdAbs = isAbsolute$1(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
+ self.nomount = !!options.nomount;
+
+ if (process.platform === "win32") {
+ self.root = self.root.replace(/\\/g, "/");
+ self.cwd = self.cwd.replace(/\\/g, "/");
+ self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
+ }
+
+ // disable comments and negation in Minimatch.
+ // Note that they are not supported in Glob itself anyway.
+ options.nonegate = true;
+ options.nocomment = true;
+
+ self.minimatch = new Minimatch(pattern, options);
+ self.options = self.minimatch.options;
+}
+
+function finish (self) {
+ var nou = self.nounique;
+ var all = nou ? [] : Object.create(null);
+
+ for (var i = 0, l = self.matches.length; i < l; i ++) {
+ var matches = self.matches[i];
+ if (!matches || Object.keys(matches).length === 0) {
+ if (self.nonull) {
+ // do like the shell, and spit out the literal glob
+ var literal = self.minimatch.globSet[i];
+ if (nou)
+ all.push(literal);
+ else
+ all[literal] = true;
+ }
+ } else {
+ // had matches
+ var m = Object.keys(matches);
+ if (nou)
+ all.push.apply(all, m);
+ else
+ m.forEach(function (m) {
+ all[m] = true;
+ });
+ }
+ }
+
+ if (!nou)
+ all = Object.keys(all);
+
+ if (!self.nosort)
+ all = all.sort(alphasort);
+
+ // at *some* point we statted all of these
+ if (self.mark) {
+ for (var i = 0; i < all.length; i++) {
+ all[i] = self._mark(all[i]);
+ }
+ if (self.nodir) {
+ all = all.filter(function (e) {
+ var notDir = !(/\/$/.test(e));
+ var c = self.cache[e] || self.cache[makeAbs(self, e)];
+ if (notDir && c)
+ notDir = c !== 'DIR' && !Array.isArray(c);
+ return notDir
+ });
+ }
+ }
+
+ if (self.ignore.length)
+ all = all.filter(function(m) {
+ return !isIgnored(self, m)
+ });
+
+ self.found = all;
+}
+
+function mark$1 (self, p) {
+ var abs = makeAbs(self, p);
+ var c = self.cache[abs];
+ var m = p;
+ if (c) {
+ var isDir = c === 'DIR' || Array.isArray(c);
+ var slash = p.slice(-1) === '/';
+
+ if (isDir && !slash)
+ m += '/';
+ else if (!isDir && slash)
+ m = m.slice(0, -1);
+
+ if (m !== p) {
+ var mabs = makeAbs(self, m);
+ self.statCache[mabs] = self.statCache[abs];
+ self.cache[mabs] = self.cache[abs];
+ }
+ }
+
+ return m
+}
+
+// lotta situps...
+function makeAbs (self, f) {
+ var abs = f;
+ if (f.charAt(0) === '/') {
+ abs = path$f.join(self.root, f);
+ } else if (isAbsolute$1(f) || f === '') {
+ abs = f;
+ } else if (self.changedCwd) {
+ abs = path$f.resolve(self.cwd, f);
+ } else {
+ abs = path$f.resolve(f);
+ }
+
+ if (process.platform === 'win32')
+ abs = abs.replace(/\\/g, '/');
+
+ return abs
+}
+
+
+// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
+// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
+function isIgnored (self, path) {
+ if (!self.ignore.length)
+ return false
+
+ return self.ignore.some(function(item) {
+ return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
+ })
+}
+
+function childrenIgnored (self, path) {
+ if (!self.ignore.length)
+ return false
+
+ return self.ignore.some(function(item) {
+ return !!(item.gmatcher && item.gmatcher.match(path))
+ })
+}
+
+var sync$2;
+var hasRequiredSync;
+
+function requireSync () {
+ if (hasRequiredSync) return sync$2;
+ hasRequiredSync = 1;
+ sync$2 = globSync;
+ globSync.GlobSync = GlobSync;
+
+ var rp = fs_realpath;
+ var minimatch = minimatch_1;
+ minimatch.Minimatch;
+ requireGlob().Glob;
+ var path = require$$0$c;
+ var assert = require$$5$2;
+ var isAbsolute = require$$0$c.isAbsolute;
+ var common = common$7;
+ var setopts = common.setopts;
+ var ownProp = common.ownProp;
+ var childrenIgnored = common.childrenIgnored;
+ var isIgnored = common.isIgnored;
+
+ function globSync (pattern, options) {
+ if (typeof options === 'function' || arguments.length === 3)
+ throw new TypeError('callback provided to sync glob\n'+
+ 'See: https://github.com/isaacs/node-glob/issues/167')
+
+ return new GlobSync(pattern, options).found
+ }
+
+ function GlobSync (pattern, options) {
+ if (!pattern)
+ throw new Error('must provide pattern')
+
+ if (typeof options === 'function' || arguments.length === 3)
+ throw new TypeError('callback provided to sync glob\n'+
+ 'See: https://github.com/isaacs/node-glob/issues/167')
+
+ if (!(this instanceof GlobSync))
+ return new GlobSync(pattern, options)
+
+ setopts(this, pattern, options);
+
+ if (this.noprocess)
+ return this
+
+ var n = this.minimatch.set.length;
+ this.matches = new Array(n);
+ for (var i = 0; i < n; i ++) {
+ this._process(this.minimatch.set[i], i, false);
+ }
+ this._finish();
+ }
+
+ GlobSync.prototype._finish = function () {
+ assert.ok(this instanceof GlobSync);
+ if (this.realpath) {
+ var self = this;
+ this.matches.forEach(function (matchset, index) {
+ var set = self.matches[index] = Object.create(null);
+ for (var p in matchset) {
+ try {
+ p = self._makeAbs(p);
+ var real = rp.realpathSync(p, self.realpathCache);
+ set[real] = true;
+ } catch (er) {
+ if (er.syscall === 'stat')
+ set[self._makeAbs(p)] = true;
+ else
+ throw er
+ }
+ }
+ });
+ }
+ common.finish(this);
+ };
+
+
+ GlobSync.prototype._process = function (pattern, index, inGlobStar) {
+ assert.ok(this instanceof GlobSync);
+
+ // Get the first [n] parts of pattern that are all strings.
+ var n = 0;
+ while (typeof pattern[n] === 'string') {
+ n ++;
+ }
+ // now n is the index of the first one that is *not* a string.
+
+ // See if there's anything else
+ var prefix;
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index);
+ return
+
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null;
+ break
+
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/');
+ break
+ }
+
+ var remain = pattern.slice(n);
+
+ // get the list of entries.
+ var read;
+ if (prefix === null)
+ read = '.';
+ else if (isAbsolute(prefix) ||
+ isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]'
+ }).join('/'))) {
+ if (!prefix || !isAbsolute(prefix))
+ prefix = '/' + prefix;
+ read = prefix;
+ } else
+ read = prefix;
+
+ var abs = this._makeAbs(read);
+
+ //if ignored, skip processing
+ if (childrenIgnored(this, read))
+ return
+
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR;
+ if (isGlobStar)
+ this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
+ else
+ this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
+ };
+
+
+ GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
+ var entries = this._readdir(abs, inGlobStar);
+
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries)
+ return
+
+ // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+ var pn = remain[0];
+ var negate = !!this.minimatch.negate;
+ var rawGlob = pn._glob;
+ var dotOk = this.dot || rawGlob.charAt(0) === '.';
+
+ var matchedEntries = [];
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i];
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m;
+ if (negate && !prefix) {
+ m = !e.match(pn);
+ } else {
+ m = e.match(pn);
+ }
+ if (m)
+ matchedEntries.push(e);
+ }
+ }
+
+ var len = matchedEntries.length;
+ // If there are no matched entries, then nothing matches.
+ if (len === 0)
+ return
+
+ // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
+
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null);
+
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i];
+ if (prefix) {
+ if (prefix.slice(-1) !== '/')
+ e = prefix + '/' + e;
+ else
+ e = prefix + e;
+ }
+
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e);
+ }
+ this._emitMatch(index, e);
+ }
+ // This was the last one, and no stats were needed
+ return
+ }
+
+ // now test all matched entries as stand-ins for that part
+ // of the pattern.
+ remain.shift();
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i];
+ var newPattern;
+ if (prefix)
+ newPattern = [prefix, e];
+ else
+ newPattern = [e];
+ this._process(newPattern.concat(remain), index, inGlobStar);
+ }
+ };
+
+
+ GlobSync.prototype._emitMatch = function (index, e) {
+ if (isIgnored(this, e))
+ return
+
+ var abs = this._makeAbs(e);
+
+ if (this.mark)
+ e = this._mark(e);
+
+ if (this.absolute) {
+ e = abs;
+ }
+
+ if (this.matches[index][e])
+ return
+
+ if (this.nodir) {
+ var c = this.cache[abs];
+ if (c === 'DIR' || Array.isArray(c))
+ return
+ }
+
+ this.matches[index][e] = true;
+
+ if (this.stat)
+ this._stat(e);
+ };
+
+
+ GlobSync.prototype._readdirInGlobStar = function (abs) {
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow)
+ return this._readdir(abs, false)
+
+ var entries;
+ var lstat;
+ try {
+ lstat = this.fs.lstatSync(abs);
+ } catch (er) {
+ if (er.code === 'ENOENT') {
+ // lstat failed, doesn't exist
+ return null
+ }
+ }
+
+ var isSym = lstat && lstat.isSymbolicLink();
+ this.symlinks[abs] = isSym;
+
+ // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+ if (!isSym && lstat && !lstat.isDirectory())
+ this.cache[abs] = 'FILE';
+ else
+ entries = this._readdir(abs, false);
+
+ return entries
+ };
+
+ GlobSync.prototype._readdir = function (abs, inGlobStar) {
+
+ if (inGlobStar && !ownProp(this.symlinks, abs))
+ return this._readdirInGlobStar(abs)
+
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+ if (!c || c === 'FILE')
+ return null
+
+ if (Array.isArray(c))
+ return c
+ }
+
+ try {
+ return this._readdirEntries(abs, this.fs.readdirSync(abs))
+ } catch (er) {
+ this._readdirError(abs, er);
+ return null
+ }
+ };
+
+ GlobSync.prototype._readdirEntries = function (abs, entries) {
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i ++) {
+ var e = entries[i];
+ if (abs === '/')
+ e = abs + e;
+ else
+ e = abs + '/' + e;
+ this.cache[e] = true;
+ }
+ }
+
+ this.cache[abs] = entries;
+
+ // mark and cache dir-ness
+ return entries
+ };
+
+ GlobSync.prototype._readdirError = function (f, er) {
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+ case 'ENOTDIR': // totally normal. means it *does* exist.
+ var abs = this._makeAbs(f);
+ this.cache[abs] = 'FILE';
+ if (abs === this.cwdAbs) {
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd);
+ error.path = this.cwd;
+ error.code = er.code;
+ throw error
+ }
+ break
+
+ case 'ENOENT': // not terribly unusual
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false;
+ break
+
+ default: // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false;
+ if (this.strict)
+ throw er
+ if (!this.silent)
+ console.error('glob error', er);
+ break
+ }
+ };
+
+ GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
+
+ var entries = this._readdir(abs, inGlobStar);
+
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries)
+ return
+
+ // test without the globstar, and with every child both below
+ // and replacing the globstar.
+ var remainWithoutGlobStar = remain.slice(1);
+ var gspref = prefix ? [ prefix ] : [];
+ var noGlobStar = gspref.concat(remainWithoutGlobStar);
+
+ // the noGlobStar pattern exits the inGlobStar state
+ this._process(noGlobStar, index, false);
+
+ var len = entries.length;
+ var isSym = this.symlinks[abs];
+
+ // If it's a symlink, and we're in a globstar, then stop
+ if (isSym && inGlobStar)
+ return
+
+ for (var i = 0; i < len; i++) {
+ var e = entries[i];
+ if (e.charAt(0) === '.' && !this.dot)
+ continue
+
+ // these two cases enter the inGlobStar state
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar);
+ this._process(instead, index, true);
+
+ var below = gspref.concat(entries[i], remain);
+ this._process(below, index, true);
+ }
+ };
+
+ GlobSync.prototype._processSimple = function (prefix, index) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var exists = this._stat(prefix);
+
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null);
+
+ // If it doesn't exist, then just mark the lack of results
+ if (!exists)
+ return
+
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix);
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix);
+ } else {
+ prefix = path.resolve(this.root, prefix);
+ if (trail)
+ prefix += '/';
+ }
+ }
+
+ if (process.platform === 'win32')
+ prefix = prefix.replace(/\\/g, '/');
+
+ // Mark this as a match
+ this._emitMatch(index, prefix);
+ };
+
+ // Returns either 'DIR', 'FILE', or false
+ GlobSync.prototype._stat = function (f) {
+ var abs = this._makeAbs(f);
+ var needDir = f.slice(-1) === '/';
+
+ if (f.length > this.maxLength)
+ return false
+
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+
+ if (Array.isArray(c))
+ c = 'DIR';
+
+ // It exists, but maybe not how we need it
+ if (!needDir || c === 'DIR')
+ return c
+
+ if (needDir && c === 'FILE')
+ return false
+
+ // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
+ var stat = this.statCache[abs];
+ if (!stat) {
+ var lstat;
+ try {
+ lstat = this.fs.lstatSync(abs);
+ } catch (er) {
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+ this.statCache[abs] = false;
+ return false
+ }
+ }
+
+ if (lstat && lstat.isSymbolicLink()) {
+ try {
+ stat = this.fs.statSync(abs);
+ } catch (er) {
+ stat = lstat;
+ }
+ } else {
+ stat = lstat;
+ }
+ }
+
+ this.statCache[abs] = stat;
+
+ var c = true;
+ if (stat)
+ c = stat.isDirectory() ? 'DIR' : 'FILE';
+
+ this.cache[abs] = this.cache[abs] || c;
+
+ if (needDir && c === 'FILE')
+ return false
+
+ return c
+ };
+
+ GlobSync.prototype._mark = function (p) {
+ return common.mark(this, p)
+ };
+
+ GlobSync.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f)
+ };
+ return sync$2;
+}
+
+var wrappy = wrappy_1;
+var reqs = Object.create(null);
+var once = onceExports;
+
+var inflight_1 = wrappy(inflight);
+
+function inflight (key, cb) {
+ if (reqs[key]) {
+ reqs[key].push(cb);
+ return null
+ } else {
+ reqs[key] = [cb];
+ return makeres(key)
+ }
+}
+
+function makeres (key) {
+ return once(function RES () {
+ var cbs = reqs[key];
+ var len = cbs.length;
+ var args = slice(arguments);
+
+ // XXX It's somewhat ambiguous whether a new callback added in this
+ // pass should be queued for later execution if something in the
+ // list of callbacks throws, or if it should just be discarded.
+ // However, it's such an edge case that it hardly matters, and either
+ // choice is likely as surprising as the other.
+ // As it happens, we do go ahead and schedule it for later execution.
+ try {
+ for (var i = 0; i < len; i++) {
+ cbs[i].apply(null, args);
+ }
+ } finally {
+ if (cbs.length > len) {
+ // added more in the interim.
+ // de-zalgo, just in case, but don't call again.
+ cbs.splice(0, len);
+ process.nextTick(function () {
+ RES.apply(null, args);
+ });
+ } else {
+ delete reqs[key];
+ }
+ }
+ })
+}
+
+function slice (args) {
+ var length = args.length;
+ var array = [];
+
+ for (var i = 0; i < length; i++) array[i] = args[i];
+ return array
+}
+
+var glob_1;
+var hasRequiredGlob;
+
+function requireGlob () {
+ if (hasRequiredGlob) return glob_1;
+ hasRequiredGlob = 1;
+ // Approach:
+ //
+ // 1. Get the minimatch set
+ // 2. For each pattern in the set, PROCESS(pattern, false)
+ // 3. Store matches per-set, then uniq them
+ //
+ // PROCESS(pattern, inGlobStar)
+ // Get the first [n] items from pattern that are all strings
+ // Join these together. This is PREFIX.
+ // If there is no more remaining, then stat(PREFIX) and
+ // add to matches if it succeeds. END.
+ //
+ // If inGlobStar and PREFIX is symlink and points to dir
+ // set ENTRIES = []
+ // else readdir(PREFIX) as ENTRIES
+ // If fail, END
+ //
+ // with ENTRIES
+ // If pattern[n] is GLOBSTAR
+ // // handle the case where the globstar match is empty
+ // // by pruning it out, and testing the resulting pattern
+ // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
+ // // handle other cases.
+ // for ENTRY in ENTRIES (not dotfiles)
+ // // attach globstar + tail onto the entry
+ // // Mark that this entry is a globstar match
+ // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
+ //
+ // else // not globstar
+ // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
+ // Test ENTRY against pattern[n]
+ // If fails, continue
+ // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
+ //
+ // Caveat:
+ // Cache all stats and readdirs results to minimize syscall. Since all
+ // we ever care about is existence and directory-ness, we can just keep
+ // `true` for files, and [children,...] for directories, or `false` for
+ // things that don't exist.
+
+ glob_1 = glob;
+
+ var rp = fs_realpath;
+ var minimatch = minimatch_1;
+ minimatch.Minimatch;
+ var inherits = requireInherits();
+ var EE = require$$0$f.EventEmitter;
+ var path = require$$0$c;
+ var assert = require$$5$2;
+ var isAbsolute = require$$0$c.isAbsolute;
+ var globSync = requireSync();
+ var common = common$7;
+ var setopts = common.setopts;
+ var ownProp = common.ownProp;
+ var inflight = inflight_1;
+ var childrenIgnored = common.childrenIgnored;
+ var isIgnored = common.isIgnored;
+
+ var once = onceExports;
+
+ function glob (pattern, options, cb) {
+ if (typeof options === 'function') cb = options, options = {};
+ if (!options) options = {};
+
+ if (options.sync) {
+ if (cb)
+ throw new TypeError('callback provided to sync glob')
+ return globSync(pattern, options)
+ }
+
+ return new Glob(pattern, options, cb)
+ }
+
+ glob.sync = globSync;
+ var GlobSync = glob.GlobSync = globSync.GlobSync;
+
+ // old api surface
+ glob.glob = glob;
+
+ function extend (origin, add) {
+ if (add === null || typeof add !== 'object') {
+ return origin
+ }
+
+ var keys = Object.keys(add);
+ var i = keys.length;
+ while (i--) {
+ origin[keys[i]] = add[keys[i]];
+ }
+ return origin
+ }
+
+ glob.hasMagic = function (pattern, options_) {
+ var options = extend({}, options_);
+ options.noprocess = true;
+
+ var g = new Glob(pattern, options);
+ var set = g.minimatch.set;
+
+ if (!pattern)
+ return false
+
+ if (set.length > 1)
+ return true
+
+ for (var j = 0; j < set[0].length; j++) {
+ if (typeof set[0][j] !== 'string')
+ return true
+ }
+
+ return false
+ };
+
+ glob.Glob = Glob;
+ inherits(Glob, EE);
+ function Glob (pattern, options, cb) {
+ if (typeof options === 'function') {
+ cb = options;
+ options = null;
+ }
+
+ if (options && options.sync) {
+ if (cb)
+ throw new TypeError('callback provided to sync glob')
+ return new GlobSync(pattern, options)
+ }
+
+ if (!(this instanceof Glob))
+ return new Glob(pattern, options, cb)
+
+ setopts(this, pattern, options);
+ this._didRealPath = false;
+
+ // process each pattern in the minimatch set
+ var n = this.minimatch.set.length;
+
+ // The matches are stored as {: true,...} so that
+ // duplicates are automagically pruned.
+ // Later, we do an Object.keys() on these.
+ // Keep them as a list so we can fill in when nonull is set.
+ this.matches = new Array(n);
+
+ if (typeof cb === 'function') {
+ cb = once(cb);
+ this.on('error', cb);
+ this.on('end', function (matches) {
+ cb(null, matches);
+ });
+ }
+
+ var self = this;
+ this._processing = 0;
+
+ this._emitQueue = [];
+ this._processQueue = [];
+ this.paused = false;
+
+ if (this.noprocess)
+ return this
+
+ if (n === 0)
+ return done()
+
+ var sync = true;
+ for (var i = 0; i < n; i ++) {
+ this._process(this.minimatch.set[i], i, false, done);
+ }
+ sync = false;
+
+ function done () {
+ --self._processing;
+ if (self._processing <= 0) {
+ if (sync) {
+ process.nextTick(function () {
+ self._finish();
+ });
+ } else {
+ self._finish();
+ }
+ }
+ }
+ }
+
+ Glob.prototype._finish = function () {
+ assert(this instanceof Glob);
+ if (this.aborted)
+ return
+
+ if (this.realpath && !this._didRealpath)
+ return this._realpath()
+
+ common.finish(this);
+ this.emit('end', this.found);
+ };
+
+ Glob.prototype._realpath = function () {
+ if (this._didRealpath)
+ return
+
+ this._didRealpath = true;
+
+ var n = this.matches.length;
+ if (n === 0)
+ return this._finish()
+
+ var self = this;
+ for (var i = 0; i < this.matches.length; i++)
+ this._realpathSet(i, next);
+
+ function next () {
+ if (--n === 0)
+ self._finish();
+ }
+ };
+
+ Glob.prototype._realpathSet = function (index, cb) {
+ var matchset = this.matches[index];
+ if (!matchset)
+ return cb()
+
+ var found = Object.keys(matchset);
+ var self = this;
+ var n = found.length;
+
+ if (n === 0)
+ return cb()
+
+ var set = this.matches[index] = Object.create(null);
+ found.forEach(function (p, i) {
+ // If there's a problem with the stat, then it means that
+ // one or more of the links in the realpath couldn't be
+ // resolved. just return the abs value in that case.
+ p = self._makeAbs(p);
+ rp.realpath(p, self.realpathCache, function (er, real) {
+ if (!er)
+ set[real] = true;
+ else if (er.syscall === 'stat')
+ set[p] = true;
+ else
+ self.emit('error', er); // srsly wtf right here
+
+ if (--n === 0) {
+ self.matches[index] = set;
+ cb();
+ }
+ });
+ });
+ };
+
+ Glob.prototype._mark = function (p) {
+ return common.mark(this, p)
+ };
+
+ Glob.prototype._makeAbs = function (f) {
+ return common.makeAbs(this, f)
+ };
+
+ Glob.prototype.abort = function () {
+ this.aborted = true;
+ this.emit('abort');
+ };
+
+ Glob.prototype.pause = function () {
+ if (!this.paused) {
+ this.paused = true;
+ this.emit('pause');
+ }
+ };
+
+ Glob.prototype.resume = function () {
+ if (this.paused) {
+ this.emit('resume');
+ this.paused = false;
+ if (this._emitQueue.length) {
+ var eq = this._emitQueue.slice(0);
+ this._emitQueue.length = 0;
+ for (var i = 0; i < eq.length; i ++) {
+ var e = eq[i];
+ this._emitMatch(e[0], e[1]);
+ }
+ }
+ if (this._processQueue.length) {
+ var pq = this._processQueue.slice(0);
+ this._processQueue.length = 0;
+ for (var i = 0; i < pq.length; i ++) {
+ var p = pq[i];
+ this._processing--;
+ this._process(p[0], p[1], p[2], p[3]);
+ }
+ }
+ }
+ };
+
+ Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
+ assert(this instanceof Glob);
+ assert(typeof cb === 'function');
+
+ if (this.aborted)
+ return
+
+ this._processing++;
+ if (this.paused) {
+ this._processQueue.push([pattern, index, inGlobStar, cb]);
+ return
+ }
+
+ //console.error('PROCESS %d', this._processing, pattern)
+
+ // Get the first [n] parts of pattern that are all strings.
+ var n = 0;
+ while (typeof pattern[n] === 'string') {
+ n ++;
+ }
+ // now n is the index of the first one that is *not* a string.
+
+ // see if there's anything else
+ var prefix;
+ switch (n) {
+ // if not, then this is rather simple
+ case pattern.length:
+ this._processSimple(pattern.join('/'), index, cb);
+ return
+
+ case 0:
+ // pattern *starts* with some non-trivial item.
+ // going to readdir(cwd), but not include the prefix in matches.
+ prefix = null;
+ break
+
+ default:
+ // pattern has some string bits in the front.
+ // whatever it starts with, whether that's 'absolute' like /foo/bar,
+ // or 'relative' like '../baz'
+ prefix = pattern.slice(0, n).join('/');
+ break
+ }
+
+ var remain = pattern.slice(n);
+
+ // get the list of entries.
+ var read;
+ if (prefix === null)
+ read = '.';
+ else if (isAbsolute(prefix) ||
+ isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]'
+ }).join('/'))) {
+ if (!prefix || !isAbsolute(prefix))
+ prefix = '/' + prefix;
+ read = prefix;
+ } else
+ read = prefix;
+
+ var abs = this._makeAbs(read);
+
+ //if ignored, skip _processing
+ if (childrenIgnored(this, read))
+ return cb()
+
+ var isGlobStar = remain[0] === minimatch.GLOBSTAR;
+ if (isGlobStar)
+ this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
+ else
+ this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
+ };
+
+ Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this;
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
+ });
+ };
+
+ Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+
+ // if the abs isn't a dir, then nothing can match!
+ if (!entries)
+ return cb()
+
+ // It will only match dot entries if it starts with a dot, or if
+ // dot is set. Stuff like @(.foo|.bar) isn't allowed.
+ var pn = remain[0];
+ var negate = !!this.minimatch.negate;
+ var rawGlob = pn._glob;
+ var dotOk = this.dot || rawGlob.charAt(0) === '.';
+
+ var matchedEntries = [];
+ for (var i = 0; i < entries.length; i++) {
+ var e = entries[i];
+ if (e.charAt(0) !== '.' || dotOk) {
+ var m;
+ if (negate && !prefix) {
+ m = !e.match(pn);
+ } else {
+ m = e.match(pn);
+ }
+ if (m)
+ matchedEntries.push(e);
+ }
+ }
+
+ //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
+
+ var len = matchedEntries.length;
+ // If there are no matched entries, then nothing matches.
+ if (len === 0)
+ return cb()
+
+ // if this is the last remaining pattern bit, then no need for
+ // an additional stat *unless* the user has specified mark or
+ // stat explicitly. We know they exist, since readdir returned
+ // them.
+
+ if (remain.length === 1 && !this.mark && !this.stat) {
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null);
+
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i];
+ if (prefix) {
+ if (prefix !== '/')
+ e = prefix + '/' + e;
+ else
+ e = prefix + e;
+ }
+
+ if (e.charAt(0) === '/' && !this.nomount) {
+ e = path.join(this.root, e);
+ }
+ this._emitMatch(index, e);
+ }
+ // This was the last one, and no stats were needed
+ return cb()
+ }
+
+ // now test all matched entries as stand-ins for that part
+ // of the pattern.
+ remain.shift();
+ for (var i = 0; i < len; i ++) {
+ var e = matchedEntries[i];
+ if (prefix) {
+ if (prefix !== '/')
+ e = prefix + '/' + e;
+ else
+ e = prefix + e;
+ }
+ this._process([e].concat(remain), index, inGlobStar, cb);
+ }
+ cb();
+ };
+
+ Glob.prototype._emitMatch = function (index, e) {
+ if (this.aborted)
+ return
+
+ if (isIgnored(this, e))
+ return
+
+ if (this.paused) {
+ this._emitQueue.push([index, e]);
+ return
+ }
+
+ var abs = isAbsolute(e) ? e : this._makeAbs(e);
+
+ if (this.mark)
+ e = this._mark(e);
+
+ if (this.absolute)
+ e = abs;
+
+ if (this.matches[index][e])
+ return
+
+ if (this.nodir) {
+ var c = this.cache[abs];
+ if (c === 'DIR' || Array.isArray(c))
+ return
+ }
+
+ this.matches[index][e] = true;
+
+ var st = this.statCache[abs];
+ if (st)
+ this.emit('stat', e, st);
+
+ this.emit('match', e);
+ };
+
+ Glob.prototype._readdirInGlobStar = function (abs, cb) {
+ if (this.aborted)
+ return
+
+ // follow all symlinked directories forever
+ // just proceed as if this is a non-globstar situation
+ if (this.follow)
+ return this._readdir(abs, false, cb)
+
+ var lstatkey = 'lstat\0' + abs;
+ var self = this;
+ var lstatcb = inflight(lstatkey, lstatcb_);
+
+ if (lstatcb)
+ self.fs.lstat(abs, lstatcb);
+
+ function lstatcb_ (er, lstat) {
+ if (er && er.code === 'ENOENT')
+ return cb()
+
+ var isSym = lstat && lstat.isSymbolicLink();
+ self.symlinks[abs] = isSym;
+
+ // If it's not a symlink or a dir, then it's definitely a regular file.
+ // don't bother doing a readdir in that case.
+ if (!isSym && lstat && !lstat.isDirectory()) {
+ self.cache[abs] = 'FILE';
+ cb();
+ } else
+ self._readdir(abs, false, cb);
+ }
+ };
+
+ Glob.prototype._readdir = function (abs, inGlobStar, cb) {
+ if (this.aborted)
+ return
+
+ cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
+ if (!cb)
+ return
+
+ //console.error('RD %j %j', +inGlobStar, abs)
+ if (inGlobStar && !ownProp(this.symlinks, abs))
+ return this._readdirInGlobStar(abs, cb)
+
+ if (ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+ if (!c || c === 'FILE')
+ return cb()
+
+ if (Array.isArray(c))
+ return cb(null, c)
+ }
+
+ var self = this;
+ self.fs.readdir(abs, readdirCb(this, abs, cb));
+ };
+
+ function readdirCb (self, abs, cb) {
+ return function (er, entries) {
+ if (er)
+ self._readdirError(abs, er, cb);
+ else
+ self._readdirEntries(abs, entries, cb);
+ }
+ }
+
+ Glob.prototype._readdirEntries = function (abs, entries, cb) {
+ if (this.aborted)
+ return
+
+ // if we haven't asked to stat everything, then just
+ // assume that everything in there exists, so we can avoid
+ // having to stat it a second time.
+ if (!this.mark && !this.stat) {
+ for (var i = 0; i < entries.length; i ++) {
+ var e = entries[i];
+ if (abs === '/')
+ e = abs + e;
+ else
+ e = abs + '/' + e;
+ this.cache[e] = true;
+ }
+ }
+
+ this.cache[abs] = entries;
+ return cb(null, entries)
+ };
+
+ Glob.prototype._readdirError = function (f, er, cb) {
+ if (this.aborted)
+ return
+
+ // handle errors, and cache the information
+ switch (er.code) {
+ case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
+ case 'ENOTDIR': // totally normal. means it *does* exist.
+ var abs = this._makeAbs(f);
+ this.cache[abs] = 'FILE';
+ if (abs === this.cwdAbs) {
+ var error = new Error(er.code + ' invalid cwd ' + this.cwd);
+ error.path = this.cwd;
+ error.code = er.code;
+ this.emit('error', error);
+ this.abort();
+ }
+ break
+
+ case 'ENOENT': // not terribly unusual
+ case 'ELOOP':
+ case 'ENAMETOOLONG':
+ case 'UNKNOWN':
+ this.cache[this._makeAbs(f)] = false;
+ break
+
+ default: // some unusual error. Treat as failure.
+ this.cache[this._makeAbs(f)] = false;
+ if (this.strict) {
+ this.emit('error', er);
+ // If the error is handled, then we abort
+ // if not, we threw out of here
+ this.abort();
+ }
+ if (!this.silent)
+ console.error('glob error', er);
+ break
+ }
+
+ return cb()
+ };
+
+ Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
+ var self = this;
+ this._readdir(abs, inGlobStar, function (er, entries) {
+ self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
+ });
+ };
+
+
+ Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
+ //console.error('pgs2', prefix, remain[0], entries)
+
+ // no entries means not a dir, so it can never have matches
+ // foo.txt/** doesn't match foo.txt
+ if (!entries)
+ return cb()
+
+ // test without the globstar, and with every child both below
+ // and replacing the globstar.
+ var remainWithoutGlobStar = remain.slice(1);
+ var gspref = prefix ? [ prefix ] : [];
+ var noGlobStar = gspref.concat(remainWithoutGlobStar);
+
+ // the noGlobStar pattern exits the inGlobStar state
+ this._process(noGlobStar, index, false, cb);
+
+ var isSym = this.symlinks[abs];
+ var len = entries.length;
+
+ // If it's a symlink, and we're in a globstar, then stop
+ if (isSym && inGlobStar)
+ return cb()
+
+ for (var i = 0; i < len; i++) {
+ var e = entries[i];
+ if (e.charAt(0) === '.' && !this.dot)
+ continue
+
+ // these two cases enter the inGlobStar state
+ var instead = gspref.concat(entries[i], remainWithoutGlobStar);
+ this._process(instead, index, true, cb);
+
+ var below = gspref.concat(entries[i], remain);
+ this._process(below, index, true, cb);
+ }
+
+ cb();
+ };
+
+ Glob.prototype._processSimple = function (prefix, index, cb) {
+ // XXX review this. Shouldn't it be doing the mounting etc
+ // before doing stat? kinda weird?
+ var self = this;
+ this._stat(prefix, function (er, exists) {
+ self._processSimple2(prefix, index, er, exists, cb);
+ });
+ };
+ Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
+
+ //console.error('ps2', prefix, exists)
+
+ if (!this.matches[index])
+ this.matches[index] = Object.create(null);
+
+ // If it doesn't exist, then just mark the lack of results
+ if (!exists)
+ return cb()
+
+ if (prefix && isAbsolute(prefix) && !this.nomount) {
+ var trail = /[\/\\]$/.test(prefix);
+ if (prefix.charAt(0) === '/') {
+ prefix = path.join(this.root, prefix);
+ } else {
+ prefix = path.resolve(this.root, prefix);
+ if (trail)
+ prefix += '/';
+ }
+ }
+
+ if (process.platform === 'win32')
+ prefix = prefix.replace(/\\/g, '/');
+
+ // Mark this as a match
+ this._emitMatch(index, prefix);
+ cb();
+ };
+
+ // Returns either 'DIR', 'FILE', or false
+ Glob.prototype._stat = function (f, cb) {
+ var abs = this._makeAbs(f);
+ var needDir = f.slice(-1) === '/';
+
+ if (f.length > this.maxLength)
+ return cb()
+
+ if (!this.stat && ownProp(this.cache, abs)) {
+ var c = this.cache[abs];
+
+ if (Array.isArray(c))
+ c = 'DIR';
+
+ // It exists, but maybe not how we need it
+ if (!needDir || c === 'DIR')
+ return cb(null, c)
+
+ if (needDir && c === 'FILE')
+ return cb()
+
+ // otherwise we have to stat, because maybe c=true
+ // if we know it exists, but not what it is.
+ }
+ var stat = this.statCache[abs];
+ if (stat !== undefined) {
+ if (stat === false)
+ return cb(null, stat)
+ else {
+ var type = stat.isDirectory() ? 'DIR' : 'FILE';
+ if (needDir && type === 'FILE')
+ return cb()
+ else
+ return cb(null, type, stat)
+ }
+ }
+
+ var self = this;
+ var statcb = inflight('stat\0' + abs, lstatcb_);
+ if (statcb)
+ self.fs.lstat(abs, statcb);
+
+ function lstatcb_ (er, lstat) {
+ if (lstat && lstat.isSymbolicLink()) {
+ // If it's a symlink, then treat it as the target, unless
+ // the target does not exist, then treat it as a file.
+ return self.fs.stat(abs, function (er, stat) {
+ if (er)
+ self._stat2(f, abs, null, lstat, cb);
+ else
+ self._stat2(f, abs, er, stat, cb);
+ })
+ } else {
+ self._stat2(f, abs, er, lstat, cb);
+ }
+ }
+ };
+
+ Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
+ if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
+ this.statCache[abs] = false;
+ return cb()
+ }
+
+ var needDir = f.slice(-1) === '/';
+ this.statCache[abs] = stat;
+
+ if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
+ return cb(null, false, stat)
+
+ var c = true;
+ if (stat)
+ c = stat.isDirectory() ? 'DIR' : 'FILE';
+ this.cache[abs] = this.cache[abs] || c;
+
+ if (needDir && c === 'FILE')
+ return cb()
+
+ return cb(null, c, stat)
+ };
+ return glob_1;
+}
+
+/*
+ * Copyright (c) 2015, Yahoo Inc. All rights reserved.
+ * Copyrights licensed under the New BSD License.
+ * See the accompanying LICENSE file for terms.
+ */
+var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __awaiter$1 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+};
+Object.defineProperty(expressHandlebars, "__esModule", { value: true });
+var Handlebars = lib$1;
+var fs$c = gracefulFs;
+var path$e = require$$0$c;
+var util_1 = require$$1$7;
+var globSync = requireGlob();
+var glob = (0, util_1.promisify)(globSync);
+var readFile = (0, util_1.promisify)(fs$c.readFile);
+// -----------------------------------------------------------------------------
+var defaultConfig = {
+ handlebars: Handlebars,
+ extname: ".handlebars",
+ encoding: "utf8",
+ layoutsDir: undefined,
+ partialsDir: undefined,
+ defaultLayout: "main",
+ helpers: undefined,
+ compilerOptions: undefined,
+ runtimeOptions: undefined,
+};
+var ExpressHandlebars = /** @class */ (function () {
+ function ExpressHandlebars(config) {
+ if (config === void 0) { config = {}; }
+ // Config properties with defaults.
+ Object.assign(this, defaultConfig, config);
+ // save given config to override other settings.
+ this.config = config;
+ // Express view engine integration point.
+ this.engine = this.renderView.bind(this);
+ // Normalize `extname`.
+ if (this.extname.charAt(0) !== ".") {
+ this.extname = "." + this.extname;
+ }
+ // Internal caches of compiled and precompiled templates.
+ this.compiled = {};
+ this.precompiled = {};
+ // Private internal file system cache.
+ this._fsCache = {};
+ }
+ ExpressHandlebars.prototype.getPartials = function (options) {
+ if (options === void 0) { options = {}; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var partialsDirs, dirs, partials, _i, dirs_1, dir, templates, namespace, rename, filePaths, getTemplateNameFn, _a, filePaths_1, filePath, partialName;
+ var _this = this;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ if (typeof this.partialsDir === "undefined") {
+ return [2 /*return*/, {}];
+ }
+ partialsDirs = Array.isArray(this.partialsDir) ? this.partialsDir : [this.partialsDir];
+ return [4 /*yield*/, Promise.all(partialsDirs.map(function (dir) { return __awaiter$1(_this, void 0, void 0, function () {
+ var dirPath, dirTemplates, dirNamespace, dirRename, templates, _a;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ // Support `partialsDir` collection with object entries that contain a
+ // templates promise and a namespace.
+ if (typeof dir === "string") {
+ dirPath = dir;
+ }
+ else if (typeof dir === "object") {
+ dirTemplates = dir.templates;
+ dirNamespace = dir.namespace;
+ dirRename = dir.rename;
+ dirPath = dir.dir;
+ }
+ // We must have some path to templates, or templates themselves.
+ if (!dirPath && !dirTemplates) {
+ throw new Error("A partials dir must be a string or config object");
+ }
+ _a = dirTemplates;
+ if (_a) return [3 /*break*/, 2];
+ return [4 /*yield*/, this.getTemplates(dirPath, options)];
+ case 1:
+ _a = (_b.sent());
+ _b.label = 2;
+ case 2:
+ templates = _a;
+ return [2 /*return*/, {
+ templates: templates,
+ namespace: dirNamespace,
+ rename: dirRename,
+ }];
+ }
+ });
+ }); }))];
+ case 1:
+ dirs = _b.sent();
+ partials = {};
+ for (_i = 0, dirs_1 = dirs; _i < dirs_1.length; _i++) {
+ dir = dirs_1[_i];
+ templates = dir.templates, namespace = dir.namespace, rename = dir.rename;
+ filePaths = Object.keys(templates);
+ getTemplateNameFn = typeof rename === "function"
+ ? rename
+ : this._getTemplateName.bind(this);
+ for (_a = 0, filePaths_1 = filePaths; _a < filePaths_1.length; _a++) {
+ filePath = filePaths_1[_a];
+ partialName = getTemplateNameFn(filePath, namespace);
+ partials[partialName] = templates[filePath];
+ }
+ }
+ return [2 /*return*/, partials];
+ }
+ });
+ });
+ };
+ ExpressHandlebars.prototype.getTemplate = function (filePath, options) {
+ if (options === void 0) { options = {}; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var encoding, cache, template, err_1;
+ var _this = this;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ filePath = path$e.resolve(filePath);
+ encoding = options.encoding || this.encoding;
+ cache = options.precompiled ? this.precompiled : this.compiled;
+ template = options.cache && cache[filePath];
+ if (template) {
+ return [2 /*return*/, template];
+ }
+ _a.label = 1;
+ case 1:
+ _a.trys.push([1, 3, , 4]);
+ cache[filePath] = this._getFile(filePath, { cache: options.cache, encoding: encoding })
+ .then(function (file) {
+ var compileTemplate = (options.precompiled ? _this._precompileTemplate : _this._compileTemplate).bind(_this);
+ return compileTemplate(file, _this.compilerOptions);
+ });
+ return [4 /*yield*/, cache[filePath]];
+ case 2: return [2 /*return*/, _a.sent()];
+ case 3:
+ err_1 = _a.sent();
+ delete cache[filePath];
+ throw err_1;
+ case 4: return [2 /*return*/];
+ }
+ });
+ });
+ };
+ ExpressHandlebars.prototype.getTemplates = function (dirPath, options) {
+ if (options === void 0) { options = {}; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var cache, filePaths, templates, hash, i;
+ var _this = this;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ cache = options.cache;
+ return [4 /*yield*/, this._getDir(dirPath, { cache: cache })];
+ case 1:
+ filePaths = _a.sent();
+ return [4 /*yield*/, Promise.all(filePaths.map(function (filePath) {
+ return _this.getTemplate(path$e.join(dirPath, filePath), options);
+ }))];
+ case 2:
+ templates = _a.sent();
+ hash = {};
+ for (i = 0; i < filePaths.length; i++) {
+ hash[filePaths[i]] = templates[i];
+ }
+ return [2 /*return*/, hash];
+ }
+ });
+ });
+ };
+ ExpressHandlebars.prototype.render = function (filePath, context, options) {
+ if (context === void 0) { context = {}; }
+ if (options === void 0) { options = {}; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var encoding, _a, template, partials, helpers, runtimeOptions, data, html;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ encoding = options.encoding || this.encoding;
+ return [4 /*yield*/, Promise.all([
+ this.getTemplate(filePath, { cache: options.cache, encoding: encoding }),
+ (options.partials || this.getPartials({ cache: options.cache, encoding: encoding })),
+ ])];
+ case 1:
+ _a = _b.sent(), template = _a[0], partials = _a[1];
+ helpers = __assign(__assign({}, this.helpers), options.helpers);
+ runtimeOptions = __assign(__assign({}, this.runtimeOptions), options.runtimeOptions);
+ data = __assign(__assign({}, options.data), { exphbs: __assign(__assign({}, options), { filePath: filePath, helpers: helpers, partials: partials, runtimeOptions: runtimeOptions }) });
+ html = this._renderTemplate(template, context, __assign(__assign({}, runtimeOptions), { data: data, helpers: helpers, partials: partials }));
+ return [2 /*return*/, html];
+ }
+ });
+ });
+ };
+ ExpressHandlebars.prototype.renderView = function (viewPath, options, callback) {
+ if (options === void 0) { options = {}; }
+ if (callback === void 0) { callback = null; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var context, promise, view, views, viewsPath, encoding, helpers, partials, _a, renderOptions, html, layoutPath, err_2;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ if (typeof options === "function") {
+ callback = options;
+ options = {};
+ }
+ context = options;
+ promise = null;
+ if (!callback) {
+ promise = new Promise(function (resolve, reject) {
+ callback = function (err, value) { err !== null ? reject(err) : resolve(value); };
+ });
+ }
+ views = options.settings && options.settings.views;
+ viewsPath = this._resolveViewsPath(views, viewPath);
+ if (viewsPath) {
+ view = this._getTemplateName(path$e.relative(viewsPath, viewPath));
+ this.partialsDir = this.config.partialsDir || path$e.join(viewsPath, "partials/");
+ this.layoutsDir = this.config.layoutsDir || path$e.join(viewsPath, "layouts/");
+ }
+ encoding = options.encoding || this.encoding;
+ helpers = __assign(__assign({}, this.helpers), options.helpers);
+ _a = [{}];
+ return [4 /*yield*/, this.getPartials({ cache: options.cache, encoding: encoding })];
+ case 1:
+ partials = __assign.apply(void 0, [__assign.apply(void 0, _a.concat([_b.sent()])), (options.partials || {})]);
+ renderOptions = {
+ cache: options.cache,
+ encoding: encoding,
+ view: view,
+ layout: "layout" in options ? options.layout : this.defaultLayout,
+ data: options.data,
+ helpers: helpers,
+ partials: partials,
+ runtimeOptions: options.runtimeOptions,
+ };
+ _b.label = 2;
+ case 2:
+ _b.trys.push([2, 6, , 7]);
+ return [4 /*yield*/, this.render(viewPath, context, renderOptions)];
+ case 3:
+ html = _b.sent();
+ layoutPath = this._resolveLayoutPath(renderOptions.layout);
+ if (!layoutPath) return [3 /*break*/, 5];
+ return [4 /*yield*/, this.render(layoutPath, __assign(__assign({}, context), { body: html }), __assign(__assign({}, renderOptions), { layout: undefined }))];
+ case 4:
+ html = _b.sent();
+ _b.label = 5;
+ case 5:
+ callback(null, html);
+ return [3 /*break*/, 7];
+ case 6:
+ err_2 = _b.sent();
+ callback(err_2);
+ return [3 /*break*/, 7];
+ case 7: return [2 /*return*/, promise];
+ }
+ });
+ });
+ };
+ // -- Protected Hooks ----------------------------------------------------------
+ ExpressHandlebars.prototype._compileTemplate = function (template, options) {
+ if (options === void 0) { options = {}; }
+ return this.handlebars.compile(template.trim(), options);
+ };
+ ExpressHandlebars.prototype._precompileTemplate = function (template, options) {
+ if (options === void 0) { options = {}; }
+ return this.handlebars.precompile(template.trim(), options);
+ };
+ ExpressHandlebars.prototype._renderTemplate = function (template, context, options) {
+ if (context === void 0) { context = {}; }
+ if (options === void 0) { options = {}; }
+ return template(context, options).trim();
+ };
+ // -- Private ------------------------------------------------------------------
+ ExpressHandlebars.prototype._getDir = function (dirPath, options) {
+ if (options === void 0) { options = {}; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var cache, dir, pattern, err_3;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ dirPath = path$e.resolve(dirPath);
+ cache = this._fsCache;
+ dir = options.cache && cache[dirPath];
+ if (!dir) return [3 /*break*/, 2];
+ return [4 /*yield*/, dir];
+ case 1: return [2 /*return*/, (_a.sent()).concat()];
+ case 2:
+ pattern = "**/*" + this.extname;
+ _a.label = 3;
+ case 3:
+ _a.trys.push([3, 5, , 6]);
+ dir = cache[dirPath] = glob(pattern, {
+ cwd: dirPath,
+ follow: true,
+ });
+ // @ts-ignore FIXME: not sure how to throw error in glob for test coverage
+ if (options._throwTestError) {
+ throw new Error("test");
+ }
+ return [4 /*yield*/, dir];
+ case 4: return [2 /*return*/, (_a.sent()).concat()];
+ case 5:
+ err_3 = _a.sent();
+ delete cache[dirPath];
+ throw err_3;
+ case 6: return [2 /*return*/];
+ }
+ });
+ });
+ };
+ ExpressHandlebars.prototype._getFile = function (filePath, options) {
+ if (options === void 0) { options = {}; }
+ return __awaiter$1(this, void 0, void 0, function () {
+ var cache, encoding, file, err_4;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ filePath = path$e.resolve(filePath);
+ cache = this._fsCache;
+ encoding = options.encoding || this.encoding;
+ file = options.cache && cache[filePath];
+ if (file) {
+ return [2 /*return*/, file];
+ }
+ _a.label = 1;
+ case 1:
+ _a.trys.push([1, 3, , 4]);
+ cache[filePath] = readFile(filePath, { encoding: encoding || "utf8" });
+ return [4 /*yield*/, cache[filePath]];
+ case 2: return [2 /*return*/, _a.sent()];
+ case 3:
+ err_4 = _a.sent();
+ delete cache[filePath];
+ throw err_4;
+ case 4: return [2 /*return*/];
+ }
+ });
+ });
+ };
+ ExpressHandlebars.prototype._getTemplateName = function (filePath, namespace) {
+ if (namespace === void 0) { namespace = null; }
+ var name = filePath;
+ if (name.endsWith(this.extname)) {
+ name = name.substring(0, name.length - this.extname.length);
+ }
+ if (namespace) {
+ name = namespace + "/" + name;
+ }
+ return name;
+ };
+ ExpressHandlebars.prototype._resolveViewsPath = function (views, file) {
+ if (!Array.isArray(views)) {
+ return views;
+ }
+ var lastDir = path$e.resolve(file);
+ var dir = path$e.dirname(lastDir);
+ var absoluteViews = views.map(function (v) { return path$e.resolve(v); });
+ // find the closest parent
+ while (dir !== lastDir) {
+ var index = absoluteViews.indexOf(dir);
+ if (index >= 0) {
+ return views[index];
+ }
+ lastDir = dir;
+ dir = path$e.dirname(lastDir);
+ }
+ // cannot resolve view
+ return null;
+ };
+ ExpressHandlebars.prototype._resolveLayoutPath = function (layoutPath) {
+ if (!layoutPath) {
+ return null;
+ }
+ if (!path$e.extname(layoutPath)) {
+ layoutPath += this.extname;
+ }
+ return path$e.resolve(this.layoutsDir || "", layoutPath);
+ };
+ return ExpressHandlebars;
+}());
+expressHandlebars.default = ExpressHandlebars;
+
+/*
+ * Copyright (c) 2014, Yahoo Inc. All rights reserved.
+ * Copyrights licensed under the New BSD License.
+ * See the accompanying LICENSE file for terms.
+ */
+Object.defineProperty(dist, "__esModule", { value: true });
+dist.engine = dist.create = dist.ExpressHandlebars = void 0;
+var express_handlebars_1$1 = expressHandlebars;
+dist.ExpressHandlebars = express_handlebars_1$1.default;
+function create(config) {
+ if (config === void 0) { config = {}; }
+ return new express_handlebars_1$1.default(config);
+}
+dist.create = create;
+function engine(config) {
+ if (config === void 0) { config = {}; }
+ return create(config).engine;
+}
+dist.engine = engine;
+
+var __createBinding$3 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault$3 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar$3 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$3(result, mod, k);
+ __setModuleDefault$3(result, mod);
+ return result;
+};
+Object.defineProperty(server, "__esModule", { value: true });
+server.Server = void 0;
+const express_1 = __importStar$3(expressExports$1);
+const path_1$2 = require$$0$c;
+const webhooks_1$1 = require$$0$8;
+const get_log_1$1 = getLog$1;
+const logging_middleware_1$1 = loggingMiddleware;
+const webhook_proxy_1 = webhookProxy;
+const version_1 = version$9;
+const express_handlebars_1 = dist;
+class Server {
+ constructor(options = {}) {
+ this.version = version_1.VERSION;
+ this.expressApp = (0, express_1.default)();
+ this.log = options.log || (0, get_log_1$1.getLog)().child({ name: "server" });
+ this.probotApp = new options.Probot();
+ this.state = {
+ port: options.port,
+ host: options.host,
+ webhookPath: options.webhookPath || "/",
+ webhookProxy: options.webhookProxy,
+ };
+ this.expressApp.use((0, logging_middleware_1$1.getLoggingMiddleware)(this.log, options.loggingOptions));
+ this.expressApp.use("/probot/static/", express_1.default.static((0, path_1$2.join)(__dirname, "..", "..", "static")));
+ this.expressApp.use(this.state.webhookPath, (0, webhooks_1$1.createNodeMiddleware)(this.probotApp.webhooks, {
+ path: "/",
+ }));
+ this.expressApp.engine("handlebars", (0, express_handlebars_1.engine)({
+ defaultLayout: false,
+ }));
+ this.expressApp.set("view engine", "handlebars");
+ this.expressApp.set("views", (0, path_1$2.join)(__dirname, "..", "..", "views"));
+ this.expressApp.get("/ping", (req, res) => res.end("PONG"));
+ }
+ async load(appFn) {
+ await appFn(this.probotApp, {
+ getRouter: (path) => this.router(path),
+ });
+ }
+ async start() {
+ this.log.info(`Running Probot v${this.version} (Node.js: ${process.version})`);
+ const port = this.state.port || 3000;
+ const { host, webhookPath, webhookProxy } = this.state;
+ const printableHost = host !== null && host !== void 0 ? host : "localhost";
+ this.state.httpServer = (await new Promise((resolve, reject) => {
+ const server = this.expressApp.listen(port, ...(host ? [host] : []), () => {
+ if (webhookProxy) {
+ this.state.eventSource = (0, webhook_proxy_1.createWebhookProxy)({
+ logger: this.log,
+ path: webhookPath,
+ port: port,
+ url: webhookProxy,
+ });
+ }
+ this.log.info(`Listening on http://${printableHost}:${port}`);
+ resolve(server);
+ });
+ server.on("error", (error) => {
+ if (error.code === "EADDRINUSE") {
+ error = Object.assign(error, {
+ message: `Port ${port} is already in use. You can define the PORT environment variable to use a different port.`,
+ });
+ }
+ this.log.error(error);
+ reject(error);
+ });
+ }));
+ return this.state.httpServer;
+ }
+ async stop() {
+ if (this.state.eventSource)
+ this.state.eventSource.close();
+ if (!this.state.httpServer)
+ return;
+ const server = this.state.httpServer;
+ return new Promise((resolve) => server.close(resolve));
+ }
+ router(path = "/") {
+ const newRouter = (0, express_1.Router)();
+ this.expressApp.use(path, newRouter);
+ return newRouter;
+ }
+}
+server.Server = Server;
+Server.version = version_1.VERSION;
+
+var run$1 = {};
+
+var pkgConfExports = {};
+var pkgConf$1 = {
+ get exports(){ return pkgConfExports; },
+ set exports(v){ pkgConfExports = v; },
+};
+
+var findUpExports = {};
+var findUp$1 = {
+ get exports(){ return findUpExports; },
+ set exports(v){ findUpExports = v; },
+};
+
+var locatePathExports = {};
+var locatePath$1 = {
+ get exports(){ return locatePathExports; },
+ set exports(v){ locatePathExports = v; },
+};
+
+var pathExistsExports = {};
+var pathExists$1 = {
+ get exports(){ return pathExistsExports; },
+ set exports(v){ pathExistsExports = v; },
+};
+
+const fs$b = require$$0$e;
+
+pathExists$1.exports = fp => new Promise(resolve => {
+ fs$b.access(fp, err => {
+ resolve(!err);
+ });
+});
+
+pathExistsExports.sync = fp => {
+ try {
+ fs$b.accessSync(fp);
+ return true;
+ } catch (err) {
+ return false;
+ }
+};
+
+var pLimitExports = {};
+var pLimit$2 = {
+ get exports(){ return pLimitExports; },
+ set exports(v){ pLimitExports = v; },
+};
+
+var pTryExports = {};
+var pTry$2 = {
+ get exports(){ return pTryExports; },
+ set exports(v){ pTryExports = v; },
+};
+
+const pTry$1 = (fn, ...arguments_) => new Promise(resolve => {
+ resolve(fn(...arguments_));
+});
+
+pTry$2.exports = pTry$1;
+// TODO: remove this in the next major version
+pTryExports.default = pTry$1;
+
+const pTry = pTryExports;
+
+const pLimit$1 = concurrency => {
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
+ return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
+ }
+
+ const queue = [];
+ let activeCount = 0;
+
+ const next = () => {
+ activeCount--;
+
+ if (queue.length > 0) {
+ queue.shift()();
+ }
+ };
+
+ const run = (fn, resolve, ...args) => {
+ activeCount++;
+
+ const result = pTry(fn, ...args);
+
+ resolve(result);
+
+ result.then(next, next);
+ };
+
+ const enqueue = (fn, resolve, ...args) => {
+ if (activeCount < concurrency) {
+ run(fn, resolve, ...args);
+ } else {
+ queue.push(run.bind(null, fn, resolve, ...args));
+ }
+ };
+
+ const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
+ Object.defineProperties(generator, {
+ activeCount: {
+ get: () => activeCount
+ },
+ pendingCount: {
+ get: () => queue.length
+ },
+ clearQueue: {
+ value: () => {
+ queue.length = 0;
+ }
+ }
+ });
+
+ return generator;
+};
+
+pLimit$2.exports = pLimit$1;
+pLimitExports.default = pLimit$1;
+
+const pLimit = pLimitExports;
+
+class EndError extends Error {
+ constructor(value) {
+ super();
+ this.value = value;
+ }
+}
+
+// The input can also be a promise, so we `Promise.resolve()` it
+const testElement = (el, tester) => Promise.resolve(el).then(tester);
+
+// The input can also be a promise, so we `Promise.all()` them both
+const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
+
+var pLocate$1 = (iterable, tester, opts) => {
+ opts = Object.assign({
+ concurrency: Infinity,
+ preserveOrder: true
+ }, opts);
+
+ const limit = pLimit(opts.concurrency);
+
+ // Start all the promises concurrently with optional limit
+ const items = [...iterable].map(el => [el, limit(testElement, el, tester)]);
+
+ // Check the promises either serially or concurrently
+ const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
+
+ return Promise.all(items.map(el => checkLimit(finder, el)))
+ .then(() => {})
+ .catch(err => err instanceof EndError ? err.value : Promise.reject(err));
+};
+
+const path$d = require$$0$c;
+const pathExists = pathExistsExports;
+const pLocate = pLocate$1;
+
+locatePath$1.exports = (iterable, options) => {
+ options = Object.assign({
+ cwd: process.cwd()
+ }, options);
+
+ return pLocate(iterable, el => pathExists(path$d.resolve(options.cwd, el)), options);
+};
+
+locatePathExports.sync = (iterable, options) => {
+ options = Object.assign({
+ cwd: process.cwd()
+ }, options);
+
+ for (const el of iterable) {
+ if (pathExists.sync(path$d.resolve(options.cwd, el))) {
+ return el;
+ }
+ }
+};
+
+const path$c = require$$0$c;
+const locatePath = locatePathExports;
+
+findUp$1.exports = (filename, opts = {}) => {
+ const startDir = path$c.resolve(opts.cwd || '');
+ const {root} = path$c.parse(startDir);
+
+ const filenames = [].concat(filename);
+
+ return new Promise(resolve => {
+ (function find(dir) {
+ locatePath(filenames, {cwd: dir}).then(file => {
+ if (file) {
+ resolve(path$c.join(dir, file));
+ } else if (dir === root) {
+ resolve(null);
+ } else {
+ find(path$c.dirname(dir));
+ }
+ });
+ })(startDir);
+ });
+};
+
+findUpExports.sync = (filename, opts = {}) => {
+ let dir = path$c.resolve(opts.cwd || '');
+ const {root} = path$c.parse(dir);
+
+ const filenames = [].concat(filename);
+
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const file = locatePath.sync(filenames, {cwd: dir});
+
+ if (file) {
+ return path$c.join(dir, file);
+ }
+
+ if (dir === root) {
+ return null;
+ }
+
+ dir = path$c.dirname(dir);
+ }
+};
+
+var loadJsonFileExports = {};
+var loadJsonFile$2 = {
+ get exports(){ return loadJsonFileExports; },
+ set exports(v){ loadJsonFileExports = v; },
+};
+
+var stripBom$1 = x => {
+ if (typeof x !== 'string') {
+ throw new TypeError('Expected a string, got ' + typeof x);
+ }
+
+ // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
+ // conversion translates it to FEFF (UTF-16 BOM)
+ if (x.charCodeAt(0) === 0xFEFF) {
+ return x.slice(1);
+ }
+
+ return x;
+};
+
+var isArrayish$1 = function isArrayish(obj) {
+ if (!obj) {
+ return false;
+ }
+
+ return obj instanceof Array || Array.isArray(obj) ||
+ (obj.length >= 0 && obj.splice instanceof Function);
+};
+
+var util$3 = require$$1$7;
+var isArrayish = isArrayish$1;
+
+var errorEx$1 = function errorEx(name, properties) {
+ if (!name || name.constructor !== String) {
+ properties = name || {};
+ name = Error.name;
+ }
+
+ var errorExError = function ErrorEXError(message) {
+ if (!this) {
+ return new ErrorEXError(message);
+ }
+
+ message = message instanceof Error
+ ? message.message
+ : (message || this.message);
+
+ Error.call(this, message);
+ Error.captureStackTrace(this, errorExError);
+
+ this.name = name;
+
+ Object.defineProperty(this, 'message', {
+ configurable: true,
+ enumerable: false,
+ get: function () {
+ var newMessage = message.split(/\r?\n/g);
+
+ for (var key in properties) {
+ if (!properties.hasOwnProperty(key)) {
+ continue;
+ }
+
+ var modifier = properties[key];
+
+ if ('message' in modifier) {
+ newMessage = modifier.message(this[key], newMessage) || newMessage;
+ if (!isArrayish(newMessage)) {
+ newMessage = [newMessage];
+ }
+ }
+ }
+
+ return newMessage.join('\n');
+ },
+ set: function (v) {
+ message = v;
+ }
+ });
+
+ var overwrittenStack = null;
+
+ var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
+ var stackGetter = stackDescriptor.get;
+ var stackValue = stackDescriptor.value;
+ delete stackDescriptor.value;
+ delete stackDescriptor.writable;
+
+ stackDescriptor.set = function (newstack) {
+ overwrittenStack = newstack;
+ };
+
+ stackDescriptor.get = function () {
+ var stack = (overwrittenStack || ((stackGetter)
+ ? stackGetter.call(this)
+ : stackValue)).split(/\r?\n+/g);
+
+ // starting in Node 7, the stack builder caches the message.
+ // just replace it.
+ if (!overwrittenStack) {
+ stack[0] = this.name + ': ' + this.message;
+ }
+
+ var lineCount = 1;
+ for (var key in properties) {
+ if (!properties.hasOwnProperty(key)) {
+ continue;
+ }
+
+ var modifier = properties[key];
+
+ if ('line' in modifier) {
+ var line = modifier.line(this[key]);
+ if (line) {
+ stack.splice(lineCount++, 0, ' ' + line);
+ }
+ }
+
+ if ('stack' in modifier) {
+ modifier.stack(this[key], stack);
+ }
+ }
+
+ return stack.join('\n');
+ };
+
+ Object.defineProperty(this, 'stack', stackDescriptor);
+ };
+
+ if (Object.setPrototypeOf) {
+ Object.setPrototypeOf(errorExError.prototype, Error.prototype);
+ Object.setPrototypeOf(errorExError, Error);
+ } else {
+ util$3.inherits(errorExError, Error);
+ }
+
+ return errorExError;
+};
+
+errorEx$1.append = function (str, def) {
+ return {
+ message: function (v, message) {
+ v = v || def;
+
+ if (v) {
+ message[0] += ' ' + str.replace('%s', v.toString());
+ }
+
+ return message;
+ }
+ };
+};
+
+errorEx$1.line = function (str, def) {
+ return {
+ line: function (v) {
+ v = v || def;
+
+ if (v) {
+ return str.replace('%s', v.toString());
+ }
+
+ return null;
+ }
+ };
+};
+
+var errorEx_1 = errorEx$1;
+
+var jsonParseBetterErrors = parseJson$2;
+function parseJson$2 (txt, reviver, context) {
+ context = context || 20;
+ try {
+ return JSON.parse(txt, reviver)
+ } catch (e) {
+ if (typeof txt !== 'string') {
+ const isEmptyArray = Array.isArray(txt) && txt.length === 0;
+ const errorMessage = 'Cannot parse ' +
+ (isEmptyArray ? 'an empty array' : String(txt));
+ throw new TypeError(errorMessage)
+ }
+ const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i);
+ const errIdx = syntaxErr
+ ? +syntaxErr[1]
+ : e.message.match(/^Unexpected end of JSON.*/i)
+ ? txt.length - 1
+ : null;
+ if (errIdx != null) {
+ const start = errIdx <= context
+ ? 0
+ : errIdx - context;
+ const end = errIdx + context >= txt.length
+ ? txt.length
+ : errIdx + context;
+ e.message += ` while parsing near '${
+ start === 0 ? '' : '...'
+ }${txt.slice(start, end)}${
+ end === txt.length ? '' : '...'
+ }'`;
+ } else {
+ e.message += ` while parsing '${txt.slice(0, context * 2)}'`;
+ }
+ throw e
+ }
+}
+
+const errorEx = errorEx_1;
+const fallback = jsonParseBetterErrors;
+
+const JSONError = errorEx('JSONError', {
+ fileName: errorEx.append('in %s')
+});
+
+var parseJson$1 = (input, reviver, filename) => {
+ if (typeof reviver === 'string') {
+ filename = reviver;
+ reviver = null;
+ }
+
+ try {
+ try {
+ return JSON.parse(input, reviver);
+ } catch (err) {
+ fallback(input, reviver);
+
+ throw err;
+ }
+ } catch (err) {
+ err.message = err.message.replace(/\n/g, '');
+
+ const jsonErr = new JSONError(err);
+ if (filename) {
+ jsonErr.fileName = filename;
+ }
+
+ throw jsonErr;
+ }
+};
+
+const processFn = (fn, options) => function (...args) {
+ const P = options.promiseModule;
+
+ return new P((resolve, reject) => {
+ if (options.multiArgs) {
+ args.push((...result) => {
+ if (options.errorFirst) {
+ if (result[0]) {
+ reject(result);
+ } else {
+ result.shift();
+ resolve(result);
+ }
+ } else {
+ resolve(result);
+ }
+ });
+ } else if (options.errorFirst) {
+ args.push((error, result) => {
+ if (error) {
+ reject(error);
+ } else {
+ resolve(result);
+ }
+ });
+ } else {
+ args.push(resolve);
+ }
+
+ fn.apply(this, args);
+ });
+};
+
+var pify$1 = (input, options) => {
+ options = Object.assign({
+ exclude: [/.+(Sync|Stream)$/],
+ errorFirst: true,
+ promiseModule: Promise
+ }, options);
+
+ const objType = typeof input;
+ if (!(input !== null && (objType === 'object' || objType === 'function'))) {
+ throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objType}\``);
+ }
+
+ const filter = key => {
+ const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
+ return options.include ? options.include.some(match) : !options.exclude.some(match);
+ };
+
+ let ret;
+ if (objType === 'function') {
+ ret = function (...args) {
+ return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args);
+ };
+ } else {
+ ret = Object.create(Object.getPrototypeOf(input));
+ }
+
+ for (const key in input) { // eslint-disable-line guard-for-in
+ const property = input[key];
+ ret[key] = typeof property === 'function' && filter(key) ? processFn(property, options) : property;
+ }
+
+ return ret;
+};
+
+const path$b = require$$0$c;
+const fs$a = gracefulFs;
+const stripBom = stripBom$1;
+const parseJson = parseJson$1;
+const pify = pify$1;
+
+const parse$3 = (data, filePath, options = {}) => {
+ data = stripBom(data);
+
+ if (typeof options.beforeParse === 'function') {
+ data = options.beforeParse(data);
+ }
+
+ return parseJson(data, options.reviver, path$b.relative(process.cwd(), filePath));
+};
+
+const loadJsonFile$1 = (filePath, options) => pify(fs$a.readFile)(filePath, 'utf8').then(data => parse$3(data, filePath, options));
+
+loadJsonFile$2.exports = loadJsonFile$1;
+// TODO: Remove this for the next major release
+loadJsonFileExports.default = loadJsonFile$1;
+loadJsonFileExports.sync = (filePath, options) => parse$3(fs$a.readFileSync(filePath, 'utf8'), filePath, options);
+
+const path$a = require$$0$c;
+const findUp = findUpExports;
+const loadJsonFile = loadJsonFileExports;
+
+const filepaths = new WeakMap();
+const filepath = conf => filepaths.get(conf);
+const findNextCwd = pkgPath => path$a.resolve(path$a.dirname(pkgPath), '..');
+
+const addFilePath = (object, filePath) => {
+ filepaths.set(object, filePath);
+ return object;
+};
+
+const pkgConf = (namespace, options = {}) => {
+ if (!namespace) {
+ return Promise.reject(new TypeError('Expected a namespace'));
+ }
+
+ return findUp('package.json', options.cwd ? {cwd: options.cwd} : {})
+ .then(filePath => {
+ if (!filePath) {
+ return addFilePath(Object.assign({}, options.defaults), filePath);
+ }
+
+ return loadJsonFile(filePath).then(package_ => {
+ if (options.skipOnFalse && package_[namespace] === false) {
+ const newOptions = Object.assign({}, options, {cwd: findNextCwd(filePath)});
+ return pkgConf(namespace, newOptions);
+ }
+
+ return addFilePath(Object.assign({}, options.defaults, package_[namespace]), filePath);
+ });
+ });
+};
+
+const sync$1 = (namespace, options = {}) => {
+ if (!namespace) {
+ throw new TypeError('Expected a namespace');
+ }
+
+ const filePath = findUp.sync('package.json', options.cwd ? {cwd: options.cwd} : {});
+
+ if (!filePath) {
+ return addFilePath(Object.assign({}, options.defaults), filePath);
+ }
+
+ const package_ = loadJsonFile.sync(filePath);
+
+ if (options.skipOnFalse && package_[namespace] === false) {
+ const newOptions = Object.assign({}, options, {cwd: findNextCwd(filePath)});
+ return sync$1(namespace, newOptions);
+ }
+
+ return addFilePath(Object.assign({}, options.defaults, package_[namespace]), filePath);
+};
+
+pkgConf$1.exports = pkgConf;
+// TODO: Remove this for the next major release
+pkgConfExports.default = pkgConf;
+pkgConfExports.filepath = filepath;
+pkgConfExports.sync = sync$1;
+
+var setup = {};
+
+var mainExports = {};
+var main$3 = {
+ get exports(){ return mainExports; },
+ set exports(v){ mainExports = v; },
+};
+
+var name$1 = "dotenv";
+var version$6 = "16.0.3";
+var description$1 = "Loads environment variables from .env file";
+var main$2 = "lib/main.js";
+var types$1 = "lib/main.d.ts";
+var exports$1 = {
+ ".": {
+ require: "./lib/main.js",
+ types: "./lib/main.d.ts",
+ "default": "./lib/main.js"
+ },
+ "./config": "./config.js",
+ "./config.js": "./config.js",
+ "./lib/env-options": "./lib/env-options.js",
+ "./lib/env-options.js": "./lib/env-options.js",
+ "./lib/cli-options": "./lib/cli-options.js",
+ "./lib/cli-options.js": "./lib/cli-options.js",
+ "./package.json": "./package.json"
+};
+var scripts$1 = {
+ "dts-check": "tsc --project tests/types/tsconfig.json",
+ lint: "standard",
+ "lint-readme": "standard-markdown",
+ pretest: "npm run lint && npm run dts-check",
+ test: "tap tests/*.js --100 -Rspec",
+ prerelease: "npm test",
+ release: "standard-version"
+};
+var repository$1 = {
+ type: "git",
+ url: "git://github.com/motdotla/dotenv.git"
+};
+var keywords$1 = [
+ "dotenv",
+ "env",
+ ".env",
+ "environment",
+ "variables",
+ "config",
+ "settings"
+];
+var readmeFilename = "README.md";
+var license$1 = "BSD-2-Clause";
+var devDependencies$1 = {
+ "@types/node": "^17.0.9",
+ decache: "^4.6.1",
+ dtslint: "^3.7.0",
+ sinon: "^12.0.1",
+ standard: "^16.0.4",
+ "standard-markdown": "^7.1.0",
+ "standard-version": "^9.3.2",
+ tap: "^15.1.6",
+ tar: "^6.1.11",
+ typescript: "^4.5.4"
+};
+var engines = {
+ node: ">=12"
+};
+var require$$3 = {
+ name: name$1,
+ version: version$6,
+ description: description$1,
+ main: main$2,
+ types: types$1,
+ exports: exports$1,
+ scripts: scripts$1,
+ repository: repository$1,
+ keywords: keywords$1,
+ readmeFilename: readmeFilename,
+ license: license$1,
+ devDependencies: devDependencies$1,
+ engines: engines
+};
+
+const fs$9 = require$$0$e;
+const path$9 = require$$0$c;
+const os$6 = require$$0$h;
+const packageJson = require$$3;
+
+const version$5 = packageJson.version;
+
+const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
+
+// Parser src into an Object
+function parse$2 (src) {
+ const obj = {};
+
+ // Convert buffer to string
+ let lines = src.toString();
+
+ // Convert line breaks to same format
+ lines = lines.replace(/\r\n?/mg, '\n');
+
+ let match;
+ while ((match = LINE.exec(lines)) != null) {
+ const key = match[1];
+
+ // Default undefined or null to empty string
+ let value = (match[2] || '');
+
+ // Remove whitespace
+ value = value.trim();
+
+ // Check if double quoted
+ const maybeQuote = value[0];
+
+ // Remove surrounding quotes
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
+
+ // Expand newlines if double quoted
+ if (maybeQuote === '"') {
+ value = value.replace(/\\n/g, '\n');
+ value = value.replace(/\\r/g, '\r');
+ }
+
+ // Add to object
+ obj[key] = value;
+ }
+
+ return obj
+}
+
+function _log (message) {
+ console.log(`[dotenv@${version$5}][DEBUG] ${message}`);
+}
+
+function _resolveHome (envPath) {
+ return envPath[0] === '~' ? path$9.join(os$6.homedir(), envPath.slice(1)) : envPath
+}
+
+// Populates process.env from .env file
+function config (options) {
+ let dotenvPath = path$9.resolve(process.cwd(), '.env');
+ let encoding = 'utf8';
+ const debug = Boolean(options && options.debug);
+ const override = Boolean(options && options.override);
+
+ if (options) {
+ if (options.path != null) {
+ dotenvPath = _resolveHome(options.path);
+ }
+ if (options.encoding != null) {
+ encoding = options.encoding;
+ }
+ }
+
+ try {
+ // Specifying an encoding returns a string instead of a buffer
+ const parsed = DotenvModule.parse(fs$9.readFileSync(dotenvPath, { encoding }));
+
+ Object.keys(parsed).forEach(function (key) {
+ if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
+ process.env[key] = parsed[key];
+ } else {
+ if (override === true) {
+ process.env[key] = parsed[key];
+ }
+
+ if (debug) {
+ if (override === true) {
+ _log(`"${key}" is already defined in \`process.env\` and WAS overwritten`);
+ } else {
+ _log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`);
+ }
+ }
+ }
+ });
+
+ return { parsed }
+ } catch (e) {
+ if (debug) {
+ _log(`Failed to load ${dotenvPath} ${e.message}`);
+ }
+
+ return { error: e }
+ }
+}
+
+const DotenvModule = {
+ config,
+ parse: parse$2
+};
+
+mainExports.config = DotenvModule.config;
+mainExports.parse = DotenvModule.parse;
+main$3.exports = DotenvModule;
+
+const dotenv = mainExports;
+const fs$8 = require$$0$e;
+const path$8 = require$$0$c;
+const { promisify } = require$$1$7;
+
+function escapeNewlines (str) {
+ return str.replace(/\n/g, '\\n')
+}
+
+function format$1 (key, value) {
+ return `${key}=${escapeNewlines(value)}`
+}
+
+var updateDotenv = async function updateDotenv (env) {
+ const filename = path$8.join(process.cwd(), '.env');
+
+ // Merge with existing values
+ try {
+ const existing = dotenv.parse(await promisify(fs$8.readFile)(filename, 'utf-8'));
+ env = Object.assign(existing, env);
+ } catch (err) {
+ if (err.code !== 'ENOENT') {
+ throw err
+ }
+ }
+
+ const contents = Object.keys(env).map(key => format$1(key, env[key])).join('\n');
+ await promisify(fs$8.writeFile)(filename, contents);
+
+ // Update current env with new values
+ Object.assign(process.env, env);
+
+ return env
+};
+
+var manifestCreation = {};
+
+var jsYaml$1 = {};
+
+var loader$1 = {};
+
+var common$6 = {};
+
+function isNothing(subject) {
+ return (typeof subject === 'undefined') || (subject === null);
+}
+
+
+function isObject(subject) {
+ return (typeof subject === 'object') && (subject !== null);
+}
+
+
+function toArray(sequence) {
+ if (Array.isArray(sequence)) return sequence;
+ else if (isNothing(sequence)) return [];
+
+ return [ sequence ];
+}
+
+
+function extend(target, source) {
+ var index, length, key, sourceKeys;
+
+ if (source) {
+ sourceKeys = Object.keys(source);
+
+ for (index = 0, length = sourceKeys.length; index < length; index += 1) {
+ key = sourceKeys[index];
+ target[key] = source[key];
+ }
+ }
+
+ return target;
+}
+
+
+function repeat(string, count) {
+ var result = '', cycle;
+
+ for (cycle = 0; cycle < count; cycle += 1) {
+ result += string;
+ }
+
+ return result;
+}
+
+
+function isNegativeZero(number) {
+ return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
+}
+
+
+common$6.isNothing = isNothing;
+common$6.isObject = isObject;
+common$6.toArray = toArray;
+common$6.repeat = repeat;
+common$6.isNegativeZero = isNegativeZero;
+common$6.extend = extend;
+
+function YAMLException$4(reason, mark) {
+ // Super constructor
+ Error.call(this);
+
+ this.name = 'YAMLException';
+ this.reason = reason;
+ this.mark = mark;
+ this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
+
+ // Include stack trace in error object
+ if (Error.captureStackTrace) {
+ // Chrome and NodeJS
+ Error.captureStackTrace(this, this.constructor);
+ } else {
+ // FF, IE 10+ and Safari 6+. Fallback for others
+ this.stack = (new Error()).stack || '';
+ }
+}
+
+
+// Inherit from Error
+YAMLException$4.prototype = Object.create(Error.prototype);
+YAMLException$4.prototype.constructor = YAMLException$4;
+
+
+YAMLException$4.prototype.toString = function toString(compact) {
+ var result = this.name + ': ';
+
+ result += this.reason || '(unknown reason)';
+
+ if (!compact && this.mark) {
+ result += ' ' + this.mark.toString();
+ }
+
+ return result;
+};
+
+
+var exception = YAMLException$4;
+
+var common$5 = common$6;
+
+
+function Mark$1(name, buffer, position, line, column) {
+ this.name = name;
+ this.buffer = buffer;
+ this.position = position;
+ this.line = line;
+ this.column = column;
+}
+
+
+Mark$1.prototype.getSnippet = function getSnippet(indent, maxLength) {
+ var head, start, tail, end, snippet;
+
+ if (!this.buffer) return null;
+
+ indent = indent || 4;
+ maxLength = maxLength || 75;
+
+ head = '';
+ start = this.position;
+
+ while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
+ start -= 1;
+ if (this.position - start > (maxLength / 2 - 1)) {
+ head = ' ... ';
+ start += 5;
+ break;
+ }
+ }
+
+ tail = '';
+ end = this.position;
+
+ while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
+ end += 1;
+ if (end - this.position > (maxLength / 2 - 1)) {
+ tail = ' ... ';
+ end -= 5;
+ break;
+ }
+ }
+
+ snippet = this.buffer.slice(start, end);
+
+ return common$5.repeat(' ', indent) + head + snippet + tail + '\n' +
+ common$5.repeat(' ', indent + this.position - start + head.length) + '^';
+};
+
+
+Mark$1.prototype.toString = function toString(compact) {
+ var snippet, where = '';
+
+ if (this.name) {
+ where += 'in "' + this.name + '" ';
+ }
+
+ where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
+
+ if (!compact) {
+ snippet = this.getSnippet();
+
+ if (snippet) {
+ where += ':\n' + snippet;
+ }
+ }
+
+ return where;
+};
+
+
+var mark = Mark$1;
+
+var YAMLException$3 = exception;
+
+var TYPE_CONSTRUCTOR_OPTIONS = [
+ 'kind',
+ 'resolve',
+ 'construct',
+ 'instanceOf',
+ 'predicate',
+ 'represent',
+ 'defaultStyle',
+ 'styleAliases'
+];
+
+var YAML_NODE_KINDS = [
+ 'scalar',
+ 'sequence',
+ 'mapping'
+];
+
+function compileStyleAliases(map) {
+ var result = {};
+
+ if (map !== null) {
+ Object.keys(map).forEach(function (style) {
+ map[style].forEach(function (alias) {
+ result[String(alias)] = style;
+ });
+ });
+ }
+
+ return result;
+}
+
+function Type$h(tag, options) {
+ options = options || {};
+
+ Object.keys(options).forEach(function (name) {
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
+ throw new YAMLException$3('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
+ }
+ });
+
+ // TODO: Add tag format check.
+ this.tag = tag;
+ this.kind = options['kind'] || null;
+ this.resolve = options['resolve'] || function () { return true; };
+ this.construct = options['construct'] || function (data) { return data; };
+ this.instanceOf = options['instanceOf'] || null;
+ this.predicate = options['predicate'] || null;
+ this.represent = options['represent'] || null;
+ this.defaultStyle = options['defaultStyle'] || null;
+ this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
+
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
+ throw new YAMLException$3('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
+ }
+}
+
+var type = Type$h;
+
+/*eslint-disable max-len*/
+
+var common$4 = common$6;
+var YAMLException$2 = exception;
+var Type$g = type;
+
+
+function compileList(schema, name, result) {
+ var exclude = [];
+
+ schema.include.forEach(function (includedSchema) {
+ result = compileList(includedSchema, name, result);
+ });
+
+ schema[name].forEach(function (currentType) {
+ result.forEach(function (previousType, previousIndex) {
+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
+ exclude.push(previousIndex);
+ }
+ });
+
+ result.push(currentType);
+ });
+
+ return result.filter(function (type, index) {
+ return exclude.indexOf(index) === -1;
+ });
+}
+
+
+function compileMap(/* lists... */) {
+ var result = {
+ scalar: {},
+ sequence: {},
+ mapping: {},
+ fallback: {}
+ }, index, length;
+
+ function collectType(type) {
+ result[type.kind][type.tag] = result['fallback'][type.tag] = type;
+ }
+
+ for (index = 0, length = arguments.length; index < length; index += 1) {
+ arguments[index].forEach(collectType);
+ }
+ return result;
+}
+
+
+function Schema$5(definition) {
+ this.include = definition.include || [];
+ this.implicit = definition.implicit || [];
+ this.explicit = definition.explicit || [];
+
+ this.implicit.forEach(function (type) {
+ if (type.loadKind && type.loadKind !== 'scalar') {
+ throw new YAMLException$2('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
+ }
+ });
+
+ this.compiledImplicit = compileList(this, 'implicit', []);
+ this.compiledExplicit = compileList(this, 'explicit', []);
+ this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
+}
+
+
+Schema$5.DEFAULT = null;
+
+
+Schema$5.create = function createSchema() {
+ var schemas, types;
+
+ switch (arguments.length) {
+ case 1:
+ schemas = Schema$5.DEFAULT;
+ types = arguments[0];
+ break;
+
+ case 2:
+ schemas = arguments[0];
+ types = arguments[1];
+ break;
+
+ default:
+ throw new YAMLException$2('Wrong number of arguments for Schema.create function');
+ }
+
+ schemas = common$4.toArray(schemas);
+ types = common$4.toArray(types);
+
+ if (!schemas.every(function (schema) { return schema instanceof Schema$5; })) {
+ throw new YAMLException$2('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
+ }
+
+ if (!types.every(function (type) { return type instanceof Type$g; })) {
+ throw new YAMLException$2('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ }
+
+ return new Schema$5({
+ include: schemas,
+ explicit: types
+ });
+};
+
+
+var schema = Schema$5;
+
+var Type$f = type;
+
+var str = new Type$f('tag:yaml.org,2002:str', {
+ kind: 'scalar',
+ construct: function (data) { return data !== null ? data : ''; }
+});
+
+var Type$e = type;
+
+var seq = new Type$e('tag:yaml.org,2002:seq', {
+ kind: 'sequence',
+ construct: function (data) { return data !== null ? data : []; }
+});
+
+var Type$d = type;
+
+var map = new Type$d('tag:yaml.org,2002:map', {
+ kind: 'mapping',
+ construct: function (data) { return data !== null ? data : {}; }
+});
+
+var Schema$4 = schema;
+
+
+var failsafe = new Schema$4({
+ explicit: [
+ str,
+ seq,
+ map
+ ]
+});
+
+var Type$c = type;
+
+function resolveYamlNull(data) {
+ if (data === null) return true;
+
+ var max = data.length;
+
+ return (max === 1 && data === '~') ||
+ (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
+}
+
+function constructYamlNull() {
+ return null;
+}
+
+function isNull(object) {
+ return object === null;
+}
+
+var _null = new Type$c('tag:yaml.org,2002:null', {
+ kind: 'scalar',
+ resolve: resolveYamlNull,
+ construct: constructYamlNull,
+ predicate: isNull,
+ represent: {
+ canonical: function () { return '~'; },
+ lowercase: function () { return 'null'; },
+ uppercase: function () { return 'NULL'; },
+ camelcase: function () { return 'Null'; }
+ },
+ defaultStyle: 'lowercase'
+});
+
+var Type$b = type;
+
+function resolveYamlBoolean(data) {
+ if (data === null) return false;
+
+ var max = data.length;
+
+ return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
+ (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
+}
+
+function constructYamlBoolean(data) {
+ return data === 'true' ||
+ data === 'True' ||
+ data === 'TRUE';
+}
+
+function isBoolean(object) {
+ return Object.prototype.toString.call(object) === '[object Boolean]';
+}
+
+var bool = new Type$b('tag:yaml.org,2002:bool', {
+ kind: 'scalar',
+ resolve: resolveYamlBoolean,
+ construct: constructYamlBoolean,
+ predicate: isBoolean,
+ represent: {
+ lowercase: function (object) { return object ? 'true' : 'false'; },
+ uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
+ camelcase: function (object) { return object ? 'True' : 'False'; }
+ },
+ defaultStyle: 'lowercase'
+});
+
+var common$3 = common$6;
+var Type$a = type;
+
+function isHexCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
+ ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
+ ((0x61/* a */ <= c) && (c <= 0x66/* f */));
+}
+
+function isOctCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
+}
+
+function isDecCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
+}
+
+function resolveYamlInteger(data) {
+ if (data === null) return false;
+
+ var max = data.length,
+ index = 0,
+ hasDigits = false,
+ ch;
+
+ if (!max) return false;
+
+ ch = data[index];
+
+ // sign
+ if (ch === '-' || ch === '+') {
+ ch = data[++index];
+ }
+
+ if (ch === '0') {
+ // 0
+ if (index + 1 === max) return true;
+ ch = data[++index];
+
+ // base 2, base 8, base 16
+
+ if (ch === 'b') {
+ // base 2
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (ch !== '0' && ch !== '1') return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+
+ if (ch === 'x') {
+ // base 16
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isHexCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+ // base 8
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isOctCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+ // base 10 (except 0) or base 60
+
+ // value should not start with `_`;
+ if (ch === '_') return false;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (ch === ':') break;
+ if (!isDecCode(data.charCodeAt(index))) {
+ return false;
+ }
+ hasDigits = true;
+ }
+
+ // Should have digits and should not end with `_`
+ if (!hasDigits || ch === '_') return false;
+
+ // if !base60 - done;
+ if (ch !== ':') return true;
+
+ // base60 almost not used, no needs to optimize
+ return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
+}
+
+function constructYamlInteger(data) {
+ var value = data, sign = 1, ch, base, digits = [];
+
+ if (value.indexOf('_') !== -1) {
+ value = value.replace(/_/g, '');
+ }
+
+ ch = value[0];
+
+ if (ch === '-' || ch === '+') {
+ if (ch === '-') sign = -1;
+ value = value.slice(1);
+ ch = value[0];
+ }
+
+ if (value === '0') return 0;
+
+ if (ch === '0') {
+ if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
+ if (value[1] === 'x') return sign * parseInt(value, 16);
+ return sign * parseInt(value, 8);
+ }
+
+ if (value.indexOf(':') !== -1) {
+ value.split(':').forEach(function (v) {
+ digits.unshift(parseInt(v, 10));
+ });
+
+ value = 0;
+ base = 1;
+
+ digits.forEach(function (d) {
+ value += (d * base);
+ base *= 60;
+ });
+
+ return sign * value;
+
+ }
+
+ return sign * parseInt(value, 10);
+}
+
+function isInteger(object) {
+ return (Object.prototype.toString.call(object)) === '[object Number]' &&
+ (object % 1 === 0 && !common$3.isNegativeZero(object));
+}
+
+var int = new Type$a('tag:yaml.org,2002:int', {
+ kind: 'scalar',
+ resolve: resolveYamlInteger,
+ construct: constructYamlInteger,
+ predicate: isInteger,
+ represent: {
+ binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
+ octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },
+ decimal: function (obj) { return obj.toString(10); },
+ /* eslint-disable max-len */
+ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
+ },
+ defaultStyle: 'decimal',
+ styleAliases: {
+ binary: [ 2, 'bin' ],
+ octal: [ 8, 'oct' ],
+ decimal: [ 10, 'dec' ],
+ hexadecimal: [ 16, 'hex' ]
+ }
+});
+
+var common$2 = common$6;
+var Type$9 = type;
+
+var YAML_FLOAT_PATTERN = new RegExp(
+ // 2.5e4, 2.5 and integers
+ '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
+ // .2e4, .2
+ // special case, seems not from spec
+ '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
+ // 20:59
+ '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
+ // .inf
+ '|[-+]?\\.(?:inf|Inf|INF)' +
+ // .nan
+ '|\\.(?:nan|NaN|NAN))$');
+
+function resolveYamlFloat(data) {
+ if (data === null) return false;
+
+ if (!YAML_FLOAT_PATTERN.test(data) ||
+ // Quick hack to not allow integers end with `_`
+ // Probably should update regexp & check speed
+ data[data.length - 1] === '_') {
+ return false;
+ }
+
+ return true;
+}
+
+function constructYamlFloat(data) {
+ var value, sign, base, digits;
+
+ value = data.replace(/_/g, '').toLowerCase();
+ sign = value[0] === '-' ? -1 : 1;
+ digits = [];
+
+ if ('+-'.indexOf(value[0]) >= 0) {
+ value = value.slice(1);
+ }
+
+ if (value === '.inf') {
+ return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
+
+ } else if (value === '.nan') {
+ return NaN;
+
+ } else if (value.indexOf(':') >= 0) {
+ value.split(':').forEach(function (v) {
+ digits.unshift(parseFloat(v, 10));
+ });
+
+ value = 0.0;
+ base = 1;
+
+ digits.forEach(function (d) {
+ value += d * base;
+ base *= 60;
+ });
+
+ return sign * value;
+
+ }
+ return sign * parseFloat(value, 10);
+}
+
+
+var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
+
+function representYamlFloat(object, style) {
+ var res;
+
+ if (isNaN(object)) {
+ switch (style) {
+ case 'lowercase': return '.nan';
+ case 'uppercase': return '.NAN';
+ case 'camelcase': return '.NaN';
+ }
+ } else if (Number.POSITIVE_INFINITY === object) {
+ switch (style) {
+ case 'lowercase': return '.inf';
+ case 'uppercase': return '.INF';
+ case 'camelcase': return '.Inf';
+ }
+ } else if (Number.NEGATIVE_INFINITY === object) {
+ switch (style) {
+ case 'lowercase': return '-.inf';
+ case 'uppercase': return '-.INF';
+ case 'camelcase': return '-.Inf';
+ }
+ } else if (common$2.isNegativeZero(object)) {
+ return '-0.0';
+ }
+
+ res = object.toString(10);
+
+ // JS stringifier can build scientific format without dots: 5e-100,
+ // while YAML requres dot: 5.e-100. Fix it with simple hack
+
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
+}
+
+function isFloat(object) {
+ return (Object.prototype.toString.call(object) === '[object Number]') &&
+ (object % 1 !== 0 || common$2.isNegativeZero(object));
+}
+
+var float = new Type$9('tag:yaml.org,2002:float', {
+ kind: 'scalar',
+ resolve: resolveYamlFloat,
+ construct: constructYamlFloat,
+ predicate: isFloat,
+ represent: representYamlFloat,
+ defaultStyle: 'lowercase'
+});
+
+var Schema$3 = schema;
+
+
+var json = new Schema$3({
+ include: [
+ failsafe
+ ],
+ implicit: [
+ _null,
+ bool,
+ int,
+ float
+ ]
+});
+
+var Schema$2 = schema;
+
+
+var core$3 = new Schema$2({
+ include: [
+ json
+ ]
+});
+
+var Type$8 = type;
+
+var YAML_DATE_REGEXP = new RegExp(
+ '^([0-9][0-9][0-9][0-9])' + // [1] year
+ '-([0-9][0-9])' + // [2] month
+ '-([0-9][0-9])$'); // [3] day
+
+var YAML_TIMESTAMP_REGEXP = new RegExp(
+ '^([0-9][0-9][0-9][0-9])' + // [1] year
+ '-([0-9][0-9]?)' + // [2] month
+ '-([0-9][0-9]?)' + // [3] day
+ '(?:[Tt]|[ \\t]+)' + // ...
+ '([0-9][0-9]?)' + // [4] hour
+ ':([0-9][0-9])' + // [5] minute
+ ':([0-9][0-9])' + // [6] second
+ '(?:\\.([0-9]*))?' + // [7] fraction
+ '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
+ '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
+
+function resolveYamlTimestamp(data) {
+ if (data === null) return false;
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
+ return false;
+}
+
+function constructYamlTimestamp(data) {
+ var match, year, month, day, hour, minute, second, fraction = 0,
+ delta = null, tz_hour, tz_minute, date;
+
+ match = YAML_DATE_REGEXP.exec(data);
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
+
+ if (match === null) throw new Error('Date resolve error');
+
+ // match: [1] year [2] month [3] day
+
+ year = +(match[1]);
+ month = +(match[2]) - 1; // JS month starts with 0
+ day = +(match[3]);
+
+ if (!match[4]) { // no hour
+ return new Date(Date.UTC(year, month, day));
+ }
+
+ // match: [4] hour [5] minute [6] second [7] fraction
+
+ hour = +(match[4]);
+ minute = +(match[5]);
+ second = +(match[6]);
+
+ if (match[7]) {
+ fraction = match[7].slice(0, 3);
+ while (fraction.length < 3) { // milli-seconds
+ fraction += '0';
+ }
+ fraction = +fraction;
+ }
+
+ // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
+
+ if (match[9]) {
+ tz_hour = +(match[10]);
+ tz_minute = +(match[11] || 0);
+ delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
+ if (match[9] === '-') delta = -delta;
+ }
+
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
+
+ if (delta) date.setTime(date.getTime() - delta);
+
+ return date;
+}
+
+function representYamlTimestamp(object /*, style*/) {
+ return object.toISOString();
+}
+
+var timestamp = new Type$8('tag:yaml.org,2002:timestamp', {
+ kind: 'scalar',
+ resolve: resolveYamlTimestamp,
+ construct: constructYamlTimestamp,
+ instanceOf: Date,
+ represent: representYamlTimestamp
+});
+
+var Type$7 = type;
+
+function resolveYamlMerge(data) {
+ return data === '<<' || data === null;
+}
+
+var merge = new Type$7('tag:yaml.org,2002:merge', {
+ kind: 'scalar',
+ resolve: resolveYamlMerge
+});
+
+/*eslint-disable no-bitwise*/
+
+var NodeBuffer;
+
+try {
+ // A trick for browserified version, to not include `Buffer` shim
+ var _require$1 = commonjsRequire;
+ NodeBuffer = _require$1('buffer').Buffer;
+} catch (__) {}
+
+var Type$6 = type;
+
+
+// [ 64, 65, 66 ] -> [ padding, CR, LF ]
+var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
+
+
+function resolveYamlBinary(data) {
+ if (data === null) return false;
+
+ var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
+
+ // Convert one by one.
+ for (idx = 0; idx < max; idx++) {
+ code = map.indexOf(data.charAt(idx));
+
+ // Skip CR/LF
+ if (code > 64) continue;
+
+ // Fail on illegal characters
+ if (code < 0) return false;
+
+ bitlen += 6;
+ }
+
+ // If there are any bits left, source was corrupted
+ return (bitlen % 8) === 0;
+}
+
+function constructYamlBinary(data) {
+ var idx, tailbits,
+ input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
+ max = input.length,
+ map = BASE64_MAP,
+ bits = 0,
+ result = [];
+
+ // Collect by 6*4 bits (3 bytes)
+
+ for (idx = 0; idx < max; idx++) {
+ if ((idx % 4 === 0) && idx) {
+ result.push((bits >> 16) & 0xFF);
+ result.push((bits >> 8) & 0xFF);
+ result.push(bits & 0xFF);
+ }
+
+ bits = (bits << 6) | map.indexOf(input.charAt(idx));
+ }
+
+ // Dump tail
+
+ tailbits = (max % 4) * 6;
+
+ if (tailbits === 0) {
+ result.push((bits >> 16) & 0xFF);
+ result.push((bits >> 8) & 0xFF);
+ result.push(bits & 0xFF);
+ } else if (tailbits === 18) {
+ result.push((bits >> 10) & 0xFF);
+ result.push((bits >> 2) & 0xFF);
+ } else if (tailbits === 12) {
+ result.push((bits >> 4) & 0xFF);
+ }
+
+ // Wrap into Buffer for NodeJS and leave Array for browser
+ if (NodeBuffer) {
+ // Support node 6.+ Buffer API when available
+ return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
+ }
+
+ return result;
+}
+
+function representYamlBinary(object /*, style*/) {
+ var result = '', bits = 0, idx, tail,
+ max = object.length,
+ map = BASE64_MAP;
+
+ // Convert every three bytes to 4 ASCII characters.
+
+ for (idx = 0; idx < max; idx++) {
+ if ((idx % 3 === 0) && idx) {
+ result += map[(bits >> 18) & 0x3F];
+ result += map[(bits >> 12) & 0x3F];
+ result += map[(bits >> 6) & 0x3F];
+ result += map[bits & 0x3F];
+ }
+
+ bits = (bits << 8) + object[idx];
+ }
+
+ // Dump tail
+
+ tail = max % 3;
+
+ if (tail === 0) {
+ result += map[(bits >> 18) & 0x3F];
+ result += map[(bits >> 12) & 0x3F];
+ result += map[(bits >> 6) & 0x3F];
+ result += map[bits & 0x3F];
+ } else if (tail === 2) {
+ result += map[(bits >> 10) & 0x3F];
+ result += map[(bits >> 4) & 0x3F];
+ result += map[(bits << 2) & 0x3F];
+ result += map[64];
+ } else if (tail === 1) {
+ result += map[(bits >> 2) & 0x3F];
+ result += map[(bits << 4) & 0x3F];
+ result += map[64];
+ result += map[64];
+ }
+
+ return result;
+}
+
+function isBinary(object) {
+ return NodeBuffer && NodeBuffer.isBuffer(object);
+}
+
+var binary = new Type$6('tag:yaml.org,2002:binary', {
+ kind: 'scalar',
+ resolve: resolveYamlBinary,
+ construct: constructYamlBinary,
+ predicate: isBinary,
+ represent: representYamlBinary
+});
+
+var Type$5 = type;
+
+var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
+var _toString$2 = Object.prototype.toString;
+
+function resolveYamlOmap(data) {
+ if (data === null) return true;
+
+ var objectKeys = [], index, length, pair, pairKey, pairHasKey,
+ object = data;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+ pairHasKey = false;
+
+ if (_toString$2.call(pair) !== '[object Object]') return false;
+
+ for (pairKey in pair) {
+ if (_hasOwnProperty$3.call(pair, pairKey)) {
+ if (!pairHasKey) pairHasKey = true;
+ else return false;
+ }
+ }
+
+ if (!pairHasKey) return false;
+
+ if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
+ else return false;
+ }
+
+ return true;
+}
+
+function constructYamlOmap(data) {
+ return data !== null ? data : [];
+}
+
+var omap = new Type$5('tag:yaml.org,2002:omap', {
+ kind: 'sequence',
+ resolve: resolveYamlOmap,
+ construct: constructYamlOmap
+});
+
+var Type$4 = type;
+
+var _toString$1 = Object.prototype.toString;
+
+function resolveYamlPairs(data) {
+ if (data === null) return true;
+
+ var index, length, pair, keys, result,
+ object = data;
+
+ result = new Array(object.length);
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+
+ if (_toString$1.call(pair) !== '[object Object]') return false;
+
+ keys = Object.keys(pair);
+
+ if (keys.length !== 1) return false;
+
+ result[index] = [ keys[0], pair[keys[0]] ];
+ }
+
+ return true;
+}
+
+function constructYamlPairs(data) {
+ if (data === null) return [];
+
+ var index, length, pair, keys, result,
+ object = data;
+
+ result = new Array(object.length);
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+
+ keys = Object.keys(pair);
+
+ result[index] = [ keys[0], pair[keys[0]] ];
+ }
+
+ return result;
+}
+
+var pairs = new Type$4('tag:yaml.org,2002:pairs', {
+ kind: 'sequence',
+ resolve: resolveYamlPairs,
+ construct: constructYamlPairs
+});
+
+var Type$3 = type;
+
+var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
+
+function resolveYamlSet(data) {
+ if (data === null) return true;
+
+ var key, object = data;
+
+ for (key in object) {
+ if (_hasOwnProperty$2.call(object, key)) {
+ if (object[key] !== null) return false;
+ }
+ }
+
+ return true;
+}
+
+function constructYamlSet(data) {
+ return data !== null ? data : {};
+}
+
+var set = new Type$3('tag:yaml.org,2002:set', {
+ kind: 'mapping',
+ resolve: resolveYamlSet,
+ construct: constructYamlSet
+});
+
+var Schema$1 = schema;
+
+
+var default_safe = new Schema$1({
+ include: [
+ core$3
+ ],
+ implicit: [
+ timestamp,
+ merge
+ ],
+ explicit: [
+ binary,
+ omap,
+ pairs,
+ set
+ ]
+});
+
+var Type$2 = type;
+
+function resolveJavascriptUndefined() {
+ return true;
+}
+
+function constructJavascriptUndefined() {
+ /*eslint-disable no-undefined*/
+ return undefined;
+}
+
+function representJavascriptUndefined() {
+ return '';
+}
+
+function isUndefined(object) {
+ return typeof object === 'undefined';
+}
+
+var _undefined = new Type$2('tag:yaml.org,2002:js/undefined', {
+ kind: 'scalar',
+ resolve: resolveJavascriptUndefined,
+ construct: constructJavascriptUndefined,
+ predicate: isUndefined,
+ represent: representJavascriptUndefined
+});
+
+var Type$1 = type;
+
+function resolveJavascriptRegExp(data) {
+ if (data === null) return false;
+ if (data.length === 0) return false;
+
+ var regexp = data,
+ tail = /\/([gim]*)$/.exec(data),
+ modifiers = '';
+
+ // if regexp starts with '/' it can have modifiers and must be properly closed
+ // `/foo/gim` - modifiers tail can be maximum 3 chars
+ if (regexp[0] === '/') {
+ if (tail) modifiers = tail[1];
+
+ if (modifiers.length > 3) return false;
+ // if expression starts with /, is should be properly terminated
+ if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
+ }
+
+ return true;
+}
+
+function constructJavascriptRegExp(data) {
+ var regexp = data,
+ tail = /\/([gim]*)$/.exec(data),
+ modifiers = '';
+
+ // `/foo/gim` - tail can be maximum 4 chars
+ if (regexp[0] === '/') {
+ if (tail) modifiers = tail[1];
+ regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
+ }
+
+ return new RegExp(regexp, modifiers);
+}
+
+function representJavascriptRegExp(object /*, style*/) {
+ var result = '/' + object.source + '/';
+
+ if (object.global) result += 'g';
+ if (object.multiline) result += 'm';
+ if (object.ignoreCase) result += 'i';
+
+ return result;
+}
+
+function isRegExp(object) {
+ return Object.prototype.toString.call(object) === '[object RegExp]';
+}
+
+var regexp = new Type$1('tag:yaml.org,2002:js/regexp', {
+ kind: 'scalar',
+ resolve: resolveJavascriptRegExp,
+ construct: constructJavascriptRegExp,
+ predicate: isRegExp,
+ represent: representJavascriptRegExp
+});
+
+var esprima;
+
+// Browserified version does not have esprima
+//
+// 1. For node.js just require module as deps
+// 2. For browser try to require mudule via external AMD system.
+// If not found - try to fallback to window.esprima. If not
+// found too - then fail to parse.
+//
+try {
+ // workaround to exclude package from browserify list.
+ var _require = commonjsRequire;
+ esprima = _require('esprima');
+} catch (_) {
+ /* eslint-disable no-redeclare */
+ /* global window */
+ if (typeof window !== 'undefined') esprima = window.esprima;
+}
+
+var Type = type;
+
+function resolveJavascriptFunction(data) {
+ if (data === null) return false;
+
+ try {
+ var source = '(' + data + ')',
+ ast = esprima.parse(source, { range: true });
+
+ if (ast.type !== 'Program' ||
+ ast.body.length !== 1 ||
+ ast.body[0].type !== 'ExpressionStatement' ||
+ (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
+ ast.body[0].expression.type !== 'FunctionExpression')) {
+ return false;
+ }
+
+ return true;
+ } catch (err) {
+ return false;
+ }
+}
+
+function constructJavascriptFunction(data) {
+ /*jslint evil:true*/
+
+ var source = '(' + data + ')',
+ ast = esprima.parse(source, { range: true }),
+ params = [],
+ body;
+
+ if (ast.type !== 'Program' ||
+ ast.body.length !== 1 ||
+ ast.body[0].type !== 'ExpressionStatement' ||
+ (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
+ ast.body[0].expression.type !== 'FunctionExpression')) {
+ throw new Error('Failed to resolve function');
+ }
+
+ ast.body[0].expression.params.forEach(function (param) {
+ params.push(param.name);
+ });
+
+ body = ast.body[0].expression.body.range;
+
+ // Esprima's ranges include the first '{' and the last '}' characters on
+ // function expressions. So cut them out.
+ if (ast.body[0].expression.body.type === 'BlockStatement') {
+ /*eslint-disable no-new-func*/
+ return new Function(params, source.slice(body[0] + 1, body[1] - 1));
+ }
+ // ES6 arrow functions can omit the BlockStatement. In that case, just return
+ // the body.
+ /*eslint-disable no-new-func*/
+ return new Function(params, 'return ' + source.slice(body[0], body[1]));
+}
+
+function representJavascriptFunction(object /*, style*/) {
+ return object.toString();
+}
+
+function isFunction(object) {
+ return Object.prototype.toString.call(object) === '[object Function]';
+}
+
+var _function = new Type('tag:yaml.org,2002:js/function', {
+ kind: 'scalar',
+ resolve: resolveJavascriptFunction,
+ construct: constructJavascriptFunction,
+ predicate: isFunction,
+ represent: representJavascriptFunction
+});
+
+var Schema = schema;
+
+
+var default_full = Schema.DEFAULT = new Schema({
+ include: [
+ default_safe
+ ],
+ explicit: [
+ _undefined,
+ regexp,
+ _function
+ ]
+});
+
+/*eslint-disable max-len,no-use-before-define*/
+
+var common$1 = common$6;
+var YAMLException$1 = exception;
+var Mark = mark;
+var DEFAULT_SAFE_SCHEMA$1 = default_safe;
+var DEFAULT_FULL_SCHEMA$1 = default_full;
+
+
+var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
+
+
+var CONTEXT_FLOW_IN = 1;
+var CONTEXT_FLOW_OUT = 2;
+var CONTEXT_BLOCK_IN = 3;
+var CONTEXT_BLOCK_OUT = 4;
+
+
+var CHOMPING_CLIP = 1;
+var CHOMPING_STRIP = 2;
+var CHOMPING_KEEP = 3;
+
+
+var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
+var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
+var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
+var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
+var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
+
+
+function _class(obj) { return Object.prototype.toString.call(obj); }
+
+function is_EOL(c) {
+ return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
+}
+
+function is_WHITE_SPACE(c) {
+ return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
+}
+
+function is_WS_OR_EOL(c) {
+ return (c === 0x09/* Tab */) ||
+ (c === 0x20/* Space */) ||
+ (c === 0x0A/* LF */) ||
+ (c === 0x0D/* CR */);
+}
+
+function is_FLOW_INDICATOR(c) {
+ return c === 0x2C/* , */ ||
+ c === 0x5B/* [ */ ||
+ c === 0x5D/* ] */ ||
+ c === 0x7B/* { */ ||
+ c === 0x7D/* } */;
+}
+
+function fromHexCode(c) {
+ var lc;
+
+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
+ return c - 0x30;
+ }
+
+ /*eslint-disable no-bitwise*/
+ lc = c | 0x20;
+
+ if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
+ return lc - 0x61 + 10;
+ }
+
+ return -1;
+}
+
+function escapedHexLen(c) {
+ if (c === 0x78/* x */) { return 2; }
+ if (c === 0x75/* u */) { return 4; }
+ if (c === 0x55/* U */) { return 8; }
+ return 0;
+}
+
+function fromDecimalCode(c) {
+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
+ return c - 0x30;
+ }
+
+ return -1;
+}
+
+function simpleEscapeSequence(c) {
+ /* eslint-disable indent */
+ return (c === 0x30/* 0 */) ? '\x00' :
+ (c === 0x61/* a */) ? '\x07' :
+ (c === 0x62/* b */) ? '\x08' :
+ (c === 0x74/* t */) ? '\x09' :
+ (c === 0x09/* Tab */) ? '\x09' :
+ (c === 0x6E/* n */) ? '\x0A' :
+ (c === 0x76/* v */) ? '\x0B' :
+ (c === 0x66/* f */) ? '\x0C' :
+ (c === 0x72/* r */) ? '\x0D' :
+ (c === 0x65/* e */) ? '\x1B' :
+ (c === 0x20/* Space */) ? ' ' :
+ (c === 0x22/* " */) ? '\x22' :
+ (c === 0x2F/* / */) ? '/' :
+ (c === 0x5C/* \ */) ? '\x5C' :
+ (c === 0x4E/* N */) ? '\x85' :
+ (c === 0x5F/* _ */) ? '\xA0' :
+ (c === 0x4C/* L */) ? '\u2028' :
+ (c === 0x50/* P */) ? '\u2029' : '';
+}
+
+function charFromCodepoint(c) {
+ if (c <= 0xFFFF) {
+ return String.fromCharCode(c);
+ }
+ // Encode UTF-16 surrogate pair
+ // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
+ return String.fromCharCode(
+ ((c - 0x010000) >> 10) + 0xD800,
+ ((c - 0x010000) & 0x03FF) + 0xDC00
+ );
+}
+
+var simpleEscapeCheck = new Array(256); // integer, for fast access
+var simpleEscapeMap = new Array(256);
+for (var i$2 = 0; i$2 < 256; i$2++) {
+ simpleEscapeCheck[i$2] = simpleEscapeSequence(i$2) ? 1 : 0;
+ simpleEscapeMap[i$2] = simpleEscapeSequence(i$2);
+}
+
+
+function State$1(input, options) {
+ this.input = input;
+
+ this.filename = options['filename'] || null;
+ this.schema = options['schema'] || DEFAULT_FULL_SCHEMA$1;
+ this.onWarning = options['onWarning'] || null;
+ this.legacy = options['legacy'] || false;
+ this.json = options['json'] || false;
+ this.listener = options['listener'] || null;
+
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.typeMap = this.schema.compiledTypeMap;
+
+ this.length = input.length;
+ this.position = 0;
+ this.line = 0;
+ this.lineStart = 0;
+ this.lineIndent = 0;
+
+ this.documents = [];
+
+ /*
+ this.version;
+ this.checkLineBreaks;
+ this.tagMap;
+ this.anchorMap;
+ this.tag;
+ this.anchor;
+ this.kind;
+ this.result;*/
+
+}
+
+
+function generateError(state, message) {
+ return new YAMLException$1(
+ message,
+ new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
+}
+
+function throwError(state, message) {
+ throw generateError(state, message);
+}
+
+function throwWarning(state, message) {
+ if (state.onWarning) {
+ state.onWarning.call(null, generateError(state, message));
+ }
+}
+
+
+var directiveHandlers = {
+
+ YAML: function handleYamlDirective(state, name, args) {
+
+ var match, major, minor;
+
+ if (state.version !== null) {
+ throwError(state, 'duplication of %YAML directive');
+ }
+
+ if (args.length !== 1) {
+ throwError(state, 'YAML directive accepts exactly one argument');
+ }
+
+ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
+
+ if (match === null) {
+ throwError(state, 'ill-formed argument of the YAML directive');
+ }
+
+ major = parseInt(match[1], 10);
+ minor = parseInt(match[2], 10);
+
+ if (major !== 1) {
+ throwError(state, 'unacceptable YAML version of the document');
+ }
+
+ state.version = args[0];
+ state.checkLineBreaks = (minor < 2);
+
+ if (minor !== 1 && minor !== 2) {
+ throwWarning(state, 'unsupported YAML version of the document');
+ }
+ },
+
+ TAG: function handleTagDirective(state, name, args) {
+
+ var handle, prefix;
+
+ if (args.length !== 2) {
+ throwError(state, 'TAG directive accepts exactly two arguments');
+ }
+
+ handle = args[0];
+ prefix = args[1];
+
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
+ throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
+ }
+
+ if (_hasOwnProperty$1.call(state.tagMap, handle)) {
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
+ }
+
+ if (!PATTERN_TAG_URI.test(prefix)) {
+ throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
+ }
+
+ state.tagMap[handle] = prefix;
+ }
+};
+
+
+function captureSegment(state, start, end, checkJson) {
+ var _position, _length, _character, _result;
+
+ if (start < end) {
+ _result = state.input.slice(start, end);
+
+ if (checkJson) {
+ for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
+ _character = _result.charCodeAt(_position);
+ if (!(_character === 0x09 ||
+ (0x20 <= _character && _character <= 0x10FFFF))) {
+ throwError(state, 'expected valid JSON character');
+ }
+ }
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
+ throwError(state, 'the stream contains non-printable characters');
+ }
+
+ state.result += _result;
+ }
+}
+
+function mergeMappings(state, destination, source, overridableKeys) {
+ var sourceKeys, key, index, quantity;
+
+ if (!common$1.isObject(source)) {
+ throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
+ }
+
+ sourceKeys = Object.keys(source);
+
+ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
+ key = sourceKeys[index];
+
+ if (!_hasOwnProperty$1.call(destination, key)) {
+ destination[key] = source[key];
+ overridableKeys[key] = true;
+ }
+ }
+}
+
+function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
+ var index, quantity;
+
+ // The output is a plain object here, so keys can only be strings.
+ // We need to convert keyNode to a string, but doing so can hang the process
+ // (deeply nested arrays that explode exponentially using aliases).
+ if (Array.isArray(keyNode)) {
+ keyNode = Array.prototype.slice.call(keyNode);
+
+ for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
+ if (Array.isArray(keyNode[index])) {
+ throwError(state, 'nested arrays are not supported inside keys');
+ }
+
+ if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
+ keyNode[index] = '[object Object]';
+ }
+ }
+ }
+
+ // Avoid code execution in load() via toString property
+ // (still use its own toString for arrays, timestamps,
+ // and whatever user schema extensions happen to have @@toStringTag)
+ if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
+ keyNode = '[object Object]';
+ }
+
+
+ keyNode = String(keyNode);
+
+ if (_result === null) {
+ _result = {};
+ }
+
+ if (keyTag === 'tag:yaml.org,2002:merge') {
+ if (Array.isArray(valueNode)) {
+ for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
+ }
+ } else {
+ mergeMappings(state, _result, valueNode, overridableKeys);
+ }
+ } else {
+ if (!state.json &&
+ !_hasOwnProperty$1.call(overridableKeys, keyNode) &&
+ _hasOwnProperty$1.call(_result, keyNode)) {
+ state.line = startLine || state.line;
+ state.position = startPos || state.position;
+ throwError(state, 'duplicated mapping key');
+ }
+ _result[keyNode] = valueNode;
+ delete overridableKeys[keyNode];
+ }
+
+ return _result;
+}
+
+function readLineBreak(state) {
+ var ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x0A/* LF */) {
+ state.position++;
+ } else if (ch === 0x0D/* CR */) {
+ state.position++;
+ if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
+ state.position++;
+ }
+ } else {
+ throwError(state, 'a line break is expected');
+ }
+
+ state.line += 1;
+ state.lineStart = state.position;
+}
+
+function skipSeparationSpace(state, allowComments, checkIndent) {
+ var lineBreaks = 0,
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (allowComments && ch === 0x23/* # */) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
+ }
+
+ if (is_EOL(ch)) {
+ readLineBreak(state);
+
+ ch = state.input.charCodeAt(state.position);
+ lineBreaks++;
+ state.lineIndent = 0;
+
+ while (ch === 0x20/* Space */) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
+ throwWarning(state, 'deficient indentation');
+ }
+
+ return lineBreaks;
+}
+
+function testDocumentSeparator(state) {
+ var _position = state.position,
+ ch;
+
+ ch = state.input.charCodeAt(_position);
+
+ // Condition state.position === state.lineStart is tested
+ // in parent on each call, for efficiency. No needs to test here again.
+ if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
+ ch === state.input.charCodeAt(_position + 1) &&
+ ch === state.input.charCodeAt(_position + 2)) {
+
+ _position += 3;
+
+ ch = state.input.charCodeAt(_position);
+
+ if (ch === 0 || is_WS_OR_EOL(ch)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function writeFoldedLines(state, count) {
+ if (count === 1) {
+ state.result += ' ';
+ } else if (count > 1) {
+ state.result += common$1.repeat('\n', count - 1);
+ }
+}
+
+
+function readPlainScalar(state, nodeIndent, withinFlowCollection) {
+ var preceding,
+ following,
+ captureStart,
+ captureEnd,
+ hasPendingContent,
+ _line,
+ _lineStart,
+ _lineIndent,
+ _kind = state.kind,
+ _result = state.result,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (is_WS_OR_EOL(ch) ||
+ is_FLOW_INDICATOR(ch) ||
+ ch === 0x23/* # */ ||
+ ch === 0x26/* & */ ||
+ ch === 0x2A/* * */ ||
+ ch === 0x21/* ! */ ||
+ ch === 0x7C/* | */ ||
+ ch === 0x3E/* > */ ||
+ ch === 0x27/* ' */ ||
+ ch === 0x22/* " */ ||
+ ch === 0x25/* % */ ||
+ ch === 0x40/* @ */ ||
+ ch === 0x60/* ` */) {
+ return false;
+ }
+
+ if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following) ||
+ withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ return false;
+ }
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+
+ while (ch !== 0) {
+ if (ch === 0x3A/* : */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following) ||
+ withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ break;
+ }
+
+ } else if (ch === 0x23/* # */) {
+ preceding = state.input.charCodeAt(state.position - 1);
+
+ if (is_WS_OR_EOL(preceding)) {
+ break;
+ }
+
+ } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
+ withinFlowCollection && is_FLOW_INDICATOR(ch)) {
+ break;
+
+ } else if (is_EOL(ch)) {
+ _line = state.line;
+ _lineStart = state.lineStart;
+ _lineIndent = state.lineIndent;
+ skipSeparationSpace(state, false, -1);
+
+ if (state.lineIndent >= nodeIndent) {
+ hasPendingContent = true;
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ } else {
+ state.position = captureEnd;
+ state.line = _line;
+ state.lineStart = _lineStart;
+ state.lineIndent = _lineIndent;
+ break;
+ }
+ }
+
+ if (hasPendingContent) {
+ captureSegment(state, captureStart, captureEnd, false);
+ writeFoldedLines(state, state.line - _line);
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+ }
+
+ if (!is_WHITE_SPACE(ch)) {
+ captureEnd = state.position + 1;
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ captureSegment(state, captureStart, captureEnd, false);
+
+ if (state.result) {
+ return true;
+ }
+
+ state.kind = _kind;
+ state.result = _result;
+ return false;
+}
+
+function readSingleQuotedScalar(state, nodeIndent) {
+ var ch,
+ captureStart, captureEnd;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x27/* ' */) {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ state.position++;
+ captureStart = captureEnd = state.position;
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 0x27/* ' */) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x27/* ' */) {
+ captureStart = state.position;
+ state.position++;
+ captureEnd = state.position;
+ } else {
+ return true;
+ }
+
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, 'unexpected end of the document within a single quoted scalar');
+
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a single quoted scalar');
+}
+
+function readDoubleQuotedScalar(state, nodeIndent) {
+ var captureStart,
+ captureEnd,
+ hexLength,
+ hexResult,
+ tmp,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x22/* " */) {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ state.position++;
+ captureStart = captureEnd = state.position;
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 0x22/* " */) {
+ captureSegment(state, captureStart, state.position, true);
+ state.position++;
+ return true;
+
+ } else if (ch === 0x5C/* \ */) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+
+ if (is_EOL(ch)) {
+ skipSeparationSpace(state, false, nodeIndent);
+
+ // TODO: rework to inline fn with no type cast?
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
+ state.result += simpleEscapeMap[ch];
+ state.position++;
+
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
+ hexLength = tmp;
+ hexResult = 0;
+
+ for (; hexLength > 0; hexLength--) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if ((tmp = fromHexCode(ch)) >= 0) {
+ hexResult = (hexResult << 4) + tmp;
+
+ } else {
+ throwError(state, 'expected hexadecimal character');
+ }
+ }
+
+ state.result += charFromCodepoint(hexResult);
+
+ state.position++;
+
+ } else {
+ throwError(state, 'unknown escape sequence');
+ }
+
+ captureStart = captureEnd = state.position;
+
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, 'unexpected end of the document within a double quoted scalar');
+
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a double quoted scalar');
+}
+
+function readFlowCollection(state, nodeIndent) {
+ var readNext = true,
+ _line,
+ _tag = state.tag,
+ _result,
+ _anchor = state.anchor,
+ following,
+ terminator,
+ isPair,
+ isExplicitPair,
+ isMapping,
+ overridableKeys = {},
+ keyNode,
+ keyTag,
+ valueNode,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x5B/* [ */) {
+ terminator = 0x5D;/* ] */
+ isMapping = false;
+ _result = [];
+ } else if (ch === 0x7B/* { */) {
+ terminator = 0x7D;/* } */
+ isMapping = true;
+ _result = {};
+ } else {
+ return false;
+ }
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+
+ while (ch !== 0) {
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === terminator) {
+ state.position++;
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = isMapping ? 'mapping' : 'sequence';
+ state.result = _result;
+ return true;
+ } else if (!readNext) {
+ throwError(state, 'missed comma between flow collection entries');
+ }
+
+ keyTag = keyNode = valueNode = null;
+ isPair = isExplicitPair = false;
+
+ if (ch === 0x3F/* ? */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following)) {
+ isPair = isExplicitPair = true;
+ state.position++;
+ skipSeparationSpace(state, true, nodeIndent);
+ }
+ }
+
+ _line = state.line;
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ keyTag = state.tag;
+ keyNode = state.result;
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
+ isPair = true;
+ ch = state.input.charCodeAt(++state.position);
+ skipSeparationSpace(state, true, nodeIndent);
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ valueNode = state.result;
+ }
+
+ if (isMapping) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
+ } else if (isPair) {
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
+ } else {
+ _result.push(keyNode);
+ }
+
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x2C/* , */) {
+ readNext = true;
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ readNext = false;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a flow collection');
+}
+
+function readBlockScalar(state, nodeIndent) {
+ var captureStart,
+ folding,
+ chomping = CHOMPING_CLIP,
+ didReadContent = false,
+ detectedIndent = false,
+ textIndent = nodeIndent,
+ emptyLines = 0,
+ atMoreIndented = false,
+ tmp,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x7C/* | */) {
+ folding = false;
+ } else if (ch === 0x3E/* > */) {
+ folding = true;
+ } else {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+
+ while (ch !== 0) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
+ if (CHOMPING_CLIP === chomping) {
+ chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
+ } else {
+ throwError(state, 'repeat of a chomping mode identifier');
+ }
+
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
+ if (tmp === 0) {
+ throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
+ } else if (!detectedIndent) {
+ textIndent = nodeIndent + tmp - 1;
+ detectedIndent = true;
+ } else {
+ throwError(state, 'repeat of an indentation width identifier');
+ }
+
+ } else {
+ break;
+ }
+ }
+
+ if (is_WHITE_SPACE(ch)) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (is_WHITE_SPACE(ch));
+
+ if (ch === 0x23/* # */) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (!is_EOL(ch) && (ch !== 0));
+ }
+ }
+
+ while (ch !== 0) {
+ readLineBreak(state);
+ state.lineIndent = 0;
+
+ ch = state.input.charCodeAt(state.position);
+
+ while ((!detectedIndent || state.lineIndent < textIndent) &&
+ (ch === 0x20/* Space */)) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (!detectedIndent && state.lineIndent > textIndent) {
+ textIndent = state.lineIndent;
+ }
+
+ if (is_EOL(ch)) {
+ emptyLines++;
+ continue;
+ }
+
+ // End of the scalar.
+ if (state.lineIndent < textIndent) {
+
+ // Perform the chomping.
+ if (chomping === CHOMPING_KEEP) {
+ state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+ } else if (chomping === CHOMPING_CLIP) {
+ if (didReadContent) { // i.e. only if the scalar is not empty.
+ state.result += '\n';
+ }
+ }
+
+ // Break this `while` cycle and go to the funciton's epilogue.
+ break;
+ }
+
+ // Folded style: use fancy rules to handle line breaks.
+ if (folding) {
+
+ // Lines starting with white space characters (more-indented lines) are not folded.
+ if (is_WHITE_SPACE(ch)) {
+ atMoreIndented = true;
+ // except for the first content line (cf. Example 8.1)
+ state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+
+ // End of more-indented block.
+ } else if (atMoreIndented) {
+ atMoreIndented = false;
+ state.result += common$1.repeat('\n', emptyLines + 1);
+
+ // Just one line break - perceive as the same line.
+ } else if (emptyLines === 0) {
+ if (didReadContent) { // i.e. only if we have already read some scalar content.
+ state.result += ' ';
+ }
+
+ // Several line breaks - perceive as different lines.
+ } else {
+ state.result += common$1.repeat('\n', emptyLines);
+ }
+
+ // Literal style: just add exact number of line breaks between content lines.
+ } else {
+ // Keep all line breaks except the header line break.
+ state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+ }
+
+ didReadContent = true;
+ detectedIndent = true;
+ emptyLines = 0;
+ captureStart = state.position;
+
+ while (!is_EOL(ch) && (ch !== 0)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ captureSegment(state, captureStart, state.position, false);
+ }
+
+ return true;
+}
+
+function readBlockSequence(state, nodeIndent) {
+ var _line,
+ _tag = state.tag,
+ _anchor = state.anchor,
+ _result = [],
+ following,
+ detected = false,
+ ch;
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+
+ if (ch !== 0x2D/* - */) {
+ break;
+ }
+
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (!is_WS_OR_EOL(following)) {
+ break;
+ }
+
+ detected = true;
+ state.position++;
+
+ if (skipSeparationSpace(state, true, -1)) {
+ if (state.lineIndent <= nodeIndent) {
+ _result.push(null);
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ }
+ }
+
+ _line = state.line;
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
+ _result.push(state.result);
+ skipSeparationSpace(state, true, -1);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
+ throwError(state, 'bad indentation of a sequence entry');
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = 'sequence';
+ state.result = _result;
+ return true;
+ }
+ return false;
+}
+
+function readBlockMapping(state, nodeIndent, flowIndent) {
+ var following,
+ allowCompact,
+ _line,
+ _pos,
+ _tag = state.tag,
+ _anchor = state.anchor,
+ _result = {},
+ overridableKeys = {},
+ keyTag = null,
+ keyNode = null,
+ valueNode = null,
+ atExplicitKey = false,
+ detected = false,
+ ch;
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ following = state.input.charCodeAt(state.position + 1);
+ _line = state.line; // Save the current line.
+ _pos = state.position;
+
+ //
+ // Explicit notation case. There are two separate blocks:
+ // first for the key (denoted by "?") and second for the value (denoted by ":")
+ //
+ if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
+
+ if (ch === 0x3F/* ? */) {
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ detected = true;
+ atExplicitKey = true;
+ allowCompact = true;
+
+ } else if (atExplicitKey) {
+ // i.e. 0x3A/* : */ === character after the explicit key.
+ atExplicitKey = false;
+ allowCompact = true;
+
+ } else {
+ throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
+ }
+
+ state.position += 1;
+ ch = following;
+
+ //
+ // Implicit notation case. Flow-style node as the key first, then ":", and the value.
+ //
+ } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
+
+ if (state.line === _line) {
+ ch = state.input.charCodeAt(state.position);
+
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (ch === 0x3A/* : */) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if (!is_WS_OR_EOL(ch)) {
+ throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
+ }
+
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ detected = true;
+ atExplicitKey = false;
+ allowCompact = false;
+ keyTag = state.tag;
+ keyNode = state.result;
+
+ } else if (detected) {
+ throwError(state, 'can not read an implicit mapping pair; a colon is missed');
+
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true; // Keep the result of `composeNode`.
+ }
+
+ } else if (detected) {
+ throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
+
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true; // Keep the result of `composeNode`.
+ }
+
+ } else {
+ break; // Reading is done. Go to the epilogue.
+ }
+
+ //
+ // Common reading code for both explicit and implicit notations.
+ //
+ if (state.line === _line || state.lineIndent > nodeIndent) {
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
+ if (atExplicitKey) {
+ keyNode = state.result;
+ } else {
+ valueNode = state.result;
+ }
+ }
+
+ if (!atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ skipSeparationSpace(state, true, -1);
+ ch = state.input.charCodeAt(state.position);
+ }
+
+ if (state.lineIndent > nodeIndent && (ch !== 0)) {
+ throwError(state, 'bad indentation of a mapping entry');
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+
+ //
+ // Epilogue.
+ //
+
+ // Special case: last mapping's node contains only the key in explicit notation.
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
+ }
+
+ // Expose the resulting mapping.
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = 'mapping';
+ state.result = _result;
+ }
+
+ return detected;
+}
+
+function readTagProperty(state) {
+ var _position,
+ isVerbatim = false,
+ isNamed = false,
+ tagHandle,
+ tagName,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x21/* ! */) return false;
+
+ if (state.tag !== null) {
+ throwError(state, 'duplication of a tag property');
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x3C/* < */) {
+ isVerbatim = true;
+ ch = state.input.charCodeAt(++state.position);
+
+ } else if (ch === 0x21/* ! */) {
+ isNamed = true;
+ tagHandle = '!!';
+ ch = state.input.charCodeAt(++state.position);
+
+ } else {
+ tagHandle = '!';
+ }
+
+ _position = state.position;
+
+ if (isVerbatim) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (ch !== 0 && ch !== 0x3E/* > */);
+
+ if (state.position < state.length) {
+ tagName = state.input.slice(_position, state.position);
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ throwError(state, 'unexpected end of the stream within a verbatim tag');
+ }
+ } else {
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+
+ if (ch === 0x21/* ! */) {
+ if (!isNamed) {
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
+
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
+ throwError(state, 'named tag handle cannot contain such characters');
+ }
+
+ isNamed = true;
+ _position = state.position + 1;
+ } else {
+ throwError(state, 'tag suffix cannot contain exclamation marks');
+ }
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ tagName = state.input.slice(_position, state.position);
+
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
+ throwError(state, 'tag suffix cannot contain flow indicator characters');
+ }
+ }
+
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
+ throwError(state, 'tag name cannot contain such characters: ' + tagName);
+ }
+
+ if (isVerbatim) {
+ state.tag = tagName;
+
+ } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
+ state.tag = state.tagMap[tagHandle] + tagName;
+
+ } else if (tagHandle === '!') {
+ state.tag = '!' + tagName;
+
+ } else if (tagHandle === '!!') {
+ state.tag = 'tag:yaml.org,2002:' + tagName;
+
+ } else {
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
+ }
+
+ return true;
+}
+
+function readAnchorProperty(state) {
+ var _position,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x26/* & */) return false;
+
+ if (state.anchor !== null) {
+ throwError(state, 'duplication of an anchor property');
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (state.position === _position) {
+ throwError(state, 'name of an anchor node must contain at least one character');
+ }
+
+ state.anchor = state.input.slice(_position, state.position);
+ return true;
+}
+
+function readAlias(state) {
+ var _position, alias,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x2A/* * */) return false;
+
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (state.position === _position) {
+ throwError(state, 'name of an alias node must contain at least one character');
+ }
+
+ alias = state.input.slice(_position, state.position);
+
+ if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
+ throwError(state, 'unidentified alias "' + alias + '"');
+ }
+
+ state.result = state.anchorMap[alias];
+ skipSeparationSpace(state, true, -1);
+ return true;
+}
+
+function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
+ var allowBlockStyles,
+ allowBlockScalars,
+ allowBlockCollections,
+ indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ }
+ }
+
+ if (indentStatus === 1) {
+ while (readTagProperty(state) || readAnchorProperty(state)) {
+ if (skipSeparationSpace(state, true, -1)) {
+ atNewLine = true;
+ allowBlockCollections = allowBlockStyles;
+
+ if (state.lineIndent > parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ } else {
+ allowBlockCollections = false;
+ }
+ }
+ }
+
+ if (allowBlockCollections) {
+ allowBlockCollections = atNewLine || allowCompact;
+ }
+
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
+ flowIndent = parentIndent;
+ } else {
+ flowIndent = parentIndent + 1;
+ }
+
+ blockIndent = state.position - state.lineStart;
+
+ if (indentStatus === 1) {
+ if (allowBlockCollections &&
+ (readBlockSequence(state, blockIndent) ||
+ readBlockMapping(state, blockIndent, flowIndent)) ||
+ readFlowCollection(state, flowIndent)) {
+ hasContent = true;
+ } else {
+ if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
+ readSingleQuotedScalar(state, flowIndent) ||
+ readDoubleQuotedScalar(state, flowIndent)) {
+ hasContent = true;
+
+ } else if (readAlias(state)) {
+ hasContent = true;
+
+ if (state.tag !== null || state.anchor !== null) {
+ throwError(state, 'alias node should not have any properties');
+ }
+
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
+ hasContent = true;
+
+ if (state.tag === null) {
+ state.tag = '?';
+ }
+ }
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ } else if (indentStatus === 0) {
+ // Special case: block sequences are allowed to have same indentation level as the parent.
+ // http://www.yaml.org/spec/1.2/spec.html#id2799784
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
+ }
+ }
+
+ if (state.tag !== null && state.tag !== '!') {
+ if (state.tag === '?') {
+ // Implicit resolving is not allowed for non-scalar types, and '?'
+ // non-specific tag is only automatically assigned to plain scalars.
+ //
+ // We only need to check kind conformity in case user explicitly assigns '?'
+ // tag, for example like this: "!> [0]"
+ //
+ if (state.result !== null && state.kind !== 'scalar') {
+ throwError(state, 'unacceptable node kind for !> tag; it should be "scalar", not "' + state.kind + '"');
+ }
+
+ for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
+ type = state.implicitTypes[typeIndex];
+
+ if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
+ state.result = type.construct(state.result);
+ state.tag = type.tag;
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ break;
+ }
+ }
+ } else if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
+ type = state.typeMap[state.kind || 'fallback'][state.tag];
+
+ if (state.result !== null && type.kind !== state.kind) {
+ throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
+ }
+
+ if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
+ throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
+ } else {
+ state.result = type.construct(state.result);
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ } else {
+ throwError(state, 'unknown tag !<' + state.tag + '>');
+ }
+ }
+
+ if (state.listener !== null) {
+ state.listener('close', state);
+ }
+ return state.tag !== null || state.anchor !== null || hasContent;
+}
+
+function readDocument(state) {
+ var documentStart = state.position,
+ _position,
+ directiveName,
+ directiveArgs,
+ hasDirectives = false,
+ ch;
+
+ state.version = null;
+ state.checkLineBreaks = state.legacy;
+ state.tagMap = {};
+ state.anchorMap = {};
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ skipSeparationSpace(state, true, -1);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (state.lineIndent > 0 || ch !== 0x25/* % */) {
+ break;
+ }
+
+ hasDirectives = true;
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ directiveName = state.input.slice(_position, state.position);
+ directiveArgs = [];
+
+ if (directiveName.length < 1) {
+ throwError(state, 'directive name must not be less than one character in length');
+ }
+
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (ch === 0x23/* # */) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (ch !== 0 && !is_EOL(ch));
+ break;
+ }
+
+ if (is_EOL(ch)) break;
+
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ directiveArgs.push(state.input.slice(_position, state.position));
+ }
+
+ if (ch !== 0) readLineBreak(state);
+
+ if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
+ } else {
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
+ }
+ }
+
+ skipSeparationSpace(state, true, -1);
+
+ if (state.lineIndent === 0 &&
+ state.input.charCodeAt(state.position) === 0x2D/* - */ &&
+ state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
+ state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+
+ } else if (hasDirectives) {
+ throwError(state, 'directives end mark is expected');
+ }
+
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
+ skipSeparationSpace(state, true, -1);
+
+ if (state.checkLineBreaks &&
+ PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
+ throwWarning(state, 'non-ASCII line breaks are interpreted as content');
+ }
+
+ state.documents.push(state.result);
+
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
+
+ if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+ }
+ return;
+ }
+
+ if (state.position < (state.length - 1)) {
+ throwError(state, 'end of the stream or a document separator is expected');
+ } else {
+ return;
+ }
+}
+
+
+function loadDocuments(input, options) {
+ input = String(input);
+ options = options || {};
+
+ if (input.length !== 0) {
+
+ // Add tailing `\n` if not exists
+ if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
+ input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
+ input += '\n';
+ }
+
+ // Strip BOM
+ if (input.charCodeAt(0) === 0xFEFF) {
+ input = input.slice(1);
+ }
+ }
+
+ var state = new State$1(input, options);
+
+ var nullpos = input.indexOf('\0');
+
+ if (nullpos !== -1) {
+ state.position = nullpos;
+ throwError(state, 'null byte is not allowed in input');
+ }
+
+ // Use 0 as string terminator. That significantly simplifies bounds check.
+ state.input += '\0';
+
+ while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
+ state.lineIndent += 1;
+ state.position += 1;
+ }
+
+ while (state.position < (state.length - 1)) {
+ readDocument(state);
+ }
+
+ return state.documents;
+}
+
+
+function loadAll(input, iterator, options) {
+ if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
+ options = iterator;
+ iterator = null;
+ }
+
+ var documents = loadDocuments(input, options);
+
+ if (typeof iterator !== 'function') {
+ return documents;
+ }
+
+ for (var index = 0, length = documents.length; index < length; index += 1) {
+ iterator(documents[index]);
+ }
+}
+
+
+function load(input, options) {
+ var documents = loadDocuments(input, options);
+
+ if (documents.length === 0) {
+ /*eslint-disable no-undefined*/
+ return undefined;
+ } else if (documents.length === 1) {
+ return documents[0];
+ }
+ throw new YAMLException$1('expected a single document in the stream, but found more');
+}
+
+
+function safeLoadAll(input, iterator, options) {
+ if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {
+ options = iterator;
+ iterator = null;
+ }
+
+ return loadAll(input, iterator, common$1.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options));
+}
+
+
+function safeLoad(input, options) {
+ return load(input, common$1.extend({ schema: DEFAULT_SAFE_SCHEMA$1 }, options));
+}
+
+
+loader$1.loadAll = loadAll;
+loader$1.load = load;
+loader$1.safeLoadAll = safeLoadAll;
+loader$1.safeLoad = safeLoad;
+
+var dumper$1 = {};
+
+/*eslint-disable no-use-before-define*/
+
+var common = common$6;
+var YAMLException = exception;
+var DEFAULT_FULL_SCHEMA = default_full;
+var DEFAULT_SAFE_SCHEMA = default_safe;
+
+var _toString = Object.prototype.toString;
+var _hasOwnProperty = Object.prototype.hasOwnProperty;
+
+var CHAR_TAB = 0x09; /* Tab */
+var CHAR_LINE_FEED = 0x0A; /* LF */
+var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
+var CHAR_SPACE = 0x20; /* Space */
+var CHAR_EXCLAMATION = 0x21; /* ! */
+var CHAR_DOUBLE_QUOTE = 0x22; /* " */
+var CHAR_SHARP = 0x23; /* # */
+var CHAR_PERCENT = 0x25; /* % */
+var CHAR_AMPERSAND = 0x26; /* & */
+var CHAR_SINGLE_QUOTE = 0x27; /* ' */
+var CHAR_ASTERISK = 0x2A; /* * */
+var CHAR_COMMA = 0x2C; /* , */
+var CHAR_MINUS = 0x2D; /* - */
+var CHAR_COLON = 0x3A; /* : */
+var CHAR_EQUALS = 0x3D; /* = */
+var CHAR_GREATER_THAN = 0x3E; /* > */
+var CHAR_QUESTION = 0x3F; /* ? */
+var CHAR_COMMERCIAL_AT = 0x40; /* @ */
+var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
+var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
+var CHAR_GRAVE_ACCENT = 0x60; /* ` */
+var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
+var CHAR_VERTICAL_LINE = 0x7C; /* | */
+var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
+
+var ESCAPE_SEQUENCES = {};
+
+ESCAPE_SEQUENCES[0x00] = '\\0';
+ESCAPE_SEQUENCES[0x07] = '\\a';
+ESCAPE_SEQUENCES[0x08] = '\\b';
+ESCAPE_SEQUENCES[0x09] = '\\t';
+ESCAPE_SEQUENCES[0x0A] = '\\n';
+ESCAPE_SEQUENCES[0x0B] = '\\v';
+ESCAPE_SEQUENCES[0x0C] = '\\f';
+ESCAPE_SEQUENCES[0x0D] = '\\r';
+ESCAPE_SEQUENCES[0x1B] = '\\e';
+ESCAPE_SEQUENCES[0x22] = '\\"';
+ESCAPE_SEQUENCES[0x5C] = '\\\\';
+ESCAPE_SEQUENCES[0x85] = '\\N';
+ESCAPE_SEQUENCES[0xA0] = '\\_';
+ESCAPE_SEQUENCES[0x2028] = '\\L';
+ESCAPE_SEQUENCES[0x2029] = '\\P';
+
+var DEPRECATED_BOOLEANS_SYNTAX = [
+ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
+ 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
+];
+
+function compileStyleMap(schema, map) {
+ var result, keys, index, length, tag, style, type;
+
+ if (map === null) return {};
+
+ result = {};
+ keys = Object.keys(map);
+
+ for (index = 0, length = keys.length; index < length; index += 1) {
+ tag = keys[index];
+ style = String(map[tag]);
+
+ if (tag.slice(0, 2) === '!!') {
+ tag = 'tag:yaml.org,2002:' + tag.slice(2);
+ }
+ type = schema.compiledTypeMap['fallback'][tag];
+
+ if (type && _hasOwnProperty.call(type.styleAliases, style)) {
+ style = type.styleAliases[style];
+ }
+
+ result[tag] = style;
+ }
+
+ return result;
+}
+
+function encodeHex(character) {
+ var string, handle, length;
+
+ string = character.toString(16).toUpperCase();
+
+ if (character <= 0xFF) {
+ handle = 'x';
+ length = 2;
+ } else if (character <= 0xFFFF) {
+ handle = 'u';
+ length = 4;
+ } else if (character <= 0xFFFFFFFF) {
+ handle = 'U';
+ length = 8;
+ } else {
+ throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
+ }
+
+ return '\\' + handle + common.repeat('0', length - string.length) + string;
+}
+
+function State(options) {
+ this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
+ this.indent = Math.max(1, (options['indent'] || 2));
+ this.noArrayIndent = options['noArrayIndent'] || false;
+ this.skipInvalid = options['skipInvalid'] || false;
+ this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
+ this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
+ this.sortKeys = options['sortKeys'] || false;
+ this.lineWidth = options['lineWidth'] || 80;
+ this.noRefs = options['noRefs'] || false;
+ this.noCompatMode = options['noCompatMode'] || false;
+ this.condenseFlow = options['condenseFlow'] || false;
+
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.explicitTypes = this.schema.compiledExplicit;
+
+ this.tag = null;
+ this.result = '';
+
+ this.duplicates = [];
+ this.usedDuplicates = null;
+}
+
+// Indents every line in a string. Empty lines (\n only) are not indented.
+function indentString(string, spaces) {
+ var ind = common.repeat(' ', spaces),
+ position = 0,
+ next = -1,
+ result = '',
+ line,
+ length = string.length;
+
+ while (position < length) {
+ next = string.indexOf('\n', position);
+ if (next === -1) {
+ line = string.slice(position);
+ position = length;
+ } else {
+ line = string.slice(position, next + 1);
+ position = next + 1;
+ }
+
+ if (line.length && line !== '\n') result += ind;
+
+ result += line;
+ }
+
+ return result;
+}
+
+function generateNextLine(state, level) {
+ return '\n' + common.repeat(' ', state.indent * level);
+}
+
+function testImplicitResolving(state, str) {
+ var index, length, type;
+
+ for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
+ type = state.implicitTypes[index];
+
+ if (type.resolve(str)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// [33] s-white ::= s-space | s-tab
+function isWhitespace(c) {
+ return c === CHAR_SPACE || c === CHAR_TAB;
+}
+
+// Returns true if the character can be printed without escaping.
+// From YAML 1.2: "any allowed characters known to be non-printable
+// should also be escaped. [However,] This isn’t mandatory"
+// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
+function isPrintable(c) {
+ return (0x00020 <= c && c <= 0x00007E)
+ || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
+ || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
+ || (0x10000 <= c && c <= 0x10FFFF);
+}
+
+// [34] ns-char ::= nb-char - s-white
+// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
+// [26] b-char ::= b-line-feed | b-carriage-return
+// [24] b-line-feed ::= #xA /* LF */
+// [25] b-carriage-return ::= #xD /* CR */
+// [3] c-byte-order-mark ::= #xFEFF
+function isNsChar(c) {
+ return isPrintable(c) && !isWhitespace(c)
+ // byte-order-mark
+ && c !== 0xFEFF
+ // b-char
+ && c !== CHAR_CARRIAGE_RETURN
+ && c !== CHAR_LINE_FEED;
+}
+
+// Simplified test for values allowed after the first character in plain style.
+function isPlainSafe(c, prev) {
+ // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
+ // where nb-char ::= c-printable - b-char - c-byte-order-mark.
+ return isPrintable(c) && c !== 0xFEFF
+ // - c-flow-indicator
+ && c !== CHAR_COMMA
+ && c !== CHAR_LEFT_SQUARE_BRACKET
+ && c !== CHAR_RIGHT_SQUARE_BRACKET
+ && c !== CHAR_LEFT_CURLY_BRACKET
+ && c !== CHAR_RIGHT_CURLY_BRACKET
+ // - ":" - "#"
+ // /* An ns-char preceding */ "#"
+ && c !== CHAR_COLON
+ && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));
+}
+
+// Simplified test for values allowed as the first character in plain style.
+function isPlainSafeFirst(c) {
+ // Uses a subset of ns-char - c-indicator
+ // where ns-char = nb-char - s-white.
+ return isPrintable(c) && c !== 0xFEFF
+ && !isWhitespace(c) // - s-white
+ // - (c-indicator ::=
+ // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
+ && c !== CHAR_MINUS
+ && c !== CHAR_QUESTION
+ && c !== CHAR_COLON
+ && c !== CHAR_COMMA
+ && c !== CHAR_LEFT_SQUARE_BRACKET
+ && c !== CHAR_RIGHT_SQUARE_BRACKET
+ && c !== CHAR_LEFT_CURLY_BRACKET
+ && c !== CHAR_RIGHT_CURLY_BRACKET
+ // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
+ && c !== CHAR_SHARP
+ && c !== CHAR_AMPERSAND
+ && c !== CHAR_ASTERISK
+ && c !== CHAR_EXCLAMATION
+ && c !== CHAR_VERTICAL_LINE
+ && c !== CHAR_EQUALS
+ && c !== CHAR_GREATER_THAN
+ && c !== CHAR_SINGLE_QUOTE
+ && c !== CHAR_DOUBLE_QUOTE
+ // | “%” | “@” | “`”)
+ && c !== CHAR_PERCENT
+ && c !== CHAR_COMMERCIAL_AT
+ && c !== CHAR_GRAVE_ACCENT;
+}
+
+// Determines whether block indentation indicator is required.
+function needIndentIndicator(string) {
+ var leadingSpaceRe = /^\n* /;
+ return leadingSpaceRe.test(string);
+}
+
+var STYLE_PLAIN = 1,
+ STYLE_SINGLE = 2,
+ STYLE_LITERAL = 3,
+ STYLE_FOLDED = 4,
+ STYLE_DOUBLE = 5;
+
+// Determines which scalar styles are possible and returns the preferred style.
+// lineWidth = -1 => no limit.
+// Pre-conditions: str.length > 0.
+// Post-conditions:
+// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
+// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
+// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
+function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
+ var i;
+ var char, prev_char;
+ var hasLineBreak = false;
+ var hasFoldableLine = false; // only checked if shouldTrackWidth
+ var shouldTrackWidth = lineWidth !== -1;
+ var previousLineBreak = -1; // count the first line correctly
+ var plain = isPlainSafeFirst(string.charCodeAt(0))
+ && !isWhitespace(string.charCodeAt(string.length - 1));
+
+ if (singleLineOnly) {
+ // Case: no block styles.
+ // Check for disallowed characters to rule out plain and single.
+ for (i = 0; i < string.length; i++) {
+ char = string.charCodeAt(i);
+ if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
+ plain = plain && isPlainSafe(char, prev_char);
+ }
+ } else {
+ // Case: block styles permitted.
+ for (i = 0; i < string.length; i++) {
+ char = string.charCodeAt(i);
+ if (char === CHAR_LINE_FEED) {
+ hasLineBreak = true;
+ // Check if any line can be folded.
+ if (shouldTrackWidth) {
+ hasFoldableLine = hasFoldableLine ||
+ // Foldable line = too long, and not more-indented.
+ (i - previousLineBreak - 1 > lineWidth &&
+ string[previousLineBreak + 1] !== ' ');
+ previousLineBreak = i;
+ }
+ } else if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ prev_char = i > 0 ? string.charCodeAt(i - 1) : null;
+ plain = plain && isPlainSafe(char, prev_char);
+ }
+ // in case the end is missing a \n
+ hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
+ (i - previousLineBreak - 1 > lineWidth &&
+ string[previousLineBreak + 1] !== ' '));
+ }
+ // Although every style can represent \n without escaping, prefer block styles
+ // for multiline, since they're more readable and they don't add empty lines.
+ // Also prefer folding a super-long line.
+ if (!hasLineBreak && !hasFoldableLine) {
+ // Strings interpretable as another type have to be quoted;
+ // e.g. the string 'true' vs. the boolean true.
+ return plain && !testAmbiguousType(string)
+ ? STYLE_PLAIN : STYLE_SINGLE;
+ }
+ // Edge case: block indentation indicator can only have one digit.
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
+ return STYLE_DOUBLE;
+ }
+ // At this point we know block styles are valid.
+ // Prefer literal style unless we want to fold.
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
+}
+
+// Note: line breaking/folding is implemented for only the folded style.
+// NB. We drop the last trailing newline (if any) of a returned block scalar
+// since the dumper adds its own newline. This always works:
+// • No ending newline => unaffected; already using strip "-" chomping.
+// • Ending newline => removed then restored.
+// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
+function writeScalar(state, string, level, iskey) {
+ state.dump = (function () {
+ if (string.length === 0) {
+ return "''";
+ }
+ if (!state.noCompatMode &&
+ DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
+ return "'" + string + "'";
+ }
+
+ var indent = state.indent * Math.max(1, level); // no 0-indent scalars
+ // As indentation gets deeper, let the width decrease monotonically
+ // to the lower bound min(state.lineWidth, 40).
+ // Note that this implies
+ // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
+ // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
+ // This behaves better than a constant minimum width which disallows narrower options,
+ // or an indent threshold which causes the width to suddenly increase.
+ var lineWidth = state.lineWidth === -1
+ ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
+
+ // Without knowing if keys are implicit/explicit, assume implicit for safety.
+ var singleLineOnly = iskey
+ // No block styles in flow mode.
+ || (state.flowLevel > -1 && level >= state.flowLevel);
+ function testAmbiguity(string) {
+ return testImplicitResolving(state, string);
+ }
+
+ switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
+ case STYLE_PLAIN:
+ return string;
+ case STYLE_SINGLE:
+ return "'" + string.replace(/'/g, "''") + "'";
+ case STYLE_LITERAL:
+ return '|' + blockHeader(string, state.indent)
+ + dropEndingNewline(indentString(string, indent));
+ case STYLE_FOLDED:
+ return '>' + blockHeader(string, state.indent)
+ + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
+ case STYLE_DOUBLE:
+ return '"' + escapeString(string) + '"';
+ default:
+ throw new YAMLException('impossible error: invalid scalar style');
+ }
+ }());
+}
+
+// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
+function blockHeader(string, indentPerLevel) {
+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
+
+ // note the special case: the string '\n' counts as a "trailing" empty line.
+ var clip = string[string.length - 1] === '\n';
+ var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
+ var chomp = keep ? '+' : (clip ? '' : '-');
+
+ return indentIndicator + chomp + '\n';
+}
+
+// (See the note for writeScalar.)
+function dropEndingNewline(string) {
+ return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
+}
+
+// Note: a long line without a suitable break point will exceed the width limit.
+// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
+function foldString(string, width) {
+ // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
+ // unless they're before or after a more-indented line, or at the very
+ // beginning or end, in which case $k$ maps to $k$.
+ // Therefore, parse each chunk as newline(s) followed by a content line.
+ var lineRe = /(\n+)([^\n]*)/g;
+
+ // first line (possibly an empty line)
+ var result = (function () {
+ var nextLF = string.indexOf('\n');
+ nextLF = nextLF !== -1 ? nextLF : string.length;
+ lineRe.lastIndex = nextLF;
+ return foldLine(string.slice(0, nextLF), width);
+ }());
+ // If we haven't reached the first content line yet, don't add an extra \n.
+ var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
+ var moreIndented;
+
+ // rest of the lines
+ var match;
+ while ((match = lineRe.exec(string))) {
+ var prefix = match[1], line = match[2];
+ moreIndented = (line[0] === ' ');
+ result += prefix
+ + (!prevMoreIndented && !moreIndented && line !== ''
+ ? '\n' : '')
+ + foldLine(line, width);
+ prevMoreIndented = moreIndented;
+ }
+
+ return result;
+}
+
+// Greedy line breaking.
+// Picks the longest line under the limit each time,
+// otherwise settles for the shortest line over the limit.
+// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
+function foldLine(line, width) {
+ if (line === '' || line[0] === ' ') return line;
+
+ // Since a more-indented line adds a \n, breaks can't be followed by a space.
+ var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
+ var match;
+ // start is an inclusive index. end, curr, and next are exclusive.
+ var start = 0, end, curr = 0, next = 0;
+ var result = '';
+
+ // Invariants: 0 <= start <= length-1.
+ // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
+ // Inside the loop:
+ // A match implies length >= 2, so curr and next are <= length-2.
+ while ((match = breakRe.exec(line))) {
+ next = match.index;
+ // maintain invariant: curr - start <= width
+ if (next - start > width) {
+ end = (curr > start) ? curr : next; // derive end <= length-2
+ result += '\n' + line.slice(start, end);
+ // skip the space that was output as \n
+ start = end + 1; // derive start <= length-1
+ }
+ curr = next;
+ }
+
+ // By the invariants, start <= length-1, so there is something left over.
+ // It is either the whole string or a part starting from non-whitespace.
+ result += '\n';
+ // Insert a break if the remainder is too long and there is a break available.
+ if (line.length - start > width && curr > start) {
+ result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
+ } else {
+ result += line.slice(start);
+ }
+
+ return result.slice(1); // drop extra \n joiner
+}
+
+// Escapes a double-quoted string.
+function escapeString(string) {
+ var result = '';
+ var char, nextChar;
+ var escapeSeq;
+
+ for (var i = 0; i < string.length; i++) {
+ char = string.charCodeAt(i);
+ // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
+ if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
+ nextChar = string.charCodeAt(i + 1);
+ if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
+ // Combine the surrogate pair and store it escaped.
+ result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
+ // Advance index one extra since we already used that char here.
+ i++; continue;
+ }
+ }
+ escapeSeq = ESCAPE_SEQUENCES[char];
+ result += !escapeSeq && isPrintable(char)
+ ? string[i]
+ : escapeSeq || encodeHex(char);
+ }
+
+ return result;
+}
+
+function writeFlowSequence(state, level, object) {
+ var _result = '',
+ _tag = state.tag,
+ index,
+ length;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ // Write only valid elements.
+ if (writeNode(state, level, object[index], false, false)) {
+ if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
+ _result += state.dump;
+ }
+ }
+
+ state.tag = _tag;
+ state.dump = '[' + _result + ']';
+}
+
+function writeBlockSequence(state, level, object, compact) {
+ var _result = '',
+ _tag = state.tag,
+ index,
+ length;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ // Write only valid elements.
+ if (writeNode(state, level + 1, object[index], true, true)) {
+ if (!compact || index !== 0) {
+ _result += generateNextLine(state, level);
+ }
+
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ _result += '-';
+ } else {
+ _result += '- ';
+ }
+
+ _result += state.dump;
+ }
+ }
+
+ state.tag = _tag;
+ state.dump = _result || '[]'; // Empty sequence if no valid values.
+}
+
+function writeFlowMapping(state, level, object) {
+ var _result = '',
+ _tag = state.tag,
+ objectKeyList = Object.keys(object),
+ index,
+ length,
+ objectKey,
+ objectValue,
+ pairBuffer;
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+
+ pairBuffer = '';
+ if (index !== 0) pairBuffer += ', ';
+
+ if (state.condenseFlow) pairBuffer += '"';
+
+ objectKey = objectKeyList[index];
+ objectValue = object[objectKey];
+
+ if (!writeNode(state, level, objectKey, false, false)) {
+ continue; // Skip this pair because of invalid key;
+ }
+
+ if (state.dump.length > 1024) pairBuffer += '? ';
+
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
+
+ if (!writeNode(state, level, objectValue, false, false)) {
+ continue; // Skip this pair because of invalid value.
+ }
+
+ pairBuffer += state.dump;
+
+ // Both key and value are valid.
+ _result += pairBuffer;
+ }
+
+ state.tag = _tag;
+ state.dump = '{' + _result + '}';
+}
+
+function writeBlockMapping(state, level, object, compact) {
+ var _result = '',
+ _tag = state.tag,
+ objectKeyList = Object.keys(object),
+ index,
+ length,
+ objectKey,
+ objectValue,
+ explicitPair,
+ pairBuffer;
+
+ // Allow sorting keys so that the output file is deterministic
+ if (state.sortKeys === true) {
+ // Default sorting
+ objectKeyList.sort();
+ } else if (typeof state.sortKeys === 'function') {
+ // Custom sort function
+ objectKeyList.sort(state.sortKeys);
+ } else if (state.sortKeys) {
+ // Something is wrong
+ throw new YAMLException('sortKeys must be a boolean or a function');
+ }
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ pairBuffer = '';
+
+ if (!compact || index !== 0) {
+ pairBuffer += generateNextLine(state, level);
+ }
+
+ objectKey = objectKeyList[index];
+ objectValue = object[objectKey];
+
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
+ continue; // Skip this pair because of invalid key.
+ }
+
+ explicitPair = (state.tag !== null && state.tag !== '?') ||
+ (state.dump && state.dump.length > 1024);
+
+ if (explicitPair) {
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += '?';
+ } else {
+ pairBuffer += '? ';
+ }
+ }
+
+ pairBuffer += state.dump;
+
+ if (explicitPair) {
+ pairBuffer += generateNextLine(state, level);
+ }
+
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
+ continue; // Skip this pair because of invalid value.
+ }
+
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += ':';
+ } else {
+ pairBuffer += ': ';
+ }
+
+ pairBuffer += state.dump;
+
+ // Both key and value are valid.
+ _result += pairBuffer;
+ }
+
+ state.tag = _tag;
+ state.dump = _result || '{}'; // Empty mapping if no valid pairs.
+}
+
+function detectType(state, object, explicit) {
+ var _result, typeList, index, length, type, style;
+
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
+
+ for (index = 0, length = typeList.length; index < length; index += 1) {
+ type = typeList[index];
+
+ if ((type.instanceOf || type.predicate) &&
+ (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
+ (!type.predicate || type.predicate(object))) {
+
+ state.tag = explicit ? type.tag : '?';
+
+ if (type.represent) {
+ style = state.styleMap[type.tag] || type.defaultStyle;
+
+ if (_toString.call(type.represent) === '[object Function]') {
+ _result = type.represent(object, style);
+ } else if (_hasOwnProperty.call(type.represent, style)) {
+ _result = type.represent[style](object, style);
+ } else {
+ throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
+ }
+
+ state.dump = _result;
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// Serializes `object` and writes it to global `result`.
+// Returns true on success, or false on invalid object.
+//
+function writeNode(state, level, object, block, compact, iskey) {
+ state.tag = null;
+ state.dump = object;
+
+ if (!detectType(state, object, false)) {
+ detectType(state, object, true);
+ }
+
+ var type = _toString.call(state.dump);
+
+ if (block) {
+ block = (state.flowLevel < 0 || state.flowLevel > level);
+ }
+
+ var objectOrArray = type === '[object Object]' || type === '[object Array]',
+ duplicateIndex,
+ duplicate;
+
+ if (objectOrArray) {
+ duplicateIndex = state.duplicates.indexOf(object);
+ duplicate = duplicateIndex !== -1;
+ }
+
+ if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
+ compact = false;
+ }
+
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
+ state.dump = '*ref_' + duplicateIndex;
+ } else {
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
+ state.usedDuplicates[duplicateIndex] = true;
+ }
+ if (type === '[object Object]') {
+ if (block && (Object.keys(state.dump).length !== 0)) {
+ writeBlockMapping(state, level, state.dump, compact);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowMapping(state, level, state.dump);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ }
+ }
+ } else if (type === '[object Array]') {
+ var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;
+ if (block && (state.dump.length !== 0)) {
+ writeBlockSequence(state, arrayLevel, state.dump, compact);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowSequence(state, arrayLevel, state.dump);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ }
+ }
+ } else if (type === '[object String]') {
+ if (state.tag !== '?') {
+ writeScalar(state, state.dump, level, iskey);
+ }
+ } else {
+ if (state.skipInvalid) return false;
+ throw new YAMLException('unacceptable kind of an object to dump ' + type);
+ }
+
+ if (state.tag !== null && state.tag !== '?') {
+ state.dump = '!<' + state.tag + '> ' + state.dump;
+ }
+ }
+
+ return true;
+}
+
+function getDuplicateReferences(object, state) {
+ var objects = [],
+ duplicatesIndexes = [],
+ index,
+ length;
+
+ inspectNode(object, objects, duplicatesIndexes);
+
+ for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
+ }
+ state.usedDuplicates = new Array(length);
+}
+
+function inspectNode(object, objects, duplicatesIndexes) {
+ var objectKeyList,
+ index,
+ length;
+
+ if (object !== null && typeof object === 'object') {
+ index = objects.indexOf(object);
+ if (index !== -1) {
+ if (duplicatesIndexes.indexOf(index) === -1) {
+ duplicatesIndexes.push(index);
+ }
+ } else {
+ objects.push(object);
+
+ if (Array.isArray(object)) {
+ for (index = 0, length = object.length; index < length; index += 1) {
+ inspectNode(object[index], objects, duplicatesIndexes);
+ }
+ } else {
+ objectKeyList = Object.keys(object);
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
+ }
+ }
+ }
+ }
+}
+
+function dump(input, options) {
+ options = options || {};
+
+ var state = new State(options);
+
+ if (!state.noRefs) getDuplicateReferences(input, state);
+
+ if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
+
+ return '';
+}
+
+function safeDump(input, options) {
+ return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
+}
+
+dumper$1.dump = dump;
+dumper$1.safeDump = safeDump;
+
+var loader = loader$1;
+var dumper = dumper$1;
+
+
+function deprecated(name) {
+ return function () {
+ throw new Error('Function ' + name + ' is deprecated and cannot be used.');
+ };
+}
+
+
+jsYaml$1.Type = type;
+jsYaml$1.Schema = schema;
+jsYaml$1.FAILSAFE_SCHEMA = failsafe;
+jsYaml$1.JSON_SCHEMA = json;
+jsYaml$1.CORE_SCHEMA = core$3;
+jsYaml$1.DEFAULT_SAFE_SCHEMA = default_safe;
+jsYaml$1.DEFAULT_FULL_SCHEMA = default_full;
+jsYaml$1.load = loader.load;
+jsYaml$1.loadAll = loader.loadAll;
+jsYaml$1.safeLoad = loader.safeLoad;
+jsYaml$1.safeLoadAll = loader.safeLoadAll;
+jsYaml$1.dump = dumper.dump;
+jsYaml$1.safeDump = dumper.safeDump;
+jsYaml$1.YAMLException = exception;
+
+// Deprecated schema names from JS-YAML 2.0.x
+jsYaml$1.MINIMAL_SCHEMA = failsafe;
+jsYaml$1.SAFE_SCHEMA = default_safe;
+jsYaml$1.DEFAULT_SCHEMA = default_full;
+
+// Deprecated functions from JS-YAML 1.x.x
+jsYaml$1.scan = deprecated('scan');
+jsYaml$1.parse = deprecated('parse');
+jsYaml$1.compose = deprecated('compose');
+jsYaml$1.addConstructor = deprecated('addConstructor');
+
+var yaml = jsYaml$1;
+
+
+var jsYaml = yaml;
+
+var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(manifestCreation, "__esModule", { value: true });
+manifestCreation.ManifestCreation = void 0;
+const fs_1 = __importDefault$3(require$$0$e);
+const js_yaml_1 = __importDefault$3(jsYaml);
+const path_1$1 = __importDefault$3(require$$0$c);
+const update_dotenv_1$1 = __importDefault$3(updateDotenv);
+const probot_octokit_1 = probotOctokit;
+class ManifestCreation {
+ get pkg() {
+ let pkg;
+ try {
+ pkg = commonjsRequire(path_1$1.default.join(process.cwd(), "package.json"));
+ }
+ catch (e) {
+ pkg = {};
+ }
+ return pkg;
+ }
+ async createWebhookChannel() {
+ try {
+ // tslint:disable:no-var-requires
+ const SmeeClient = requireSmeeClient();
+ await this.updateEnv({
+ WEBHOOK_PROXY_URL: await SmeeClient.createChannel(),
+ });
+ }
+ catch (error) {
+ // Smee is not available, so we'll just move on
+ // tslint:disable:no-console
+ console.warn("Unable to connect to smee.io, try restarting your server.");
+ }
+ }
+ getManifest(pkg, baseUrl) {
+ let manifest = {};
+ try {
+ const file = fs_1.default.readFileSync(path_1$1.default.join(process.cwd(), "app.yml"), "utf8");
+ manifest = js_yaml_1.default.safeLoad(file);
+ }
+ catch (error) {
+ // App config does not exist, which is ok.
+ // @ts-ignore - in theory error can be anything
+ if (error.code !== "ENOENT") {
+ throw error;
+ }
+ }
+ const generatedManifest = JSON.stringify(Object.assign({
+ description: manifest.description || pkg.description,
+ hook_attributes: {
+ url: process.env.WEBHOOK_PROXY_URL || `${baseUrl}/`,
+ },
+ name: process.env.PROJECT_DOMAIN || manifest.name || pkg.name,
+ public: manifest.public || true,
+ redirect_url: `${baseUrl}/probot/setup`,
+ // TODO: add setup url
+ // setup_url:`${baseUrl}/probot/success`,
+ url: manifest.url || pkg.homepage || pkg.repository,
+ version: "v1",
+ }, manifest));
+ return generatedManifest;
+ }
+ async createAppFromCode(code) {
+ const octokit = new probot_octokit_1.ProbotOctokit();
+ const options = {
+ code,
+ mediaType: {
+ previews: ["fury"], // needed for GHES 2.20 and older
+ },
+ ...(process.env.GHE_HOST && {
+ baseUrl: `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3`,
+ }),
+ };
+ const response = await octokit.request("POST /app-manifests/:code/conversions", options);
+ const { id, client_id, client_secret, webhook_secret, pem } = response.data;
+ await this.updateEnv({
+ APP_ID: id.toString(),
+ PRIVATE_KEY: `"${pem}"`,
+ WEBHOOK_SECRET: webhook_secret,
+ GITHUB_CLIENT_ID: client_id,
+ GITHUB_CLIENT_SECRET: client_secret,
+ });
+ return response.data.html_url;
+ }
+ async updateEnv(env) {
+ // Needs to be public due to tests
+ return (0, update_dotenv_1$1.default)(env);
+ }
+ get createAppUrl() {
+ const githubHost = process.env.GHE_HOST || `github.com`;
+ return `${process.env.GHE_PROTOCOL || "https"}://${githubHost}${process.env.GH_ORG ? "/organizations/".concat(process.env.GH_ORG) : ""}/settings/apps/new`;
+ }
+}
+manifestCreation.ManifestCreation = ManifestCreation;
+
+var isProduction$1 = {};
+
+Object.defineProperty(isProduction$1, "__esModule", { value: true });
+isProduction$1.isProduction = void 0;
+function isProduction() {
+ return process.env.NODE_ENV === "production";
+}
+isProduction$1.isProduction = isProduction;
+
+var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(setup, "__esModule", { value: true });
+setup.setupAppFactory = void 0;
+const body_parser_1 = __importDefault$2(bodyParserExports);
+const child_process_1 = require$$1$a;
+const update_dotenv_1 = __importDefault$2(updateDotenv);
+const manifest_creation_1 = manifestCreation;
+const logging_middleware_1 = loggingMiddleware;
+const is_production_1 = isProduction$1;
+const setupAppFactory = (host, port) => async function setupApp(app, { getRouter }) {
+ const setup = new manifest_creation_1.ManifestCreation();
+ // If not on Glitch or Production, create a smee URL
+ if (!(0, is_production_1.isProduction)() &&
+ !(process.env.PROJECT_DOMAIN ||
+ process.env.WEBHOOK_PROXY_URL ||
+ process.env.NO_SMEE_SETUP === "true")) {
+ await setup.createWebhookChannel();
+ }
+ if (!getRouter) {
+ throw new Error("getRouter is required to use the setup app");
+ }
+ const route = getRouter();
+ route.use((0, logging_middleware_1.getLoggingMiddleware)(app.log));
+ printWelcomeMessage(app, host, port);
+ route.get("/probot", async (req, res) => {
+ const baseUrl = getBaseUrl(req);
+ const pkg = setup.pkg;
+ const manifest = setup.getManifest(pkg, baseUrl);
+ const createAppUrl = setup.createAppUrl;
+ // Pass the manifest to be POST'd
+ res.render("setup.handlebars", { pkg, createAppUrl, manifest });
+ });
+ route.get("/probot/setup", async (req, res) => {
+ const { code } = req.query;
+ const response = await setup.createAppFromCode(code);
+ // If using glitch, restart the app
+ if (process.env.PROJECT_DOMAIN) {
+ (0, child_process_1.exec)("refresh", (error) => {
+ if (error) {
+ app.log.error(error);
+ }
+ });
+ }
+ else {
+ printRestartMessage(app);
+ }
+ res.redirect(`${response}/installations/new`);
+ });
+ route.get("/probot/import", async (_req, res) => {
+ const { WEBHOOK_PROXY_URL, GHE_HOST } = process.env;
+ const GH_HOST = `https://${GHE_HOST !== null && GHE_HOST !== void 0 ? GHE_HOST : "github.com"}`;
+ res.render("import.handlebars", { WEBHOOK_PROXY_URL, GH_HOST });
+ });
+ route.post("/probot/import", body_parser_1.default.json(), async (req, res) => {
+ const { appId, pem, webhook_secret } = req.body;
+ if (!appId || !pem || !webhook_secret) {
+ res.status(400).send("appId and/or pem and/or webhook_secret missing");
+ return;
+ }
+ (0, update_dotenv_1.default)({
+ APP_ID: appId,
+ PRIVATE_KEY: `"${pem}"`,
+ WEBHOOK_SECRET: webhook_secret,
+ });
+ res.end();
+ printRestartMessage(app);
+ });
+ route.get("/probot/success", async (req, res) => {
+ res.render("success.handlebars");
+ });
+ route.get("/", (req, res, next) => res.redirect("/probot"));
+};
+setup.setupAppFactory = setupAppFactory;
+function printWelcomeMessage(app, host, port) {
+ // use glitch env to get correct domain welcome message
+ // https://glitch.com/help/project/
+ const domain = process.env.PROJECT_DOMAIN ||
+ `http://${host !== null && host !== void 0 ? host : "localhost"}:${port || 3000}`;
+ [
+ ``,
+ `Welcome to Probot!`,
+ `Probot is in setup mode, webhooks cannot be received and`,
+ `custom routes will not work until APP_ID and PRIVATE_KEY`,
+ `are configured in .env.`,
+ `Please follow the instructions at ${domain} to configure .env.`,
+ `Once you are done, restart the server.`,
+ ``,
+ ].forEach((line) => {
+ app.log.info(line);
+ });
+}
+function printRestartMessage(app) {
+ app.log.info("");
+ app.log.info("Probot has been set up, please restart the server!");
+ app.log.info("");
+}
+function getBaseUrl(req) {
+ const protocols = req.headers["x-forwarded-proto"] || req.protocol;
+ const protocol = typeof protocols === "string" ? protocols.split(",")[0] : protocols[0];
+ const host = req.headers["x-forwarded-host"] || req.get("host");
+ const baseUrl = `${protocol}://${host}`;
+ return baseUrl;
+}
+
+var readCliOptions$1 = {};
+
+var commanderExports = {};
+var commander = {
+ get exports(){ return commanderExports; },
+ set exports(v){ commanderExports = v; },
+};
+
+/**
+ * Module dependencies.
+ */
+
+(function (module, exports) {
+ const EventEmitter = require$$0$f.EventEmitter;
+ const spawn = require$$1$a.spawn;
+ const path = require$$0$c;
+ const fs = require$$0$e;
+
+ // @ts-check
+
+ class Option {
+ /**
+ * Initialize a new `Option` with the given `flags` and `description`.
+ *
+ * @param {string} flags
+ * @param {string} description
+ * @api public
+ */
+
+ constructor(flags, description) {
+ this.flags = flags;
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
+ // variadic test ignores et al which might be used to describe custom splitting of single argument
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
+ const optionFlags = _parseOptionFlags(flags);
+ this.short = optionFlags.shortFlag;
+ this.long = optionFlags.longFlag;
+ this.negate = false;
+ if (this.long) {
+ this.negate = this.long.startsWith('--no-');
+ }
+ this.description = description || '';
+ this.defaultValue = undefined;
+ }
+
+ /**
+ * Return option name.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ name() {
+ if (this.long) {
+ return this.long.replace(/^--/, '');
+ }
+ return this.short.replace(/^-/, '');
+ };
+
+ /**
+ * Return option name, in a camelcase format that can be used
+ * as a object attribute key.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ attributeName() {
+ return camelcase(this.name().replace(/^no-/, ''));
+ };
+
+ /**
+ * Check if `arg` matches the short or long flag.
+ *
+ * @param {string} arg
+ * @return {boolean}
+ * @api private
+ */
+
+ is(arg) {
+ return this.short === arg || this.long === arg;
+ };
+ }
+
+ /**
+ * CommanderError class
+ * @class
+ */
+ class CommanderError extends Error {
+ /**
+ * Constructs the CommanderError class
+ * @param {number} exitCode suggested exit code which could be used with process.exit
+ * @param {string} code an id string representing the error
+ * @param {string} message human-readable description of the error
+ * @constructor
+ */
+ constructor(exitCode, code, message) {
+ super(message);
+ // properly capture stack trace in Node.js
+ Error.captureStackTrace(this, this.constructor);
+ this.name = this.constructor.name;
+ this.code = code;
+ this.exitCode = exitCode;
+ this.nestedError = undefined;
+ }
+ }
+
+ class Command extends EventEmitter {
+ /**
+ * Initialize a new `Command`.
+ *
+ * @param {string} [name]
+ * @api public
+ */
+
+ constructor(name) {
+ super();
+ this.commands = [];
+ this.options = [];
+ this.parent = null;
+ this._allowUnknownOption = false;
+ this._args = [];
+ this.rawArgs = null;
+ this._scriptPath = null;
+ this._name = name || '';
+ this._optionValues = {};
+ this._storeOptionsAsProperties = true; // backwards compatible by default
+ this._storeOptionsAsPropertiesCalled = false;
+ this._passCommandToAction = true; // backwards compatible by default
+ this._actionResults = [];
+ this._actionHandler = null;
+ this._executableHandler = false;
+ this._executableFile = null; // custom name for executable
+ this._defaultCommandName = null;
+ this._exitCallback = null;
+ this._aliases = [];
+ this._combineFlagAndOptionalValue = true;
+
+ this._hidden = false;
+ this._hasHelpOption = true;
+ this._helpFlags = '-h, --help';
+ this._helpDescription = 'display help for command';
+ this._helpShortFlag = '-h';
+ this._helpLongFlag = '--help';
+ this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
+ this._helpCommandName = 'help';
+ this._helpCommandnameAndArgs = 'help [command]';
+ this._helpCommandDescription = 'display help for command';
+ }
+
+ /**
+ * Define a command.
+ *
+ * There are two styles of command: pay attention to where to put the description.
+ *
+ * Examples:
+ *
+ * // Command implemented using action handler (description is supplied separately to `.command`)
+ * program
+ * .command('clone [destination]')
+ * .description('clone a repository into a newly created directory')
+ * .action((source, destination) => {
+ * console.log('clone command called');
+ * });
+ *
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
+ * program
+ * .command('start ', 'start named service')
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
+ *
+ * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...`
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
+ * @param {Object} [execOpts] - configuration options (for executable)
+ * @return {Command} returns new command for action handler, or `this` for executable command
+ * @api public
+ */
+
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
+ let desc = actionOptsOrExecDesc;
+ let opts = execOpts;
+ if (typeof desc === 'object' && desc !== null) {
+ opts = desc;
+ desc = null;
+ }
+ opts = opts || {};
+ const args = nameAndArgs.split(/ +/);
+ const cmd = this.createCommand(args.shift());
+
+ if (desc) {
+ cmd.description(desc);
+ cmd._executableHandler = true;
+ }
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
+
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
+ cmd._hasHelpOption = this._hasHelpOption;
+ cmd._helpFlags = this._helpFlags;
+ cmd._helpDescription = this._helpDescription;
+ cmd._helpShortFlag = this._helpShortFlag;
+ cmd._helpLongFlag = this._helpLongFlag;
+ cmd._helpCommandName = this._helpCommandName;
+ cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
+ cmd._helpCommandDescription = this._helpCommandDescription;
+ cmd._exitCallback = this._exitCallback;
+ cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
+ cmd._passCommandToAction = this._passCommandToAction;
+ cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
+
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
+ this.commands.push(cmd);
+ cmd._parseExpectedArgs(args);
+ cmd.parent = this;
+
+ if (desc) return this;
+ return cmd;
+ };
+
+ /**
+ * Factory routine to create a new unattached command.
+ *
+ * See .command() for creating an attached subcommand, which uses this routine to
+ * create the command. You can override createCommand to customise subcommands.
+ *
+ * @param {string} [name]
+ * @return {Command} new command
+ * @api public
+ */
+
+ createCommand(name) {
+ return new Command(name);
+ };
+
+ /**
+ * Add a prepared subcommand.
+ *
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
+ *
+ * @param {Command} cmd - new subcommand
+ * @param {Object} [opts] - configuration options
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ addCommand(cmd, opts) {
+ if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
+
+ // To keep things simple, block automatic name generation for deeply nested executables.
+ // Fail fast and detect when adding rather than later when parsing.
+ function checkExplicitNames(commandArray) {
+ commandArray.forEach((cmd) => {
+ if (cmd._executableHandler && !cmd._executableFile) {
+ throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
+ }
+ checkExplicitNames(cmd.commands);
+ });
+ }
+ checkExplicitNames(cmd.commands);
+
+ opts = opts || {};
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
+
+ this.commands.push(cmd);
+ cmd.parent = this;
+ return this;
+ };
+
+ /**
+ * Define argument syntax for the command.
+ *
+ * @api public
+ */
+
+ arguments(desc) {
+ return this._parseExpectedArgs(desc.split(/ +/));
+ };
+
+ /**
+ * Override default decision whether to add implicit help command.
+ *
+ * addHelpCommand() // force on
+ * addHelpCommand(false); // force off
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
+ *
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ addHelpCommand(enableOrNameAndArgs, description) {
+ if (enableOrNameAndArgs === false) {
+ this._hasImplicitHelpCommand = false;
+ } else {
+ this._hasImplicitHelpCommand = true;
+ if (typeof enableOrNameAndArgs === 'string') {
+ this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
+ }
+ this._helpCommandDescription = description || this._helpCommandDescription;
+ }
+ return this;
+ };
+
+ /**
+ * @return {boolean}
+ * @api private
+ */
+
+ _lazyHasImplicitHelpCommand() {
+ if (this._hasImplicitHelpCommand === undefined) {
+ this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');
+ }
+ return this._hasImplicitHelpCommand;
+ };
+
+ /**
+ * Parse expected `args`.
+ *
+ * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
+ *
+ * @param {Array} args
+ * @return {Command} `this` command for chaining
+ * @api private
+ */
+
+ _parseExpectedArgs(args) {
+ if (!args.length) return;
+ args.forEach((arg) => {
+ const argDetails = {
+ required: false,
+ name: '',
+ variadic: false
+ };
+
+ switch (arg[0]) {
+ case '<':
+ argDetails.required = true;
+ argDetails.name = arg.slice(1, -1);
+ break;
+ case '[':
+ argDetails.name = arg.slice(1, -1);
+ break;
+ }
+
+ if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
+ argDetails.variadic = true;
+ argDetails.name = argDetails.name.slice(0, -3);
+ }
+ if (argDetails.name) {
+ this._args.push(argDetails);
+ }
+ });
+ this._args.forEach((arg, i) => {
+ if (arg.variadic && i < this._args.length - 1) {
+ throw new Error(`only the last argument can be variadic '${arg.name}'`);
+ }
+ });
+ return this;
+ };
+
+ /**
+ * Register callback to use as replacement for calling process.exit.
+ *
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ exitOverride(fn) {
+ if (fn) {
+ this._exitCallback = fn;
+ } else {
+ this._exitCallback = (err) => {
+ if (err.code !== 'commander.executeSubCommandAsync') {
+ throw err;
+ }
+ };
+ }
+ return this;
+ };
+
+ /**
+ * Call process.exit, and _exitCallback if defined.
+ *
+ * @param {number} exitCode exit code for using with process.exit
+ * @param {string} code an id string representing the error
+ * @param {string} message human-readable description of the error
+ * @return never
+ * @api private
+ */
+
+ _exit(exitCode, code, message) {
+ if (this._exitCallback) {
+ this._exitCallback(new CommanderError(exitCode, code, message));
+ // Expecting this line is not reached.
+ }
+ process.exit(exitCode);
+ };
+
+ /**
+ * Register callback `fn` for the command.
+ *
+ * Examples:
+ *
+ * program
+ * .command('help')
+ * .description('display verbose help')
+ * .action(function() {
+ * // output help here
+ * });
+ *
+ * @param {Function} fn
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ action(fn) {
+ const listener = (args) => {
+ // The .action callback takes an extra parameter which is the command or options.
+ const expectedArgsCount = this._args.length;
+ const actionArgs = args.slice(0, expectedArgsCount);
+ if (this._passCommandToAction) {
+ actionArgs[expectedArgsCount] = this;
+ } else {
+ actionArgs[expectedArgsCount] = this.opts();
+ }
+ // Add the extra arguments so available too.
+ if (args.length > expectedArgsCount) {
+ actionArgs.push(args.slice(expectedArgsCount));
+ }
+
+ const actionResult = fn.apply(this, actionArgs);
+ // Remember result in case it is async. Assume parseAsync getting called on root.
+ let rootCommand = this;
+ while (rootCommand.parent) {
+ rootCommand = rootCommand.parent;
+ }
+ rootCommand._actionResults.push(actionResult);
+ };
+ this._actionHandler = listener;
+ return this;
+ };
+
+ /**
+ * Internal routine to check whether there is a clash storing option value with a Command property.
+ *
+ * @param {Option} option
+ * @api private
+ */
+
+ _checkForOptionNameClash(option) {
+ if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) {
+ // Storing options safely, or user has been explicit and up to them.
+ return;
+ }
+ // User may override help, and hard to tell if worth warning.
+ if (option.name() === 'help') {
+ return;
+ }
+
+ const commandProperty = this._getOptionValue(option.attributeName());
+ if (commandProperty === undefined) {
+ // no clash
+ return;
+ }
+
+ let foundClash = true;
+ if (option.negate) {
+ // It is ok if define foo before --no-foo.
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
+ foundClash = !this._findOption(positiveLongFlag);
+ } else if (option.long) {
+ const negativeLongFlag = option.long.replace(/^--/, '--no-');
+ foundClash = !this._findOption(negativeLongFlag);
+ }
+
+ if (foundClash) {
+ throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command
+- call storeOptionsAsProperties(false) to store option values safely,
+- or call storeOptionsAsProperties(true) to suppress this check,
+- or change option name
+
+Read more on https://git.io/JJc0W`);
+ }
+ };
+
+ /**
+ * Internal implementation shared by .option() and .requiredOption()
+ *
+ * @param {Object} config
+ * @param {string} flags
+ * @param {string} description
+ * @param {Function|*} [fn] - custom option processing function or default value
+ * @param {*} [defaultValue]
+ * @return {Command} `this` command for chaining
+ * @api private
+ */
+
+ _optionEx(config, flags, description, fn, defaultValue) {
+ const option = new Option(flags, description);
+ const oname = option.name();
+ const name = option.attributeName();
+ option.mandatory = !!config.mandatory;
+
+ this._checkForOptionNameClash(option);
+
+ // default as 3rd arg
+ if (typeof fn !== 'function') {
+ if (fn instanceof RegExp) {
+ // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.
+ // No longer documented in README, but still present for backwards compatibility.
+ const regex = fn;
+ fn = (val, def) => {
+ const m = regex.exec(val);
+ return m ? m[0] : def;
+ };
+ } else {
+ defaultValue = fn;
+ fn = null;
+ }
+ }
+
+ // preassign default value for --no-*, [optional], , or plain flag if boolean value
+ if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
+ // when --no-foo we make sure default is true, unless a --foo option is already defined
+ if (option.negate) {
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
+ defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true;
+ }
+ // preassign only if we have a default
+ if (defaultValue !== undefined) {
+ this._setOptionValue(name, defaultValue);
+ option.defaultValue = defaultValue;
+ }
+ }
+
+ // register the option
+ this.options.push(option);
+
+ // when it's passed assign the value
+ // and conditionally invoke the callback
+ this.on('option:' + oname, (val) => {
+ const oldValue = this._getOptionValue(name);
+
+ // custom processing
+ if (val !== null && fn) {
+ val = fn(val, oldValue === undefined ? defaultValue : oldValue);
+ } else if (val !== null && option.variadic) {
+ if (oldValue === defaultValue || !Array.isArray(oldValue)) {
+ val = [val];
+ } else {
+ val = oldValue.concat(val);
+ }
+ }
+
+ // unassigned or boolean value
+ if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {
+ // if no value, negate false, and we have a default, then use it!
+ if (val == null) {
+ this._setOptionValue(name, option.negate
+ ? false
+ : defaultValue || true);
+ } else {
+ this._setOptionValue(name, val);
+ }
+ } else if (val !== null) {
+ // reassign
+ this._setOptionValue(name, option.negate ? false : val);
+ }
+ });
+
+ return this;
+ };
+
+ /**
+ * Define option with `flags`, `description` and optional
+ * coercion `fn`.
+ *
+ * The `flags` string should contain both the short and long flags,
+ * separated by comma, a pipe or space. The following are all valid
+ * all will output this way when `--help` is used.
+ *
+ * "-p, --pepper"
+ * "-p|--pepper"
+ * "-p --pepper"
+ *
+ * Examples:
+ *
+ * // simple boolean defaulting to undefined
+ * program.option('-p, --pepper', 'add pepper');
+ *
+ * program.pepper
+ * // => undefined
+ *
+ * --pepper
+ * program.pepper
+ * // => true
+ *
+ * // simple boolean defaulting to true (unless non-negated option is also defined)
+ * program.option('-C, --no-cheese', 'remove cheese');
+ *
+ * program.cheese
+ * // => true
+ *
+ * --no-cheese
+ * program.cheese
+ * // => false
+ *
+ * // required argument
+ * program.option('-C, --chdir ', 'change the working directory');
+ *
+ * --chdir /tmp
+ * program.chdir
+ * // => "/tmp"
+ *
+ * // optional argument
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
+ *
+ * @param {string} flags
+ * @param {string} description
+ * @param {Function|*} [fn] - custom option processing function or default value
+ * @param {*} [defaultValue]
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ option(flags, description, fn, defaultValue) {
+ return this._optionEx({}, flags, description, fn, defaultValue);
+ };
+
+ /**
+ * Add a required option which must have a value after parsing. This usually means
+ * the option must be specified on the command line. (Otherwise the same as .option().)
+ *
+ * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
+ *
+ * @param {string} flags
+ * @param {string} description
+ * @param {Function|*} [fn] - custom option processing function or default value
+ * @param {*} [defaultValue]
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ requiredOption(flags, description, fn, defaultValue) {
+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
+ };
+
+ /**
+ * Alter parsing of short flags with optional values.
+ *
+ * Examples:
+ *
+ * // for `.option('-f,--flag [value]'):
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
+ *
+ * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag.
+ * @api public
+ */
+ combineFlagAndOptionalValue(arg) {
+ this._combineFlagAndOptionalValue = (arg === undefined) || arg;
+ return this;
+ };
+
+ /**
+ * Allow unknown options on the command line.
+ *
+ * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown
+ * for unknown options.
+ * @api public
+ */
+ allowUnknownOption(arg) {
+ this._allowUnknownOption = (arg === undefined) || arg;
+ return this;
+ };
+
+ /**
+ * Whether to store option values as properties on command object,
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
+ *
+ * @param {boolean} value
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ storeOptionsAsProperties(value) {
+ this._storeOptionsAsPropertiesCalled = true;
+ this._storeOptionsAsProperties = (value === undefined) || value;
+ if (this.options.length) {
+ throw new Error('call .storeOptionsAsProperties() before adding options');
+ }
+ return this;
+ };
+
+ /**
+ * Whether to pass command to action handler,
+ * or just the options (specify false).
+ *
+ * @param {boolean} value
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ passCommandToAction(value) {
+ this._passCommandToAction = (value === undefined) || value;
+ return this;
+ };
+
+ /**
+ * Store option value
+ *
+ * @param {string} key
+ * @param {Object} value
+ * @api private
+ */
+
+ _setOptionValue(key, value) {
+ if (this._storeOptionsAsProperties) {
+ this[key] = value;
+ } else {
+ this._optionValues[key] = value;
+ }
+ };
+
+ /**
+ * Retrieve option value
+ *
+ * @param {string} key
+ * @return {Object} value
+ * @api private
+ */
+
+ _getOptionValue(key) {
+ if (this._storeOptionsAsProperties) {
+ return this[key];
+ }
+ return this._optionValues[key];
+ };
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * Examples:
+ *
+ * program.parse(process.argv);
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ *
+ * @param {string[]} [argv] - optional, defaults to process.argv
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ parse(argv, parseOptions) {
+ if (argv !== undefined && !Array.isArray(argv)) {
+ throw new Error('first parameter to parse must be array or undefined');
+ }
+ parseOptions = parseOptions || {};
+
+ // Default to using process.argv
+ if (argv === undefined) {
+ argv = process.argv;
+ // @ts-ignore
+ if (process.versions && process.versions.electron) {
+ parseOptions.from = 'electron';
+ }
+ }
+ this.rawArgs = argv.slice();
+
+ // make it a little easier for callers by supporting various argv conventions
+ let userArgs;
+ switch (parseOptions.from) {
+ case undefined:
+ case 'node':
+ this._scriptPath = argv[1];
+ userArgs = argv.slice(2);
+ break;
+ case 'electron':
+ // @ts-ignore
+ if (process.defaultApp) {
+ this._scriptPath = argv[1];
+ userArgs = argv.slice(2);
+ } else {
+ userArgs = argv.slice(1);
+ }
+ break;
+ case 'user':
+ userArgs = argv.slice(0);
+ break;
+ default:
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
+ }
+ if (!this._scriptPath && process.mainModule) {
+ this._scriptPath = process.mainModule.filename;
+ }
+
+ // Guess name, used in usage in help.
+ this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
+
+ // Let's go!
+ this._parseCommand([], userArgs);
+
+ return this;
+ };
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * Examples:
+ *
+ * program.parseAsync(process.argv);
+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ *
+ * @param {string[]} [argv]
+ * @param {Object} [parseOptions]
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
+ * @return {Promise}
+ * @api public
+ */
+
+ parseAsync(argv, parseOptions) {
+ this.parse(argv, parseOptions);
+ return Promise.all(this._actionResults).then(() => this);
+ };
+
+ /**
+ * Execute a sub-command executable.
+ *
+ * @api private
+ */
+
+ _executeSubCommand(subcommand, args) {
+ args = args.slice();
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs'];
+
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
+ this._checkForMissingMandatoryOptions();
+
+ // Want the entry script as the reference for command name and directory for searching for other files.
+ let scriptPath = this._scriptPath;
+ // Fallback in case not set, due to how Command created or called.
+ if (!scriptPath && process.mainModule) {
+ scriptPath = process.mainModule.filename;
+ }
+
+ let baseDir;
+ try {
+ const resolvedLink = fs.realpathSync(scriptPath);
+ baseDir = path.dirname(resolvedLink);
+ } catch (e) {
+ baseDir = '.'; // dummy, probably not going to find executable!
+ }
+
+ // name of the subcommand, like `pm-install`
+ let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
+ if (subcommand._executableFile) {
+ bin = subcommand._executableFile;
+ }
+
+ const localBin = path.join(baseDir, bin);
+ if (fs.existsSync(localBin)) {
+ // prefer local `./` to bin in the $PATH
+ bin = localBin;
+ } else {
+ // Look for source files.
+ sourceExt.forEach((ext) => {
+ if (fs.existsSync(`${localBin}${ext}`)) {
+ bin = `${localBin}${ext}`;
+ }
+ });
+ }
+ launchWithNode = sourceExt.includes(path.extname(bin));
+
+ let proc;
+ if (process.platform !== 'win32') {
+ if (launchWithNode) {
+ args.unshift(bin);
+ // add executable arguments to spawn
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
+
+ proc = spawn(process.argv[0], args, { stdio: 'inherit' });
+ } else {
+ proc = spawn(bin, args, { stdio: 'inherit' });
+ }
+ } else {
+ args.unshift(bin);
+ // add executable arguments to spawn
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
+ proc = spawn(process.execPath, args, { stdio: 'inherit' });
+ }
+
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
+ signals.forEach((signal) => {
+ // @ts-ignore
+ process.on(signal, () => {
+ if (proc.killed === false && proc.exitCode === null) {
+ proc.kill(signal);
+ }
+ });
+ });
+
+ // By default terminate process when spawned process terminates.
+ // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
+ const exitCallback = this._exitCallback;
+ if (!exitCallback) {
+ proc.on('close', process.exit.bind(process));
+ } else {
+ proc.on('close', () => {
+ exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
+ });
+ }
+ proc.on('error', (err) => {
+ // @ts-ignore
+ if (err.code === 'ENOENT') {
+ const executableMissing = `'${bin}' does not exist
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
+ throw new Error(executableMissing);
+ // @ts-ignore
+ } else if (err.code === 'EACCES') {
+ throw new Error(`'${bin}' not executable`);
+ }
+ if (!exitCallback) {
+ process.exit(1);
+ } else {
+ const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
+ wrappedError.nestedError = err;
+ exitCallback(wrappedError);
+ }
+ });
+
+ // Store the reference to the child process
+ this.runningCommand = proc;
+ };
+
+ /**
+ * @api private
+ */
+ _dispatchSubcommand(commandName, operands, unknown) {
+ const subCommand = this._findCommand(commandName);
+ if (!subCommand) this._helpAndError();
+
+ if (subCommand._executableHandler) {
+ this._executeSubCommand(subCommand, operands.concat(unknown));
+ } else {
+ subCommand._parseCommand(operands, unknown);
+ }
+ };
+
+ /**
+ * Process arguments in context of this command.
+ *
+ * @api private
+ */
+
+ _parseCommand(operands, unknown) {
+ const parsed = this.parseOptions(unknown);
+ operands = operands.concat(parsed.operands);
+ unknown = parsed.unknown;
+ this.args = operands.concat(unknown);
+
+ if (operands && this._findCommand(operands[0])) {
+ this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
+ } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
+ if (operands.length === 1) {
+ this.help();
+ } else {
+ this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
+ }
+ } else if (this._defaultCommandName) {
+ outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
+ this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
+ } else {
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
+ // probably missing subcommand and no handler, user needs help
+ this._helpAndError();
+ }
+
+ outputHelpIfRequested(this, parsed.unknown);
+ this._checkForMissingMandatoryOptions();
+ if (parsed.unknown.length > 0) {
+ this.unknownOption(parsed.unknown[0]);
+ }
+
+ if (this._actionHandler) {
+ const args = this.args.slice();
+ this._args.forEach((arg, i) => {
+ if (arg.required && args[i] == null) {
+ this.missingArgument(arg.name);
+ } else if (arg.variadic) {
+ args[i] = args.splice(i);
+ }
+ });
+
+ this._actionHandler(args);
+ this.emit('command:' + this.name(), operands, unknown);
+ } else if (operands.length) {
+ if (this._findCommand('*')) {
+ this._dispatchSubcommand('*', operands, unknown);
+ } else if (this.listenerCount('command:*')) {
+ this.emit('command:*', operands, unknown);
+ } else if (this.commands.length) {
+ this.unknownCommand();
+ }
+ } else if (this.commands.length) {
+ // This command has subcommands and nothing hooked up at this level, so display help.
+ this._helpAndError();
+ } else ;
+ }
+ };
+
+ /**
+ * Find matching command.
+ *
+ * @api private
+ */
+ _findCommand(name) {
+ if (!name) return undefined;
+ return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
+ };
+
+ /**
+ * Return an option matching `arg` if any.
+ *
+ * @param {string} arg
+ * @return {Option}
+ * @api private
+ */
+
+ _findOption(arg) {
+ return this.options.find(option => option.is(arg));
+ };
+
+ /**
+ * Display an error message if a mandatory option does not have a value.
+ * Lazy calling after checking for help flags from leaf subcommand.
+ *
+ * @api private
+ */
+
+ _checkForMissingMandatoryOptions() {
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
+ for (let cmd = this; cmd; cmd = cmd.parent) {
+ cmd.options.forEach((anOption) => {
+ if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
+ cmd.missingMandatoryOptionValue(anOption);
+ }
+ });
+ }
+ };
+
+ /**
+ * Parse options from `argv` removing known options,
+ * and return argv split into operands and unknown arguments.
+ *
+ * Examples:
+ *
+ * argv => operands, unknown
+ * --known kkk op => [op], []
+ * op --known kkk => [op], []
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
+ *
+ * @param {String[]} argv
+ * @return {{operands: String[], unknown: String[]}}
+ * @api public
+ */
+
+ parseOptions(argv) {
+ const operands = []; // operands, not options or values
+ const unknown = []; // first unknown option and remaining unknown args
+ let dest = operands;
+ const args = argv.slice();
+
+ function maybeOption(arg) {
+ return arg.length > 1 && arg[0] === '-';
+ }
+
+ // parse options
+ let activeVariadicOption = null;
+ while (args.length) {
+ const arg = args.shift();
+
+ // literal
+ if (arg === '--') {
+ if (dest === unknown) dest.push(arg);
+ dest.push(...args);
+ break;
+ }
+
+ if (activeVariadicOption && !maybeOption(arg)) {
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
+ continue;
+ }
+ activeVariadicOption = null;
+
+ if (maybeOption(arg)) {
+ const option = this._findOption(arg);
+ // recognised option, call listener to assign value with possible custom processing
+ if (option) {
+ if (option.required) {
+ const value = args.shift();
+ if (value === undefined) this.optionMissingArgument(option);
+ this.emit(`option:${option.name()}`, value);
+ } else if (option.optional) {
+ let value = null;
+ // historical behaviour is optional value is following arg unless an option
+ if (args.length > 0 && !maybeOption(args[0])) {
+ value = args.shift();
+ }
+ this.emit(`option:${option.name()}`, value);
+ } else { // boolean flag
+ this.emit(`option:${option.name()}`);
+ }
+ activeVariadicOption = option.variadic ? option : null;
+ continue;
+ }
+ }
+
+ // Look for combo options following single dash, eat first one if known.
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
+ const option = this._findOption(`-${arg[1]}`);
+ if (option) {
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
+ // option with value following in same argument
+ this.emit(`option:${option.name()}`, arg.slice(2));
+ } else {
+ // boolean option, emit and put back remainder of arg for further processing
+ this.emit(`option:${option.name()}`);
+ args.unshift(`-${arg.slice(2)}`);
+ }
+ continue;
+ }
+ }
+
+ // Look for known long flag with value, like --foo=bar
+ if (/^--[^=]+=/.test(arg)) {
+ const index = arg.indexOf('=');
+ const option = this._findOption(arg.slice(0, index));
+ if (option && (option.required || option.optional)) {
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
+ continue;
+ }
+ }
+
+ // looks like an option but unknown, unknowns from here
+ if (arg.length > 1 && arg[0] === '-') {
+ dest = unknown;
+ }
+
+ // add arg
+ dest.push(arg);
+ }
+
+ return { operands, unknown };
+ };
+
+ /**
+ * Return an object containing options as key-value pairs
+ *
+ * @return {Object}
+ * @api public
+ */
+ opts() {
+ if (this._storeOptionsAsProperties) {
+ // Preserve original behaviour so backwards compatible when still using properties
+ const result = {};
+ const len = this.options.length;
+
+ for (let i = 0; i < len; i++) {
+ const key = this.options[i].attributeName();
+ result[key] = key === this._versionOptionName ? this._version : this[key];
+ }
+ return result;
+ }
+
+ return this._optionValues;
+ };
+
+ /**
+ * Argument `name` is missing.
+ *
+ * @param {string} name
+ * @api private
+ */
+
+ missingArgument(name) {
+ const message = `error: missing required argument '${name}'`;
+ console.error(message);
+ this._exit(1, 'commander.missingArgument', message);
+ };
+
+ /**
+ * `Option` is missing an argument, but received `flag` or nothing.
+ *
+ * @param {Option} option
+ * @param {string} [flag]
+ * @api private
+ */
+
+ optionMissingArgument(option, flag) {
+ let message;
+ if (flag) {
+ message = `error: option '${option.flags}' argument missing, got '${flag}'`;
+ } else {
+ message = `error: option '${option.flags}' argument missing`;
+ }
+ console.error(message);
+ this._exit(1, 'commander.optionMissingArgument', message);
+ };
+
+ /**
+ * `Option` does not have a value, and is a mandatory option.
+ *
+ * @param {Option} option
+ * @api private
+ */
+
+ missingMandatoryOptionValue(option) {
+ const message = `error: required option '${option.flags}' not specified`;
+ console.error(message);
+ this._exit(1, 'commander.missingMandatoryOptionValue', message);
+ };
+
+ /**
+ * Unknown option `flag`.
+ *
+ * @param {string} flag
+ * @api private
+ */
+
+ unknownOption(flag) {
+ if (this._allowUnknownOption) return;
+ const message = `error: unknown option '${flag}'`;
+ console.error(message);
+ this._exit(1, 'commander.unknownOption', message);
+ };
+
+ /**
+ * Unknown command.
+ *
+ * @api private
+ */
+
+ unknownCommand() {
+ const partCommands = [this.name()];
+ for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
+ partCommands.unshift(parentCmd.name());
+ }
+ const fullCommand = partCommands.join(' ');
+ const message = `error: unknown command '${this.args[0]}'.` +
+ (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');
+ console.error(message);
+ this._exit(1, 'commander.unknownCommand', message);
+ };
+
+ /**
+ * Set the program version to `str`.
+ *
+ * This method auto-registers the "-V, --version" flag
+ * which will print the version number when passed.
+ *
+ * You can optionally supply the flags and description to override the defaults.
+ *
+ * @param {string} str
+ * @param {string} [flags]
+ * @param {string} [description]
+ * @return {this | string} `this` command for chaining, or version string if no arguments
+ * @api public
+ */
+
+ version(str, flags, description) {
+ if (str === undefined) return this._version;
+ this._version = str;
+ flags = flags || '-V, --version';
+ description = description || 'output the version number';
+ const versionOption = new Option(flags, description);
+ this._versionOptionName = versionOption.attributeName();
+ this.options.push(versionOption);
+ this.on('option:' + versionOption.name(), () => {
+ process.stdout.write(str + '\n');
+ this._exit(0, 'commander.version', str);
+ });
+ return this;
+ };
+
+ /**
+ * Set the description to `str`.
+ *
+ * @param {string} str
+ * @param {Object} [argsDescription]
+ * @return {string|Command}
+ * @api public
+ */
+
+ description(str, argsDescription) {
+ if (str === undefined && argsDescription === undefined) return this._description;
+ this._description = str;
+ this._argsDescription = argsDescription;
+ return this;
+ };
+
+ /**
+ * Set an alias for the command.
+ *
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
+ *
+ * @param {string} [alias]
+ * @return {string|Command}
+ * @api public
+ */
+
+ alias(alias) {
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
+
+ let command = this;
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
+ // assume adding alias for last added executable subcommand, rather than this
+ command = this.commands[this.commands.length - 1];
+ }
+
+ if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
+
+ command._aliases.push(alias);
+ return this;
+ };
+
+ /**
+ * Set aliases for the command.
+ *
+ * Only the first alias is shown in the auto-generated help.
+ *
+ * @param {string[]} [aliases]
+ * @return {string[]|Command}
+ * @api public
+ */
+
+ aliases(aliases) {
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
+ if (aliases === undefined) return this._aliases;
+
+ aliases.forEach((alias) => this.alias(alias));
+ return this;
+ };
+
+ /**
+ * Set / get the command usage `str`.
+ *
+ * @param {string} [str]
+ * @return {String|Command}
+ * @api public
+ */
+
+ usage(str) {
+ if (str === undefined) {
+ if (this._usage) return this._usage;
+
+ const args = this._args.map((arg) => {
+ return humanReadableArgName(arg);
+ });
+ return [].concat(
+ (this.options.length || this._hasHelpOption ? '[options]' : []),
+ (this.commands.length ? '[command]' : []),
+ (this._args.length ? args : [])
+ ).join(' ');
+ }
+
+ this._usage = str;
+ return this;
+ };
+
+ /**
+ * Get or set the name of the command
+ *
+ * @param {string} [str]
+ * @return {String|Command}
+ * @api public
+ */
+
+ name(str) {
+ if (str === undefined) return this._name;
+ this._name = str;
+ return this;
+ };
+
+ /**
+ * Return prepared commands.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+ prepareCommands() {
+ const commandDetails = this.commands.filter((cmd) => {
+ return !cmd._hidden;
+ }).map((cmd) => {
+ const args = cmd._args.map((arg) => {
+ return humanReadableArgName(arg);
+ }).join(' ');
+
+ return [
+ cmd._name +
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
+ (cmd.options.length ? ' [options]' : '') +
+ (args ? ' ' + args : ''),
+ cmd._description
+ ];
+ });
+
+ if (this._lazyHasImplicitHelpCommand()) {
+ commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);
+ }
+ return commandDetails;
+ };
+
+ /**
+ * Return the largest command length.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ largestCommandLength() {
+ const commands = this.prepareCommands();
+ return commands.reduce((max, command) => {
+ return Math.max(max, command[0].length);
+ }, 0);
+ };
+
+ /**
+ * Return the largest option length.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ largestOptionLength() {
+ const options = [].slice.call(this.options);
+ options.push({
+ flags: this._helpFlags
+ });
+
+ return options.reduce((max, option) => {
+ return Math.max(max, option.flags.length);
+ }, 0);
+ };
+
+ /**
+ * Return the largest arg length.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ largestArgLength() {
+ return this._args.reduce((max, arg) => {
+ return Math.max(max, arg.name.length);
+ }, 0);
+ };
+
+ /**
+ * Return the pad width.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ padWidth() {
+ let width = this.largestOptionLength();
+ if (this._argsDescription && this._args.length) {
+ if (this.largestArgLength() > width) {
+ width = this.largestArgLength();
+ }
+ }
+
+ if (this.commands && this.commands.length) {
+ if (this.largestCommandLength() > width) {
+ width = this.largestCommandLength();
+ }
+ }
+
+ return width;
+ };
+
+ /**
+ * Return help for options.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ optionHelp() {
+ const width = this.padWidth();
+ const columns = process.stdout.columns || 80;
+ const descriptionWidth = columns - width - 4;
+ function padOptionDetails(flags, description) {
+ return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2);
+ }
+ // Explicit options (including version)
+ const help = this.options.map((option) => {
+ const fullDesc = option.description +
+ ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
+ return padOptionDetails(option.flags, fullDesc);
+ });
+
+ // Implicit help
+ const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag);
+ const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag);
+ if (showShortHelpFlag || showLongHelpFlag) {
+ let helpFlags = this._helpFlags;
+ if (!showShortHelpFlag) {
+ helpFlags = this._helpLongFlag;
+ } else if (!showLongHelpFlag) {
+ helpFlags = this._helpShortFlag;
+ }
+ help.push(padOptionDetails(helpFlags, this._helpDescription));
+ }
+
+ return help.join('\n');
+ };
+
+ /**
+ * Return command help documentation.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ commandHelp() {
+ if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';
+
+ const commands = this.prepareCommands();
+ const width = this.padWidth();
+
+ const columns = process.stdout.columns || 80;
+ const descriptionWidth = columns - width - 4;
+
+ return [
+ 'Commands:',
+ commands.map((cmd) => {
+ const desc = cmd[1] ? ' ' + cmd[1] : '';
+ return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);
+ }).join('\n').replace(/^/gm, ' '),
+ ''
+ ].join('\n');
+ };
+
+ /**
+ * Return program help documentation.
+ *
+ * @return {string}
+ * @api public
+ */
+
+ helpInformation() {
+ let desc = [];
+ if (this._description) {
+ desc = [
+ this._description,
+ ''
+ ];
+
+ const argsDescription = this._argsDescription;
+ if (argsDescription && this._args.length) {
+ const width = this.padWidth();
+ const columns = process.stdout.columns || 80;
+ const descriptionWidth = columns - width - 5;
+ desc.push('Arguments:');
+ this._args.forEach((arg) => {
+ desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4));
+ });
+ desc.push('');
+ }
+ }
+
+ let cmdName = this._name;
+ if (this._aliases[0]) {
+ cmdName = cmdName + '|' + this._aliases[0];
+ }
+ let parentCmdNames = '';
+ for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
+ parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
+ }
+ const usage = [
+ 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),
+ ''
+ ];
+
+ let cmds = [];
+ const commandHelp = this.commandHelp();
+ if (commandHelp) cmds = [commandHelp];
+
+ let options = [];
+ if (this._hasHelpOption || this.options.length > 0) {
+ options = [
+ 'Options:',
+ '' + this.optionHelp().replace(/^/gm, ' '),
+ ''
+ ];
+ }
+
+ return usage
+ .concat(desc)
+ .concat(options)
+ .concat(cmds)
+ .join('\n');
+ };
+
+ /**
+ * Output help information for this command.
+ *
+ * When listener(s) are available for the helpLongFlag
+ * those callbacks are invoked.
+ *
+ * @api public
+ */
+
+ outputHelp(cb) {
+ if (!cb) {
+ cb = (passthru) => {
+ return passthru;
+ };
+ }
+ const cbOutput = cb(this.helpInformation());
+ if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {
+ throw new Error('outputHelp callback must return a string or a Buffer');
+ }
+ process.stdout.write(cbOutput);
+ this.emit(this._helpLongFlag);
+ };
+
+ /**
+ * You can pass in flags and a description to override the help
+ * flags and help description for your command. Pass in false to
+ * disable the built-in help option.
+ *
+ * @param {string | boolean} [flags]
+ * @param {string} [description]
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ helpOption(flags, description) {
+ if (typeof flags === 'boolean') {
+ this._hasHelpOption = flags;
+ return this;
+ }
+ this._helpFlags = flags || this._helpFlags;
+ this._helpDescription = description || this._helpDescription;
+
+ const helpFlags = _parseOptionFlags(this._helpFlags);
+ this._helpShortFlag = helpFlags.shortFlag;
+ this._helpLongFlag = helpFlags.longFlag;
+
+ return this;
+ };
+
+ /**
+ * Output help information and exit.
+ *
+ * @param {Function} [cb]
+ * @api public
+ */
+
+ help(cb) {
+ this.outputHelp(cb);
+ // exitCode: preserving original behaviour which was calling process.exit()
+ // message: do not have all displayed text available so only passing placeholder.
+ this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');
+ };
+
+ /**
+ * Output help information and exit. Display for error situations.
+ *
+ * @api private
+ */
+
+ _helpAndError() {
+ this.outputHelp();
+ // message: do not have all displayed text available so only passing placeholder.
+ this._exit(1, 'commander.help', '(outputHelp)');
+ };
+ }
+ /**
+ * Expose the root command.
+ */
+
+ exports = module.exports = new Command();
+ exports.program = exports; // More explicit access to global command.
+
+ /**
+ * Expose classes
+ */
+
+ exports.Command = Command;
+ exports.Option = Option;
+ exports.CommanderError = CommanderError;
+
+ /**
+ * Camel-case the given `flag`
+ *
+ * @param {string} flag
+ * @return {string}
+ * @api private
+ */
+
+ function camelcase(flag) {
+ return flag.split('-').reduce((str, word) => {
+ return str + word[0].toUpperCase() + word.slice(1);
+ });
+ }
+
+ /**
+ * Pad `str` to `width`.
+ *
+ * @param {string} str
+ * @param {number} width
+ * @return {string}
+ * @api private
+ */
+
+ function pad(str, width) {
+ const len = Math.max(0, width - str.length);
+ return str + Array(len + 1).join(' ');
+ }
+
+ /**
+ * Wraps the given string with line breaks at the specified width while breaking
+ * words and indenting every but the first line on the left.
+ *
+ * @param {string} str
+ * @param {number} width
+ * @param {number} indent
+ * @return {string}
+ * @api private
+ */
+ function wrap(str, width, indent) {
+ const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
+ const lines = str.match(regex) || [];
+ return lines.map((line, i) => {
+ if (line.slice(-1) === '\n') {
+ line = line.slice(0, line.length - 1);
+ }
+ return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();
+ }).join('\n');
+ }
+
+ /**
+ * Optionally wrap the given str to a max width of width characters per line
+ * while indenting with indent spaces. Do not wrap if insufficient width or
+ * string is manually formatted.
+ *
+ * @param {string} str
+ * @param {number} width
+ * @param {number} indent
+ * @return {string}
+ * @api private
+ */
+ function optionalWrap(str, width, indent) {
+ // Detect manually wrapped and indented strings by searching for line breaks
+ // followed by multiple spaces/tabs.
+ if (str.match(/[\n]\s+/)) return str;
+ // Do not wrap to narrow columns (or can end up with a word per line).
+ const minWidth = 40;
+ if (width < minWidth) return str;
+
+ return wrap(str, width, indent);
+ }
+
+ /**
+ * Output help information if help flags specified
+ *
+ * @param {Command} cmd - command to output help for
+ * @param {Array} args - array of options to search for help flags
+ * @api private
+ */
+
+ function outputHelpIfRequested(cmd, args) {
+ const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
+ if (helpOption) {
+ cmd.outputHelp();
+ // (Do not have all displayed text available so only passing placeholder.)
+ cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
+ }
+ }
+
+ /**
+ * Takes an argument and returns its human readable equivalent for help usage.
+ *
+ * @param {Object} arg
+ * @return {string}
+ * @api private
+ */
+
+ function humanReadableArgName(arg) {
+ const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
+
+ return arg.required
+ ? '<' + nameOutput + '>'
+ : '[' + nameOutput + ']';
+ }
+
+ /**
+ * Parse the short and long flag out of something like '-m,--mixed '
+ *
+ * @api private
+ */
+
+ function _parseOptionFlags(flags) {
+ let shortFlag;
+ let longFlag;
+ // Use original very loose parsing to maintain backwards compatibility for now,
+ // which allowed for example unintended `-sw, --short-word` [sic].
+ const flagParts = flags.split(/[ |,]+/);
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
+ longFlag = flagParts.shift();
+ // Add support for lone short flag without significantly changing parsing!
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
+ shortFlag = longFlag;
+ longFlag = undefined;
+ }
+ return { shortFlag, longFlag };
+ }
+
+ /**
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
+ *
+ * @param {string[]} args - array of arguments from node.execArgv
+ * @returns {string[]}
+ * @api private
+ */
+
+ function incrementNodeInspectorPort(args) {
+ // Testing for these options:
+ // --inspect[=[host:]port]
+ // --inspect-brk[=[host:]port]
+ // --inspect-port=[host:]port
+ return args.map((arg) => {
+ if (!arg.startsWith('--inspect')) {
+ return arg;
+ }
+ let debugOption;
+ let debugHost = '127.0.0.1';
+ let debugPort = '9229';
+ let match;
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
+ // e.g. --inspect
+ debugOption = match[1];
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
+ debugOption = match[1];
+ if (/^\d+$/.test(match[3])) {
+ // e.g. --inspect=1234
+ debugPort = match[3];
+ } else {
+ // e.g. --inspect=localhost
+ debugHost = match[3];
+ }
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
+ // e.g. --inspect=localhost:1234
+ debugOption = match[1];
+ debugHost = match[3];
+ debugPort = match[4];
+ }
+
+ if (debugOption && debugPort !== '0') {
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
+ }
+ return arg;
+ });
+ }
+} (commander, commanderExports));
+
+var distNode = {};
+
+var isBase64Exports = {};
+var isBase64$1 = {
+ get exports(){ return isBase64Exports; },
+ set exports(v){ isBase64Exports = v; },
+};
+
+(function (module, exports) {
+(function(root) {
+
+ function isBase64(v, opts) {
+ if (v instanceof Boolean || typeof v === 'boolean') {
+ return false
+ }
+
+ if (!(opts instanceof Object)) {
+ opts = {};
+ }
+
+ if (opts.allowEmpty === false && v === '') {
+ return false
+ }
+
+ var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?';
+ var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)';
+
+ if (opts.mimeRequired === true) {
+ regex = mimeRegex + regex;
+ } else if (opts.allowMime === true) {
+ regex = mimeRegex + '?' + regex;
+ }
+
+ if (opts.paddingRequired === false) {
+ regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?';
+ }
+
+ return (new RegExp('^' + regex + '$', 'gi')).test(v)
+ }
+
+ {
+ if (module.exports) {
+ exports = module.exports = isBase64;
+ }
+ exports.isBase64 = isBase64;
+ }
+ })();
+} (isBase64$1, isBase64Exports));
+
+Object.defineProperty(distNode, '__esModule', { value: true });
+
+function _interopDefault$1 (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var path$7 = require$$0$c;
+var fs$7 = require$$0$e;
+var isBase64 = _interopDefault$1(isBase64Exports);
+
+const VERSION = "0.0.0-development";
+
+const begin = "-----BEGIN RSA PRIVATE KEY-----";
+const end$1 = "-----END RSA PRIVATE KEY-----";
+function getPrivateKey(options = {}) {
+ const env = options.env || process.env;
+ const cwd = options.cwd || process.cwd();
+
+ if (options.filepath) {
+ return fs$7.readFileSync(path$7.resolve(cwd, options.filepath), "utf-8");
+ }
+
+ if (env.PRIVATE_KEY) {
+ let privateKey = env.PRIVATE_KEY;
+
+ if (isBase64(privateKey)) {
+ // Decode base64-encoded certificate
+ privateKey = Buffer.from(privateKey, "base64").toString();
+ }
+
+ if (privateKey.includes(begin) && privateKey.includes(end$1)) {
+ // newlines are escaped
+ if (privateKey.indexOf("\\n") !== -1) {
+ privateKey = privateKey.replace(/\\n/g, "\n");
+ } // newlines are missing
+
+
+ if (privateKey.indexOf("\n") === -1) {
+ privateKey = addNewlines(privateKey);
+ }
+
+ return privateKey;
+ }
+
+ throw new Error(`[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.`);
+ }
+
+ if (env.PRIVATE_KEY_PATH) {
+ const filepath = path$7.resolve(cwd, env.PRIVATE_KEY_PATH);
+
+ if (fs$7.existsSync(filepath)) {
+ return fs$7.readFileSync(filepath, "utf-8");
+ } else {
+ throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`);
+ }
+ }
+
+ const pemFiles = fs$7.readdirSync(cwd).filter(path => path.endsWith(".pem"));
+
+ if (pemFiles.length > 1) {
+ const paths = pemFiles.join(", ");
+ throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`);
+ } else if (pemFiles[0]) {
+ return getPrivateKey({
+ filepath: pemFiles[0],
+ cwd
+ });
+ }
+
+ return null;
+}
+
+function addNewlines(privateKey) {
+ const middleLength = privateKey.length - begin.length - end$1.length - 2;
+ const middle = privateKey.substr(begin.length + 1, middleLength);
+ return `${begin}\n${middle.trim().replace(/\s+/g, "\n")}\n${end$1}`;
+}
+
+getPrivateKey.VERSION = VERSION;
+
+distNode.getPrivateKey = getPrivateKey;
+
+var __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(readCliOptions$1, "__esModule", { value: true });
+readCliOptions$1.readCliOptions = void 0;
+const commander_1 = __importDefault$1(commanderExports);
+const get_private_key_1$2 = distNode;
+function readCliOptions(argv) {
+ commander_1.default
+ .usage("[options] ")
+ .option("-p, --port ", "Port to start the server on", String(process.env.PORT || 3000))
+ .option("-H --host ", "Host to start the server on", process.env.HOST)
+ .option("-W, --webhook-proxy ", "URL of the webhook proxy service.`", process.env.WEBHOOK_PROXY_URL)
+ .option("-w, --webhook-path ", "URL path which receives webhooks. Ex: `/webhook`", process.env.WEBHOOK_PATH)
+ .option("-a, --app ", "ID of the GitHub App", process.env.APP_ID)
+ .option("-s, --secret ", "Webhook secret of the GitHub App", process.env.WEBHOOK_SECRET)
+ .option("-P, --private-key ", "Path to private key file (.pem) for the GitHub App", process.env.PRIVATE_KEY_PATH)
+ .option("-L, --log-level ", 'One of: "trace" | "debug" | "info" | "warn" | "error" | "fatal"', process.env.LOG_LEVEL || "info")
+ .option("--log-format ", 'One of: "pretty", "json"', process.env.LOG_FORMAT)
+ .option("--log-level-in-string", "Set to log levels (trace, debug, info, ...) as words instead of numbers (10, 20, 30, ...)", process.env.LOG_LEVEL_IN_STRING === "true")
+ .option("--sentry-dsn ", 'Set to your Sentry DSN, e.g. "https://1234abcd@sentry.io/12345"', process.env.SENTRY_DSN)
+ .option("--redis-url ", 'Set to a "redis://" url in order to enable cluster support for request throttling. Example: "redis://:secret@redis-123.redislabs.com:12345/0"', process.env.REDIS_URL)
+ .option("--base-url ", 'GitHub API base URL. If you use GitHub Enterprise Server, and your hostname is "https://github.acme-inc.com", then the root URL is "https://github.acme-inc.com/api/v3"', process.env.GHE_HOST
+ ? `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3`
+ : "https://api.github.com")
+ .parse(argv);
+ const { app: appId, privateKey: privateKeyPath, redisUrl, ...options } = commander_1.default;
+ return {
+ privateKey: (0, get_private_key_1$2.getPrivateKey)({ filepath: privateKeyPath }) || undefined,
+ appId,
+ redisConfig: redisUrl,
+ ...options,
+ };
+}
+readCliOptions$1.readCliOptions = readCliOptions;
+
+var readEnvOptions$1 = {};
+
+Object.defineProperty(readEnvOptions$1, "__esModule", { value: true });
+readEnvOptions$1.readEnvOptions = void 0;
+const get_private_key_1$1 = distNode;
+function readEnvOptions(env = process.env) {
+ const privateKey = (0, get_private_key_1$1.getPrivateKey)({ env });
+ const logFormat = env.LOG_FORMAT || (env.NODE_ENV === "production" ? "json" : "pretty");
+ return {
+ args: [],
+ privateKey: (privateKey && privateKey.toString()) || undefined,
+ appId: Number(env.APP_ID),
+ port: Number(env.PORT) || 3000,
+ host: env.HOST,
+ secret: env.WEBHOOK_SECRET,
+ webhookPath: env.WEBHOOK_PATH,
+ webhookProxy: env.WEBHOOK_PROXY_URL,
+ logLevel: env.LOG_LEVEL,
+ logFormat: logFormat,
+ logLevelInString: env.LOG_LEVEL_IN_STRING === "true",
+ logMessageKey: env.LOG_MESSAGE_KEY,
+ sentryDsn: env.SENTRY_DSN,
+ redisConfig: env.REDIS_URL,
+ baseUrl: env.GHE_HOST
+ ? `${env.GHE_PROTOCOL || "https"}://${env.GHE_HOST}/api/v3`
+ : "https://api.github.com",
+ };
+}
+readEnvOptions$1.readEnvOptions = readEnvOptions;
+
+var _default = {};
+
+var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(_default, "__esModule", { value: true });
+_default.defaultApp = void 0;
+const path_1 = __importDefault(require$$0$c);
+function defaultApp(app, { getRouter }) {
+ if (!getRouter) {
+ throw new Error("getRouter() is required for defaultApp");
+ }
+ const router = getRouter();
+ router.get("/probot", (req, res) => {
+ let pkg;
+ try {
+ pkg = commonjsRequire(path_1.default.join(process.cwd(), "package.json"));
+ }
+ catch (e) {
+ pkg = {};
+ }
+ res.render("probot.handlebars", pkg);
+ });
+ router.get("/", (req, res, next) => res.redirect("/probot"));
+}
+_default.defaultApp = defaultApp;
+
+var resolveAppFunction$1 = {};
+
+var os$5 = require$$0$h;
+
+// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js
+
+var homedir$2 = os$5.homedir || function homedir() {
+ var home = process.env.HOME;
+ var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
+
+ if (process.platform === 'win32') {
+ return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;
+ }
+
+ if (process.platform === 'darwin') {
+ return home || (user ? '/Users/' + user : null);
+ }
+
+ if (process.platform === 'linux') {
+ return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens
+ }
+
+ return home || null;
+};
+
+var caller$4 = function () {
+ // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
+ var origPrepareStackTrace = Error.prepareStackTrace;
+ Error.prepareStackTrace = function (_, stack) { return stack; };
+ var stack = (new Error()).stack;
+ Error.prepareStackTrace = origPrepareStackTrace;
+ return stack[2].getFileName();
+};
+
+var pathParseExports = {};
+var pathParse = {
+ get exports(){ return pathParseExports; },
+ set exports(v){ pathParseExports = v; },
+};
+
+var hasRequiredPathParse;
+
+function requirePathParse () {
+ if (hasRequiredPathParse) return pathParseExports;
+ hasRequiredPathParse = 1;
+
+ var isWindows = process.platform === 'win32';
+
+ // Regex to split a windows path into into [dir, root, basename, name, ext]
+ var splitWindowsRe =
+ /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/;
+
+ var win32 = {};
+
+ function win32SplitPath(filename) {
+ return splitWindowsRe.exec(filename).slice(1);
+ }
+
+ win32.parse = function(pathString) {
+ if (typeof pathString !== 'string') {
+ throw new TypeError(
+ "Parameter 'pathString' must be a string, not " + typeof pathString
+ );
+ }
+ var allParts = win32SplitPath(pathString);
+ if (!allParts || allParts.length !== 5) {
+ throw new TypeError("Invalid path '" + pathString + "'");
+ }
+ return {
+ root: allParts[1],
+ dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),
+ base: allParts[2],
+ ext: allParts[4],
+ name: allParts[3]
+ };
+ };
+
+
+
+ // Split a filename into [dir, root, basename, name, ext], unix version
+ // 'root' is just a slash, or nothing.
+ var splitPathRe =
+ /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/;
+ var posix = {};
+
+
+ function posixSplitPath(filename) {
+ return splitPathRe.exec(filename).slice(1);
+ }
+
+
+ posix.parse = function(pathString) {
+ if (typeof pathString !== 'string') {
+ throw new TypeError(
+ "Parameter 'pathString' must be a string, not " + typeof pathString
+ );
+ }
+ var allParts = posixSplitPath(pathString);
+ if (!allParts || allParts.length !== 5) {
+ throw new TypeError("Invalid path '" + pathString + "'");
+ }
+
+ return {
+ root: allParts[1],
+ dir: allParts[0].slice(0, -1),
+ base: allParts[2],
+ ext: allParts[4],
+ name: allParts[3],
+ };
+ };
+
+
+ if (isWindows)
+ pathParse.exports = win32.parse;
+ else /* posix */
+ pathParse.exports = posix.parse;
+
+ pathParseExports.posix = posix.parse;
+ pathParseExports.win32 = win32.parse;
+ return pathParseExports;
+}
+
+var path$6 = require$$0$c;
+var parse$1 = path$6.parse || requirePathParse(); // eslint-disable-line global-require
+
+var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
+ var prefix = '/';
+ if ((/^([A-Za-z]:)/).test(absoluteStart)) {
+ prefix = '';
+ } else if ((/^\\\\/).test(absoluteStart)) {
+ prefix = '\\\\';
+ }
+
+ var paths = [absoluteStart];
+ var parsed = parse$1(absoluteStart);
+ while (parsed.dir !== paths[paths.length - 1]) {
+ paths.push(parsed.dir);
+ parsed = parse$1(parsed.dir);
+ }
+
+ return paths.reduce(function (dirs, aPath) {
+ return dirs.concat(modules.map(function (moduleDir) {
+ return path$6.resolve(prefix, aPath, moduleDir);
+ }));
+ }, []);
+};
+
+var nodeModulesPaths$2 = function nodeModulesPaths(start, opts, request) {
+ var modules = opts && opts.moduleDirectory
+ ? [].concat(opts.moduleDirectory)
+ : ['node_modules'];
+
+ if (opts && typeof opts.paths === 'function') {
+ return opts.paths(
+ request,
+ start,
+ function () { return getNodeModulesDirs(start, modules); },
+ opts
+ );
+ }
+
+ var dirs = getNodeModulesDirs(start, modules);
+ return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
+};
+
+var normalizeOptions$2 = function (x, opts) {
+ /**
+ * This file is purposefully a passthrough. It's expected that third-party
+ * environments will override it at runtime in order to inject special logic
+ * into `resolve` (by manipulating the options). One such example is the PnP
+ * code path in Yarn.
+ */
+
+ return opts || {};
+};
+
+var assert$2 = true;
+var async_hooks$1 = ">= 8";
+var buffer_ieee754$1 = ">= 0.5 && < 0.9.7";
+var buffer$2 = true;
+var child_process$1 = true;
+var cluster$1 = ">= 0.5";
+var console$2 = true;
+var constants$1 = true;
+var crypto$2 = true;
+var _debug_agent$1 = ">= 1 && < 8";
+var _debugger$1 = "< 8";
+var dgram$1 = true;
+var diagnostics_channel$1 = [
+ ">= 14.17 && < 15",
+ ">= 15.1"
+];
+var dns$1 = true;
+var domain$1 = ">= 0.7.12";
+var events$2 = true;
+var freelist$1 = "< 6";
+var fs$6 = true;
+var _http_agent$1 = ">= 0.11.1";
+var _http_client$1 = ">= 0.11.1";
+var _http_common$1 = ">= 0.11.1";
+var _http_incoming$1 = ">= 0.11.1";
+var _http_outgoing$1 = ">= 0.11.1";
+var _http_server$1 = ">= 0.11.1";
+var http$2 = true;
+var http2$1 = ">= 8.8";
+var https$2 = true;
+var inspector$1 = ">= 8";
+var _linklist$1 = "< 8";
+var module$2 = true;
+var net$1 = true;
+var os$4 = true;
+var path$5 = true;
+var perf_hooks$1 = ">= 8.5";
+var process$2 = ">= 1";
+var punycode$1 = ">= 0.5";
+var querystring$1 = true;
+var readline$1 = true;
+var repl$1 = true;
+var smalloc$1 = ">= 0.11.5 && < 3";
+var _stream_duplex$1 = ">= 0.9.4";
+var _stream_transform$1 = ">= 0.9.4";
+var _stream_wrap$1 = ">= 1.4.1";
+var _stream_passthrough$1 = ">= 0.9.4";
+var _stream_readable$1 = ">= 0.9.4";
+var _stream_writable$1 = ">= 0.9.4";
+var stream$1 = true;
+var string_decoder$1 = true;
+var sys$1 = [
+ ">= 0.4 && < 0.7",
+ ">= 0.8"
+];
+var timers$1 = true;
+var _tls_common$1 = ">= 0.11.13";
+var _tls_legacy$1 = ">= 0.11.3 && < 10";
+var _tls_wrap$1 = ">= 0.11.3";
+var tls$2 = true;
+var trace_events$1 = ">= 10";
+var tty$1 = true;
+var url$1 = true;
+var util$2 = true;
+var v8$1 = ">= 1";
+var vm$1 = true;
+var wasi$1 = ">= 13.4 && < 13.5";
+var worker_threads$1 = ">= 11.7";
+var zlib$1 = ">= 0.5";
+var require$$1 = {
+ assert: assert$2,
+ "node:assert": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "assert/strict": ">= 15",
+ "node:assert/strict": ">= 16",
+ async_hooks: async_hooks$1,
+ "node:async_hooks": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ buffer_ieee754: buffer_ieee754$1,
+ buffer: buffer$2,
+ "node:buffer": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ child_process: child_process$1,
+ "node:child_process": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ cluster: cluster$1,
+ "node:cluster": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ console: console$2,
+ "node:console": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ constants: constants$1,
+ "node:constants": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ crypto: crypto$2,
+ "node:crypto": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _debug_agent: _debug_agent$1,
+ _debugger: _debugger$1,
+ dgram: dgram$1,
+ "node:dgram": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ diagnostics_channel: diagnostics_channel$1,
+ "node:diagnostics_channel": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ dns: dns$1,
+ "node:dns": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "dns/promises": ">= 15",
+ "node:dns/promises": ">= 16",
+ domain: domain$1,
+ "node:domain": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ events: events$2,
+ "node:events": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ freelist: freelist$1,
+ fs: fs$6,
+ "node:fs": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "fs/promises": [
+ ">= 10 && < 10.1",
+ ">= 14"
+],
+ "node:fs/promises": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_agent: _http_agent$1,
+ "node:_http_agent": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_client: _http_client$1,
+ "node:_http_client": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_common: _http_common$1,
+ "node:_http_common": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_incoming: _http_incoming$1,
+ "node:_http_incoming": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_outgoing: _http_outgoing$1,
+ "node:_http_outgoing": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_server: _http_server$1,
+ "node:_http_server": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ http: http$2,
+ "node:http": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ http2: http2$1,
+ "node:http2": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ https: https$2,
+ "node:https": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ inspector: inspector$1,
+ "node:inspector": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "inspector/promises": [
+ ">= 19"
+],
+ "node:inspector/promises": [
+ ">= 19"
+],
+ _linklist: _linklist$1,
+ module: module$2,
+ "node:module": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ net: net$1,
+ "node:net": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "node-inspect/lib/_inspect": ">= 7.6 && < 12",
+ "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
+ "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
+ os: os$4,
+ "node:os": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ path: path$5,
+ "node:path": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "path/posix": ">= 15.3",
+ "node:path/posix": ">= 16",
+ "path/win32": ">= 15.3",
+ "node:path/win32": ">= 16",
+ perf_hooks: perf_hooks$1,
+ "node:perf_hooks": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ process: process$2,
+ "node:process": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ punycode: punycode$1,
+ "node:punycode": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ querystring: querystring$1,
+ "node:querystring": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ readline: readline$1,
+ "node:readline": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "readline/promises": ">= 17",
+ "node:readline/promises": ">= 17",
+ repl: repl$1,
+ "node:repl": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ smalloc: smalloc$1,
+ _stream_duplex: _stream_duplex$1,
+ "node:_stream_duplex": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_transform: _stream_transform$1,
+ "node:_stream_transform": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_wrap: _stream_wrap$1,
+ "node:_stream_wrap": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_passthrough: _stream_passthrough$1,
+ "node:_stream_passthrough": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_readable: _stream_readable$1,
+ "node:_stream_readable": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_writable: _stream_writable$1,
+ "node:_stream_writable": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ stream: stream$1,
+ "node:stream": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "stream/consumers": ">= 16.7",
+ "node:stream/consumers": ">= 16.7",
+ "stream/promises": ">= 15",
+ "node:stream/promises": ">= 16",
+ "stream/web": ">= 16.5",
+ "node:stream/web": ">= 16.5",
+ string_decoder: string_decoder$1,
+ "node:string_decoder": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ sys: sys$1,
+ "node:sys": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "node:test": [
+ ">= 16.17 && < 17",
+ ">= 18"
+],
+ timers: timers$1,
+ "node:timers": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "timers/promises": ">= 15",
+ "node:timers/promises": ">= 16",
+ _tls_common: _tls_common$1,
+ "node:_tls_common": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _tls_legacy: _tls_legacy$1,
+ _tls_wrap: _tls_wrap$1,
+ "node:_tls_wrap": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ tls: tls$2,
+ "node:tls": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ trace_events: trace_events$1,
+ "node:trace_events": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ tty: tty$1,
+ "node:tty": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ url: url$1,
+ "node:url": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ util: util$2,
+ "node:util": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "util/types": ">= 15.3",
+ "node:util/types": ">= 16",
+ "v8/tools/arguments": ">= 10 && < 12",
+ "v8/tools/codemap": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/consarray": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/csvparser": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/logreader": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/profile_view": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/splaytree": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ v8: v8$1,
+ "node:v8": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ vm: vm$1,
+ "node:vm": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ wasi: wasi$1,
+ worker_threads: worker_threads$1,
+ "node:worker_threads": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ zlib: zlib$1,
+ "node:zlib": [
+ ">= 14.18 && < 15",
+ ">= 16"
+]
+};
+
+var has = src$5;
+
+function specifierIncluded$1(current, specifier) {
+ var nodeParts = current.split('.');
+ var parts = specifier.split(' ');
+ var op = parts.length > 1 ? parts[0] : '=';
+ var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
+
+ for (var i = 0; i < 3; ++i) {
+ var cur = parseInt(nodeParts[i] || 0, 10);
+ var ver = parseInt(versionParts[i] || 0, 10);
+ if (cur === ver) {
+ continue; // eslint-disable-line no-restricted-syntax, no-continue
+ }
+ if (op === '<') {
+ return cur < ver;
+ }
+ if (op === '>=') {
+ return cur >= ver;
+ }
+ return false;
+ }
+ return op === '>=';
+}
+
+function matchesRange$1(current, range) {
+ var specifiers = range.split(/ ?&& ?/);
+ if (specifiers.length === 0) {
+ return false;
+ }
+ for (var i = 0; i < specifiers.length; ++i) {
+ if (!specifierIncluded$1(current, specifiers[i])) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function versionIncluded$1(nodeVersion, specifierValue) {
+ if (typeof specifierValue === 'boolean') {
+ return specifierValue;
+ }
+
+ var current = typeof nodeVersion === 'undefined'
+ ? process.versions && process.versions.node
+ : nodeVersion;
+
+ if (typeof current !== 'string') {
+ throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required');
+ }
+
+ if (specifierValue && typeof specifierValue === 'object') {
+ for (var i = 0; i < specifierValue.length; ++i) {
+ if (matchesRange$1(current, specifierValue[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return matchesRange$1(current, specifierValue);
+}
+
+var data$1 = require$$1;
+
+var isCoreModule$1 = function isCore(x, nodeVersion) {
+ return has(data$1, x) && versionIncluded$1(nodeVersion, data$1[x]);
+};
+
+var fs$5 = require$$0$e;
+var getHomedir$1 = homedir$2;
+var path$4 = require$$0$c;
+var caller$3 = caller$4;
+var nodeModulesPaths$1 = nodeModulesPaths$2;
+var normalizeOptions$1 = normalizeOptions$2;
+var isCore$2 = isCoreModule$1;
+
+var realpathFS$1 = process.platform !== 'win32' && fs$5.realpath && typeof fs$5.realpath.native === 'function' ? fs$5.realpath.native : fs$5.realpath;
+
+var homedir$1 = getHomedir$1();
+var defaultPaths$1 = function () {
+ return [
+ path$4.join(homedir$1, '.node_modules'),
+ path$4.join(homedir$1, '.node_libraries')
+ ];
+};
+
+var defaultIsFile$1 = function isFile(file, cb) {
+ fs$5.stat(file, function (err, stat) {
+ if (!err) {
+ return cb(null, stat.isFile() || stat.isFIFO());
+ }
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
+ return cb(err);
+ });
+};
+
+var defaultIsDir$1 = function isDirectory(dir, cb) {
+ fs$5.stat(dir, function (err, stat) {
+ if (!err) {
+ return cb(null, stat.isDirectory());
+ }
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
+ return cb(err);
+ });
+};
+
+var defaultRealpath = function realpath(x, cb) {
+ realpathFS$1(x, function (realpathErr, realPath) {
+ if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);
+ else cb(null, realpathErr ? x : realPath);
+ });
+};
+
+var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) {
+ if (opts && opts.preserveSymlinks === false) {
+ realpath(x, cb);
+ } else {
+ cb(null, x);
+ }
+};
+
+var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) {
+ readFile(pkgfile, function (readFileErr, body) {
+ if (readFileErr) cb(readFileErr);
+ else {
+ try {
+ var pkg = JSON.parse(body);
+ cb(null, pkg);
+ } catch (jsonErr) {
+ cb(null);
+ }
+ }
+ });
+};
+
+var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) {
+ var dirs = nodeModulesPaths$1(start, opts, x);
+ for (var i = 0; i < dirs.length; i++) {
+ dirs[i] = path$4.join(dirs[i], x);
+ }
+ return dirs;
+};
+
+var async$1 = function resolve(x, options, callback) {
+ var cb = callback;
+ var opts = options;
+ if (typeof options === 'function') {
+ cb = opts;
+ opts = {};
+ }
+ if (typeof x !== 'string') {
+ var err = new TypeError('Path must be a string.');
+ return process.nextTick(function () {
+ cb(err);
+ });
+ }
+
+ opts = normalizeOptions$1(x, opts);
+
+ var isFile = opts.isFile || defaultIsFile$1;
+ var isDirectory = opts.isDirectory || defaultIsDir$1;
+ var readFile = opts.readFile || fs$5.readFile;
+ var realpath = opts.realpath || defaultRealpath;
+ var readPackage = opts.readPackage || defaultReadPackage;
+ if (opts.readFile && opts.readPackage) {
+ var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.');
+ return process.nextTick(function () {
+ cb(conflictErr);
+ });
+ }
+ var packageIterator = opts.packageIterator;
+
+ var extensions = opts.extensions || ['.js'];
+ var includeCoreModules = opts.includeCoreModules !== false;
+ var basedir = opts.basedir || path$4.dirname(caller$3());
+ var parent = opts.filename || basedir;
+
+ opts.paths = opts.paths || defaultPaths$1();
+
+ // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
+ var absoluteStart = path$4.resolve(basedir);
+
+ maybeRealpath(
+ realpath,
+ absoluteStart,
+ opts,
+ function (err, realStart) {
+ if (err) cb(err);
+ else init(realStart);
+ }
+ );
+
+ var res;
+ function init(basedir) {
+ if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
+ res = path$4.resolve(basedir, x);
+ if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
+ if ((/\/$/).test(x) && res === basedir) {
+ loadAsDirectory(res, opts.package, onfile);
+ } else loadAsFile(res, opts.package, onfile);
+ } else if (includeCoreModules && isCore$2(x)) {
+ return cb(null, x);
+ } else loadNodeModules(x, basedir, function (err, n, pkg) {
+ if (err) cb(err);
+ else if (n) {
+ return maybeRealpath(realpath, n, opts, function (err, realN) {
+ if (err) {
+ cb(err);
+ } else {
+ cb(null, realN, pkg);
+ }
+ });
+ } else {
+ var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
+ moduleError.code = 'MODULE_NOT_FOUND';
+ cb(moduleError);
+ }
+ });
+ }
+
+ function onfile(err, m, pkg) {
+ if (err) cb(err);
+ else if (m) cb(null, m, pkg);
+ else loadAsDirectory(res, function (err, d, pkg) {
+ if (err) cb(err);
+ else if (d) {
+ maybeRealpath(realpath, d, opts, function (err, realD) {
+ if (err) {
+ cb(err);
+ } else {
+ cb(null, realD, pkg);
+ }
+ });
+ } else {
+ var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
+ moduleError.code = 'MODULE_NOT_FOUND';
+ cb(moduleError);
+ }
+ });
+ }
+
+ function loadAsFile(x, thePackage, callback) {
+ var loadAsFilePackage = thePackage;
+ var cb = callback;
+ if (typeof loadAsFilePackage === 'function') {
+ cb = loadAsFilePackage;
+ loadAsFilePackage = undefined;
+ }
+
+ var exts = [''].concat(extensions);
+ load(exts, x, loadAsFilePackage);
+
+ function load(exts, x, loadPackage) {
+ if (exts.length === 0) return cb(null, undefined, loadPackage);
+ var file = x + exts[0];
+
+ var pkg = loadPackage;
+ if (pkg) onpkg(null, pkg);
+ else loadpkg(path$4.dirname(file), onpkg);
+
+ function onpkg(err, pkg_, dir) {
+ pkg = pkg_;
+ if (err) return cb(err);
+ if (dir && pkg && opts.pathFilter) {
+ var rfile = path$4.relative(dir, file);
+ var rel = rfile.slice(0, rfile.length - exts[0].length);
+ var r = opts.pathFilter(pkg, x, rel);
+ if (r) return load(
+ [''].concat(extensions.slice()),
+ path$4.resolve(dir, r),
+ pkg
+ );
+ }
+ isFile(file, onex);
+ }
+ function onex(err, ex) {
+ if (err) return cb(err);
+ if (ex) return cb(null, file, pkg);
+ load(exts.slice(1), x, pkg);
+ }
+ }
+ }
+
+ function loadpkg(dir, cb) {
+ if (dir === '' || dir === '/') return cb(null);
+ if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
+ return cb(null);
+ }
+ if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null);
+
+ maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {
+ if (unwrapErr) return loadpkg(path$4.dirname(dir), cb);
+ var pkgfile = path$4.join(pkgdir, 'package.json');
+ isFile(pkgfile, function (err, ex) {
+ // on err, ex is false
+ if (!ex) return loadpkg(path$4.dirname(dir), cb);
+
+ readPackage(readFile, pkgfile, function (err, pkgParam) {
+ if (err) cb(err);
+
+ var pkg = pkgParam;
+
+ if (pkg && opts.packageFilter) {
+ pkg = opts.packageFilter(pkg, pkgfile);
+ }
+ cb(null, pkg, dir);
+ });
+ });
+ });
+ }
+
+ function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
+ var cb = callback;
+ var fpkg = loadAsDirectoryPackage;
+ if (typeof fpkg === 'function') {
+ cb = fpkg;
+ fpkg = opts.package;
+ }
+
+ maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {
+ if (unwrapErr) return cb(unwrapErr);
+ var pkgfile = path$4.join(pkgdir, 'package.json');
+ isFile(pkgfile, function (err, ex) {
+ if (err) return cb(err);
+ if (!ex) return loadAsFile(path$4.join(x, 'index'), fpkg, cb);
+
+ readPackage(readFile, pkgfile, function (err, pkgParam) {
+ if (err) return cb(err);
+
+ var pkg = pkgParam;
+
+ if (pkg && opts.packageFilter) {
+ pkg = opts.packageFilter(pkg, pkgfile);
+ }
+
+ if (pkg && pkg.main) {
+ if (typeof pkg.main !== 'string') {
+ var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
+ mainError.code = 'INVALID_PACKAGE_MAIN';
+ return cb(mainError);
+ }
+ if (pkg.main === '.' || pkg.main === './') {
+ pkg.main = 'index';
+ }
+ loadAsFile(path$4.resolve(x, pkg.main), pkg, function (err, m, pkg) {
+ if (err) return cb(err);
+ if (m) return cb(null, m, pkg);
+ if (!pkg) return loadAsFile(path$4.join(x, 'index'), pkg, cb);
+
+ var dir = path$4.resolve(x, pkg.main);
+ loadAsDirectory(dir, pkg, function (err, n, pkg) {
+ if (err) return cb(err);
+ if (n) return cb(null, n, pkg);
+ loadAsFile(path$4.join(x, 'index'), pkg, cb);
+ });
+ });
+ return;
+ }
+
+ loadAsFile(path$4.join(x, '/index'), pkg, cb);
+ });
+ });
+ });
+ }
+
+ function processDirs(cb, dirs) {
+ if (dirs.length === 0) return cb(null, undefined);
+ var dir = dirs[0];
+
+ isDirectory(path$4.dirname(dir), isdir);
+
+ function isdir(err, isdir) {
+ if (err) return cb(err);
+ if (!isdir) return processDirs(cb, dirs.slice(1));
+ loadAsFile(dir, opts.package, onfile);
+ }
+
+ function onfile(err, m, pkg) {
+ if (err) return cb(err);
+ if (m) return cb(null, m, pkg);
+ loadAsDirectory(dir, opts.package, ondir);
+ }
+
+ function ondir(err, n, pkg) {
+ if (err) return cb(err);
+ if (n) return cb(null, n, pkg);
+ processDirs(cb, dirs.slice(1));
+ }
+ }
+ function loadNodeModules(x, start, cb) {
+ var thunk = function () { return getPackageCandidates$1(x, start, opts); };
+ processDirs(
+ cb,
+ packageIterator ? packageIterator(x, start, thunk, opts) : thunk()
+ );
+ }
+};
+
+var assert$1 = true;
+var async_hooks = ">= 8";
+var buffer_ieee754 = ">= 0.5 && < 0.9.7";
+var buffer$1 = true;
+var child_process = true;
+var cluster = ">= 0.5";
+var console$1 = true;
+var constants = true;
+var crypto$1 = true;
+var _debug_agent = ">= 1 && < 8";
+var _debugger = "< 8";
+var dgram = true;
+var diagnostics_channel = [
+ ">= 14.17 && < 15",
+ ">= 15.1"
+];
+var dns = true;
+var domain = ">= 0.7.12";
+var events$1 = true;
+var freelist = "< 6";
+var fs$4 = true;
+var _http_agent = ">= 0.11.1";
+var _http_client = ">= 0.11.1";
+var _http_common = ">= 0.11.1";
+var _http_incoming = ">= 0.11.1";
+var _http_outgoing = ">= 0.11.1";
+var _http_server = ">= 0.11.1";
+var http$1 = true;
+var http2 = ">= 8.8";
+var https$1 = true;
+var inspector = ">= 8";
+var _linklist = "< 8";
+var module$1 = true;
+var net = true;
+var os$3 = true;
+var path$3 = true;
+var perf_hooks = ">= 8.5";
+var process$1 = ">= 1";
+var punycode = ">= 0.5";
+var querystring = true;
+var readline = true;
+var repl = true;
+var smalloc = ">= 0.11.5 && < 3";
+var _stream_duplex = ">= 0.9.4";
+var _stream_transform = ">= 0.9.4";
+var _stream_wrap = ">= 1.4.1";
+var _stream_passthrough = ">= 0.9.4";
+var _stream_readable = ">= 0.9.4";
+var _stream_writable = ">= 0.9.4";
+var stream = true;
+var string_decoder = true;
+var sys = [
+ ">= 0.4 && < 0.7",
+ ">= 0.8"
+];
+var timers = true;
+var _tls_common = ">= 0.11.13";
+var _tls_legacy = ">= 0.11.3 && < 10";
+var _tls_wrap = ">= 0.11.3";
+var tls$1 = true;
+var trace_events = ">= 10";
+var tty = true;
+var url = true;
+var util$1 = true;
+var v8 = ">= 1";
+var vm = true;
+var wasi = ">= 13.4 && < 13.5";
+var worker_threads = ">= 11.7";
+var zlib = ">= 0.5";
+var require$$0$1 = {
+ assert: assert$1,
+ "node:assert": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "assert/strict": ">= 15",
+ "node:assert/strict": ">= 16",
+ async_hooks: async_hooks,
+ "node:async_hooks": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ buffer_ieee754: buffer_ieee754,
+ buffer: buffer$1,
+ "node:buffer": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ child_process: child_process,
+ "node:child_process": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ cluster: cluster,
+ "node:cluster": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ console: console$1,
+ "node:console": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ constants: constants,
+ "node:constants": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ crypto: crypto$1,
+ "node:crypto": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _debug_agent: _debug_agent,
+ _debugger: _debugger,
+ dgram: dgram,
+ "node:dgram": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ diagnostics_channel: diagnostics_channel,
+ "node:diagnostics_channel": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ dns: dns,
+ "node:dns": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "dns/promises": ">= 15",
+ "node:dns/promises": ">= 16",
+ domain: domain,
+ "node:domain": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ events: events$1,
+ "node:events": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ freelist: freelist,
+ fs: fs$4,
+ "node:fs": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "fs/promises": [
+ ">= 10 && < 10.1",
+ ">= 14"
+],
+ "node:fs/promises": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_agent: _http_agent,
+ "node:_http_agent": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_client: _http_client,
+ "node:_http_client": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_common: _http_common,
+ "node:_http_common": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_incoming: _http_incoming,
+ "node:_http_incoming": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_outgoing: _http_outgoing,
+ "node:_http_outgoing": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _http_server: _http_server,
+ "node:_http_server": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ http: http$1,
+ "node:http": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ http2: http2,
+ "node:http2": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ https: https$1,
+ "node:https": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ inspector: inspector,
+ "node:inspector": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _linklist: _linklist,
+ module: module$1,
+ "node:module": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ net: net,
+ "node:net": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "node-inspect/lib/_inspect": ">= 7.6 && < 12",
+ "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12",
+ "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12",
+ os: os$3,
+ "node:os": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ path: path$3,
+ "node:path": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "path/posix": ">= 15.3",
+ "node:path/posix": ">= 16",
+ "path/win32": ">= 15.3",
+ "node:path/win32": ">= 16",
+ perf_hooks: perf_hooks,
+ "node:perf_hooks": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ process: process$1,
+ "node:process": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ punycode: punycode,
+ "node:punycode": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ querystring: querystring,
+ "node:querystring": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ readline: readline,
+ "node:readline": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "readline/promises": ">= 17",
+ "node:readline/promises": ">= 17",
+ repl: repl,
+ "node:repl": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ smalloc: smalloc,
+ _stream_duplex: _stream_duplex,
+ "node:_stream_duplex": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_transform: _stream_transform,
+ "node:_stream_transform": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_wrap: _stream_wrap,
+ "node:_stream_wrap": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_passthrough: _stream_passthrough,
+ "node:_stream_passthrough": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_readable: _stream_readable,
+ "node:_stream_readable": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _stream_writable: _stream_writable,
+ "node:_stream_writable": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ stream: stream,
+ "node:stream": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "stream/consumers": ">= 16.7",
+ "node:stream/consumers": ">= 16.7",
+ "stream/promises": ">= 15",
+ "node:stream/promises": ">= 16",
+ "stream/web": ">= 16.5",
+ "node:stream/web": ">= 16.5",
+ string_decoder: string_decoder,
+ "node:string_decoder": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ sys: sys,
+ "node:sys": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "node:test": ">= 18",
+ timers: timers,
+ "node:timers": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "timers/promises": ">= 15",
+ "node:timers/promises": ">= 16",
+ _tls_common: _tls_common,
+ "node:_tls_common": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ _tls_legacy: _tls_legacy,
+ _tls_wrap: _tls_wrap,
+ "node:_tls_wrap": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ tls: tls$1,
+ "node:tls": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ trace_events: trace_events,
+ "node:trace_events": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ tty: tty,
+ "node:tty": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ url: url,
+ "node:url": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ util: util$1,
+ "node:util": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ "util/types": ">= 15.3",
+ "node:util/types": ">= 16",
+ "v8/tools/arguments": ">= 10 && < 12",
+ "v8/tools/codemap": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/consarray": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/csvparser": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/logreader": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/profile_view": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ "v8/tools/splaytree": [
+ ">= 4.4 && < 5",
+ ">= 5.2 && < 12"
+],
+ v8: v8,
+ "node:v8": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ vm: vm,
+ "node:vm": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ wasi: wasi,
+ worker_threads: worker_threads,
+ "node:worker_threads": [
+ ">= 14.18 && < 15",
+ ">= 16"
+],
+ zlib: zlib,
+ "node:zlib": [
+ ">= 14.18 && < 15",
+ ">= 16"
+]
+};
+
+var current = (process.versions && process.versions.node && process.versions.node.split('.')) || [];
+
+function specifierIncluded(specifier) {
+ var parts = specifier.split(' ');
+ var op = parts.length > 1 ? parts[0] : '=';
+ var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
+
+ for (var i = 0; i < 3; ++i) {
+ var cur = parseInt(current[i] || 0, 10);
+ var ver = parseInt(versionParts[i] || 0, 10);
+ if (cur === ver) {
+ continue; // eslint-disable-line no-restricted-syntax, no-continue
+ }
+ if (op === '<') {
+ return cur < ver;
+ } else if (op === '>=') {
+ return cur >= ver;
+ }
+ return false;
+ }
+ return op === '>=';
+}
+
+function matchesRange(range) {
+ var specifiers = range.split(/ ?&& ?/);
+ if (specifiers.length === 0) { return false; }
+ for (var i = 0; i < specifiers.length; ++i) {
+ if (!specifierIncluded(specifiers[i])) { return false; }
+ }
+ return true;
+}
+
+function versionIncluded(specifierValue) {
+ if (typeof specifierValue === 'boolean') { return specifierValue; }
+ if (specifierValue && typeof specifierValue === 'object') {
+ for (var i = 0; i < specifierValue.length; ++i) {
+ if (matchesRange(specifierValue[i])) { return true; }
+ }
+ return false;
+ }
+ return matchesRange(specifierValue);
+}
+
+var data = require$$0$1;
+
+var core$2 = {};
+for (var mod in data) { // eslint-disable-line no-restricted-syntax
+ if (Object.prototype.hasOwnProperty.call(data, mod)) {
+ core$2[mod] = versionIncluded(data[mod]);
+ }
+}
+var core_1 = core$2;
+
+var isCoreModule = isCoreModule$1;
+
+var isCore$1 = function isCore(x) {
+ return isCoreModule(x);
+};
+
+var isCore = isCoreModule$1;
+var fs$3 = require$$0$e;
+var path$2 = require$$0$c;
+var getHomedir = homedir$2;
+var caller$2 = caller$4;
+var nodeModulesPaths = nodeModulesPaths$2;
+var normalizeOptions = normalizeOptions$2;
+
+var realpathFS = process.platform !== 'win32' && fs$3.realpathSync && typeof fs$3.realpathSync.native === 'function' ? fs$3.realpathSync.native : fs$3.realpathSync;
+
+var homedir = getHomedir();
+var defaultPaths = function () {
+ return [
+ path$2.join(homedir, '.node_modules'),
+ path$2.join(homedir, '.node_libraries')
+ ];
+};
+
+var defaultIsFile = function isFile(file) {
+ try {
+ var stat = fs$3.statSync(file, { throwIfNoEntry: false });
+ } catch (e) {
+ if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
+ throw e;
+ }
+ return !!stat && (stat.isFile() || stat.isFIFO());
+};
+
+var defaultIsDir = function isDirectory(dir) {
+ try {
+ var stat = fs$3.statSync(dir, { throwIfNoEntry: false });
+ } catch (e) {
+ if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
+ throw e;
+ }
+ return !!stat && stat.isDirectory();
+};
+
+var defaultRealpathSync = function realpathSync(x) {
+ try {
+ return realpathFS(x);
+ } catch (realpathErr) {
+ if (realpathErr.code !== 'ENOENT') {
+ throw realpathErr;
+ }
+ }
+ return x;
+};
+
+var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) {
+ if (opts && opts.preserveSymlinks === false) {
+ return realpathSync(x);
+ }
+ return x;
+};
+
+var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) {
+ var body = readFileSync(pkgfile);
+ try {
+ var pkg = JSON.parse(body);
+ return pkg;
+ } catch (jsonErr) {}
+};
+
+var getPackageCandidates = function getPackageCandidates(x, start, opts) {
+ var dirs = nodeModulesPaths(start, opts, x);
+ for (var i = 0; i < dirs.length; i++) {
+ dirs[i] = path$2.join(dirs[i], x);
+ }
+ return dirs;
+};
+
+var sync = function resolveSync(x, options) {
+ if (typeof x !== 'string') {
+ throw new TypeError('Path must be a string.');
+ }
+ var opts = normalizeOptions(x, options);
+
+ var isFile = opts.isFile || defaultIsFile;
+ var readFileSync = opts.readFileSync || fs$3.readFileSync;
+ var isDirectory = opts.isDirectory || defaultIsDir;
+ var realpathSync = opts.realpathSync || defaultRealpathSync;
+ var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
+ if (opts.readFileSync && opts.readPackageSync) {
+ throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.');
+ }
+ var packageIterator = opts.packageIterator;
+
+ var extensions = opts.extensions || ['.js'];
+ var includeCoreModules = opts.includeCoreModules !== false;
+ var basedir = opts.basedir || path$2.dirname(caller$2());
+ var parent = opts.filename || basedir;
+
+ opts.paths = opts.paths || defaultPaths();
+
+ // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
+ var absoluteStart = maybeRealpathSync(realpathSync, path$2.resolve(basedir), opts);
+
+ if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
+ var res = path$2.resolve(absoluteStart, x);
+ if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
+ var m = loadAsFileSync(res) || loadAsDirectorySync(res);
+ if (m) return maybeRealpathSync(realpathSync, m, opts);
+ } else if (includeCoreModules && isCore(x)) {
+ return x;
+ } else {
+ var n = loadNodeModulesSync(x, absoluteStart);
+ if (n) return maybeRealpathSync(realpathSync, n, opts);
+ }
+
+ var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
+ err.code = 'MODULE_NOT_FOUND';
+ throw err;
+
+ function loadAsFileSync(x) {
+ var pkg = loadpkg(path$2.dirname(x));
+
+ if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
+ var rfile = path$2.relative(pkg.dir, x);
+ var r = opts.pathFilter(pkg.pkg, x, rfile);
+ if (r) {
+ x = path$2.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
+ }
+ }
+
+ if (isFile(x)) {
+ return x;
+ }
+
+ for (var i = 0; i < extensions.length; i++) {
+ var file = x + extensions[i];
+ if (isFile(file)) {
+ return file;
+ }
+ }
+ }
+
+ function loadpkg(dir) {
+ if (dir === '' || dir === '/') return;
+ if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
+ return;
+ }
+ if ((/[/\\]node_modules[/\\]*$/).test(dir)) return;
+
+ var pkgfile = path$2.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json');
+
+ if (!isFile(pkgfile)) {
+ return loadpkg(path$2.dirname(dir));
+ }
+
+ var pkg = readPackageSync(readFileSync, pkgfile);
+
+ if (pkg && opts.packageFilter) {
+ // v2 will pass pkgfile
+ pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment
+ }
+
+ return { pkg: pkg, dir: dir };
+ }
+
+ function loadAsDirectorySync(x) {
+ var pkgfile = path$2.join(maybeRealpathSync(realpathSync, x, opts), '/package.json');
+ if (isFile(pkgfile)) {
+ try {
+ var pkg = readPackageSync(readFileSync, pkgfile);
+ } catch (e) {}
+
+ if (pkg && opts.packageFilter) {
+ // v2 will pass pkgfile
+ pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment
+ }
+
+ if (pkg && pkg.main) {
+ if (typeof pkg.main !== 'string') {
+ var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
+ mainError.code = 'INVALID_PACKAGE_MAIN';
+ throw mainError;
+ }
+ if (pkg.main === '.' || pkg.main === './') {
+ pkg.main = 'index';
+ }
+ try {
+ var m = loadAsFileSync(path$2.resolve(x, pkg.main));
+ if (m) return m;
+ var n = loadAsDirectorySync(path$2.resolve(x, pkg.main));
+ if (n) return n;
+ } catch (e) {}
+ }
+ }
+
+ return loadAsFileSync(path$2.join(x, '/index'));
+ }
+
+ function loadNodeModulesSync(x, start) {
+ var thunk = function () { return getPackageCandidates(x, start, opts); };
+ var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
+
+ for (var i = 0; i < dirs.length; i++) {
+ var dir = dirs[i];
+ if (isDirectory(path$2.dirname(dir))) {
+ var m = loadAsFileSync(dir);
+ if (m) return m;
+ var n = loadAsDirectorySync(dir);
+ if (n) return n;
+ }
+ }
+ }
+};
+
+var async = async$1;
+async.core = core_1;
+async.isCore = isCore$1;
+async.sync = sync;
+
+var resolve = async;
+
+var __createBinding$2 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault$2 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar$2 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$2(result, mod, k);
+ __setModuleDefault$2(result, mod);
+ return result;
+};
+Object.defineProperty(resolveAppFunction$1, "__esModule", { value: true });
+resolveAppFunction$1.resolveAppFunction = void 0;
+const resolve_1 = resolve;
+const defaultOptions$1 = {};
+const resolveAppFunction = async (appFnId, opts) => {
+ opts = opts || defaultOptions$1;
+ // These are mostly to ease testing
+ const basedir = opts.basedir || process.cwd();
+ const resolver = opts.resolver || resolve_1.sync;
+ const appFnPath = resolver(appFnId, { basedir });
+ const mod = await Promise.resolve().then(() => __importStar$2(commonjsRequire(appFnPath)));
+ // Note: This needs "esModuleInterop" to be set to "true" in "tsconfig.json"
+ return mod.default;
+};
+resolveAppFunction$1.resolveAppFunction = resolveAppFunction;
+
+var main$1 = {};
+
+/* @flow */
+
+var hasRequiredMain;
+
+function requireMain () {
+ if (hasRequiredMain) return main$1;
+ hasRequiredMain = 1;
+ /*::
+
+ type DotenvParseOptions = {
+ debug?: boolean
+ }
+
+ // keys and values from src
+ type DotenvParseOutput = { [string]: string }
+
+ type DotenvConfigOptions = {
+ path?: string, // path to .env file
+ encoding?: string, // encoding of .env file
+ debug?: string // turn on logging for debugging purposes
+ }
+
+ type DotenvConfigOutput = {
+ parsed?: DotenvParseOutput,
+ error?: Error
+ }
+
+ */
+
+ const fs = require$$0$e;
+ const path = require$$0$c;
+
+ function log (message /*: string */) {
+ console.log(`[dotenv][DEBUG] ${message}`);
+ }
+
+ const NEWLINE = '\n';
+ const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/;
+ const RE_NEWLINES = /\\n/g;
+ const NEWLINES_MATCH = /\n|\r|\r\n/;
+
+ // Parses src into an Object
+ function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
+ const debug = Boolean(options && options.debug);
+ const obj = {};
+
+ // convert Buffers before splitting into lines and processing
+ src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
+ // matching "KEY' and 'VAL' in 'KEY=VAL'
+ const keyValueArr = line.match(RE_INI_KEY_VAL);
+ // matched?
+ if (keyValueArr != null) {
+ const key = keyValueArr[1];
+ // default undefined or missing values to empty string
+ let val = (keyValueArr[2] || '');
+ const end = val.length - 1;
+ const isDoubleQuoted = val[0] === '"' && val[end] === '"';
+ const isSingleQuoted = val[0] === "'" && val[end] === "'";
+
+ // if single or double quoted, remove quotes
+ if (isSingleQuoted || isDoubleQuoted) {
+ val = val.substring(1, end);
+
+ // if double quoted, expand newlines
+ if (isDoubleQuoted) {
+ val = val.replace(RE_NEWLINES, NEWLINE);
+ }
+ } else {
+ // remove surrounding whitespace
+ val = val.trim();
+ }
+
+ obj[key] = val;
+ } else if (debug) {
+ log(`did not match key and value when parsing line ${idx + 1}: ${line}`);
+ }
+ });
+
+ return obj
+ }
+
+ // Populates process.env from .env file
+ function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
+ let dotenvPath = path.resolve(process.cwd(), '.env');
+ let encoding /*: string */ = 'utf8';
+ let debug = false;
+
+ if (options) {
+ if (options.path != null) {
+ dotenvPath = options.path;
+ }
+ if (options.encoding != null) {
+ encoding = options.encoding;
+ }
+ if (options.debug != null) {
+ debug = true;
+ }
+ }
+
+ try {
+ // specifying an encoding returns a string instead of a buffer
+ const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug });
+
+ Object.keys(parsed).forEach(function (key) {
+ if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
+ process.env[key] = parsed[key];
+ } else if (debug) {
+ log(`"${key}" is already defined in \`process.env\` and will not be overwritten`);
+ }
+ });
+
+ return { parsed }
+ } catch (e) {
+ return { error: e }
+ }
+ }
+
+ main$1.config = config;
+ main$1.parse = parse;
+ return main$1;
+}
+
+var hasRequiredRun;
+
+function requireRun () {
+ if (hasRequiredRun) return run$1;
+ hasRequiredRun = 1;
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
+ Object.defineProperty(run$1, "__esModule", { value: true });
+ run$1.run = void 0;
+ const pkg_conf_1 = __importDefault(pkgConfExports);
+ const index_1 = requireLib();
+ const setup_1 = setup;
+ const get_log_1 = getLog$1;
+ const read_cli_options_1 = readCliOptions$1;
+ const read_env_options_1 = readEnvOptions$1;
+ const server_1 = server;
+ const default_1 = _default;
+ const resolve_app_function_1 = resolveAppFunction$1;
+ const is_production_1 = isProduction$1;
+ /**
+ *
+ * @param appFnOrArgv set to either a probot application function: `(app) => { ... }` or to process.argv
+ */
+ async function run(appFnOrArgv, additionalOptions) {
+ requireMain().config();
+ const envOptions = (0, read_env_options_1.readEnvOptions)(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.env);
+ const cliOptions = Array.isArray(appFnOrArgv)
+ ? (0, read_cli_options_1.readCliOptions)(appFnOrArgv)
+ : {};
+ const {
+ // log options
+ logLevel: level, logFormat, logLevelInString, logMessageKey, sentryDsn,
+ // server options
+ host, port, webhookPath, webhookProxy,
+ // probot options
+ appId, privateKey, redisConfig, secret, baseUrl,
+ // others
+ args, } = { ...envOptions, ...cliOptions };
+ const logOptions = {
+ level,
+ logFormat,
+ logLevelInString,
+ logMessageKey,
+ sentryDsn,
+ };
+ const log = (0, get_log_1.getLog)(logOptions);
+ const probotOptions = {
+ appId,
+ privateKey,
+ redisConfig,
+ secret,
+ baseUrl,
+ log: log.child({ name: "probot" }),
+ };
+ const serverOptions = {
+ host,
+ port,
+ webhookPath,
+ webhookProxy,
+ log: log.child({ name: "server" }),
+ Probot: index_1.Probot.defaults(probotOptions),
+ };
+ let server;
+ if (!appId || !privateKey) {
+ if ((0, is_production_1.isProduction)()) {
+ if (!appId) {
+ throw new Error("App ID is missing, and is required to run in production mode. " +
+ "To resolve, ensure the APP_ID environment variable is set.");
+ }
+ else if (!privateKey) {
+ throw new Error("Certificate is missing, and is required to run in production mode. " +
+ "To resolve, ensure either the PRIVATE_KEY or PRIVATE_KEY_PATH environment variable is set and contains a valid certificate");
+ }
+ }
+ // Workaround for setup (#1512)
+ // When probot is started for the first time, it gets into a setup mode
+ // where `appId` and `privateKey` are not present. The setup mode gets
+ // these credentials. In order to not throw an error, we set the values
+ // to anything, as the Probot instance is not used in setup it makes no
+ // difference anyway.
+ server = new server_1.Server({
+ ...serverOptions,
+ Probot: index_1.Probot.defaults({
+ ...probotOptions,
+ appId: 1,
+ privateKey: "dummy value for setup, see #1512",
+ }),
+ });
+ await server.load((0, setup_1.setupAppFactory)(host, port));
+ await server.start();
+ return server;
+ }
+ if (Array.isArray(appFnOrArgv)) {
+ const pkg = await (0, pkg_conf_1.default)("probot");
+ const combinedApps = async (app) => {
+ await server.load(default_1.defaultApp);
+ if (Array.isArray(pkg.apps)) {
+ for (const appPath of pkg.apps) {
+ const appFn = await (0, resolve_app_function_1.resolveAppFunction)(appPath);
+ await server.load(appFn);
+ }
+ }
+ const [appPath] = args;
+ const appFn = await (0, resolve_app_function_1.resolveAppFunction)(appPath);
+ await server.load(appFn);
+ };
+ server = new server_1.Server(serverOptions);
+ await server.load(combinedApps);
+ await server.start();
+ return server;
+ }
+ server = new server_1.Server(serverOptions);
+ await server.load(appFnOrArgv);
+ await server.start();
+ return server;
+ }
+ run$1.run = run;
+
+ return run$1;
+}
+
+var createNodeMiddleware$1 = {};
+
+Object.defineProperty(createNodeMiddleware$1, "__esModule", { value: true });
+createNodeMiddleware$1.createNodeMiddleware = void 0;
+const webhooks_1 = require$$0$8;
+function createNodeMiddleware(appFn, { probot, webhooksPath }) {
+ probot.load(appFn);
+ return (0, webhooks_1.createNodeMiddleware)(probot.webhooks, {
+ path: webhooksPath || "/",
+ });
+}
+createNodeMiddleware$1.createNodeMiddleware = createNodeMiddleware;
+
+var createProbot$1 = {};
+
+Object.defineProperty(createProbot$1, "__esModule", { value: true });
+createProbot$1.createProbot = void 0;
+const get_private_key_1 = distNode;
+const get_log_1 = getLog$1;
+const probot_1 = probot;
+const DEFAULTS = {
+ APP_ID: "",
+ WEBHOOK_SECRET: "",
+ GHE_HOST: "",
+ GHE_PROTOCOL: "",
+ LOG_FORMAT: "",
+ LOG_LEVEL: "warn",
+ LOG_LEVEL_IN_STRING: "",
+ LOG_MESSAGE_KEY: "msg",
+ REDIS_URL: "",
+ SENTRY_DSN: "",
+};
+/**
+ * Merges configuration from defaults/environment variables/overrides and returns
+ * a Probot instance. Finds private key using [`@probot/get-private-key`](https://github.com/probot/get-private-key).
+ *
+ * @see https://probot.github.io/docs/configuration/
+ * @param defaults default Options, will be overwritten if according environment variable is set
+ * @param overrides overwrites defaults and according environment variables
+ * @param env defaults to process.env
+ */
+function createProbot({ overrides = {}, defaults = {}, env = process.env, } = {}) {
+ const privateKey = (0, get_private_key_1.getPrivateKey)({ env });
+ const envWithDefaults = { ...DEFAULTS, ...env };
+ const envOptions = {
+ logLevel: envWithDefaults.LOG_LEVEL,
+ appId: Number(envWithDefaults.APP_ID),
+ privateKey: (privateKey && privateKey.toString()) || undefined,
+ secret: envWithDefaults.WEBHOOK_SECRET,
+ redisConfig: envWithDefaults.REDIS_URL,
+ baseUrl: envWithDefaults.GHE_HOST
+ ? `${envWithDefaults.GHE_PROTOCOL || "https"}://${envWithDefaults.GHE_HOST}/api/v3`
+ : "https://api.github.com",
+ };
+ const probotOptions = {
+ ...defaults,
+ ...envOptions,
+ ...overrides,
+ };
+ const logOptions = {
+ level: probotOptions.logLevel,
+ logFormat: envWithDefaults.LOG_FORMAT,
+ logLevelInString: envWithDefaults.LOG_LEVEL_IN_STRING === "true",
+ logMessageKey: envWithDefaults.LOG_MESSAGE_KEY,
+ sentryDsn: envWithDefaults.SENTRY_DSN,
+ };
+ const log = (0, get_log_1.getLog)(logOptions).child({ name: "server" });
+ return new probot_1.Probot({
+ log: log.child({ name: "probot" }),
+ ...probotOptions,
+ });
+}
+createProbot$1.createProbot = createProbot;
+
+var hasRequiredLib;
+
+function requireLib () {
+ if (hasRequiredLib) return lib$8;
+ hasRequiredLib = 1;
+ (function (exports) {
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.createProbot = exports.createNodeMiddleware = exports.Server = exports.Probot = exports.run = exports.ProbotOctokit = exports.Context = void 0;
+ const context_1 = context;
+ Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_1.Context; } });
+ const probot_1 = probot;
+ Object.defineProperty(exports, "Probot", { enumerable: true, get: function () { return probot_1.Probot; } });
+ const server_1 = server;
+ Object.defineProperty(exports, "Server", { enumerable: true, get: function () { return server_1.Server; } });
+ const probot_octokit_1 = probotOctokit;
+ Object.defineProperty(exports, "ProbotOctokit", { enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } });
+ const run_1 = requireRun();
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return run_1.run; } });
+ const create_node_middleware_1 = createNodeMiddleware$1;
+ Object.defineProperty(exports, "createNodeMiddleware", { enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } });
+ const create_probot_1 = createProbot$1;
+ Object.defineProperty(exports, "createProbot", { enumerable: true, get: function () { return create_probot_1.createProbot; } });
+
+} (lib$8));
+ return lib$8;
+}
+
+var pinoExports = {};
+var pino$3 = {
+ get exports(){ return pinoExports; },
+ set exports(v){ pinoExports = v; },
+};
+
+// **************************************************************
+// * Code initially copied/adapted from "pony-cause" npm module *
+// * Please upstream improvements there *
+// **************************************************************
+
+const isErrorLike$1 = (err) => {
+ return err && typeof err.message === 'string'
+};
+
+/**
+ * @param {Error|{ cause?: unknown|(()=>err)}} err
+ * @returns {Error|Object|undefined}
+ */
+const getErrorCause = (err) => {
+ if (!err) return
+
+ /** @type {unknown} */
+ // @ts-ignore
+ const cause = err.cause;
+
+ // VError / NError style causes
+ if (typeof cause === 'function') {
+ // @ts-ignore
+ const causeResult = err.cause();
+
+ return isErrorLike$1(causeResult)
+ ? causeResult
+ : undefined
+ } else {
+ return isErrorLike$1(cause)
+ ? cause
+ : undefined
+ }
+};
+
+/**
+ * Internal method that keeps a track of which error we have already added, to avoid circular recursion
+ *
+ * @private
+ * @param {Error} err
+ * @param {Set} seen
+ * @returns {string}
+ */
+const _stackWithCauses = (err, seen) => {
+ if (!isErrorLike$1(err)) return ''
+
+ const stack = err.stack || '';
+
+ // Ensure we don't go circular or crazily deep
+ if (seen.has(err)) {
+ return stack + '\ncauses have become circular...'
+ }
+
+ const cause = getErrorCause(err);
+
+ if (cause) {
+ seen.add(err);
+ return (stack + '\ncaused by: ' + _stackWithCauses(cause, seen))
+ } else {
+ return stack
+ }
+};
+
+/**
+ * @param {Error} err
+ * @returns {string}
+ */
+const stackWithCauses$1 = (err) => _stackWithCauses(err, new Set());
+
+/**
+ * Internal method that keeps a track of which error we have already added, to avoid circular recursion
+ *
+ * @private
+ * @param {Error} err
+ * @param {Set} seen
+ * @param {boolean} [skip]
+ * @returns {string}
+ */
+const _messageWithCauses = (err, seen, skip) => {
+ if (!isErrorLike$1(err)) return ''
+
+ const message = skip ? '' : (err.message || '');
+
+ // Ensure we don't go circular or crazily deep
+ if (seen.has(err)) {
+ return message + ': ...'
+ }
+
+ const cause = getErrorCause(err);
+
+ if (cause) {
+ seen.add(err);
+
+ // @ts-ignore
+ const skipIfVErrorStyleCause = typeof err.cause === 'function';
+
+ return (message +
+ (skipIfVErrorStyleCause ? '' : ': ') +
+ _messageWithCauses(cause, seen, skipIfVErrorStyleCause))
+ } else {
+ return message
+ }
+};
+
+/**
+ * @param {Error} err
+ * @returns {string}
+ */
+const messageWithCauses$1 = (err) => _messageWithCauses(err, new Set());
+
+var errHelpers = {
+ isErrorLike: isErrorLike$1,
+ getErrorCause,
+ stackWithCauses: stackWithCauses$1,
+ messageWithCauses: messageWithCauses$1
+};
+
+var err = errSerializer$1;
+
+const { messageWithCauses, stackWithCauses, isErrorLike } = errHelpers;
+
+const { toString: toString$1 } = Object.prototype;
+const seen = Symbol('circular-ref-tag');
+const rawSymbol$2 = Symbol('pino-raw-err-ref');
+const pinoErrProto = Object.create({}, {
+ type: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ message: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ stack: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ aggregateErrors: {
+ enumerable: true,
+ writable: true,
+ value: undefined
+ },
+ raw: {
+ enumerable: false,
+ get: function () {
+ return this[rawSymbol$2]
+ },
+ set: function (val) {
+ this[rawSymbol$2] = val;
+ }
+ }
+});
+Object.defineProperty(pinoErrProto, rawSymbol$2, {
+ writable: true,
+ value: {}
+});
+
+function errSerializer$1 (err) {
+ if (!isErrorLike(err)) {
+ return err
+ }
+
+ err[seen] = undefined; // tag to prevent re-looking at this
+ const _err = Object.create(pinoErrProto);
+ _err.type = toString$1.call(err.constructor) === '[object Function]'
+ ? err.constructor.name
+ : err.name;
+ _err.message = messageWithCauses(err);
+ _err.stack = stackWithCauses(err);
+
+ if (Array.isArray(err.errors)) {
+ _err.aggregateErrors = err.errors.map(err => errSerializer$1(err));
+ }
+
+ for (const key in err) {
+ if (_err[key] === undefined) {
+ const val = err[key];
+ if (isErrorLike(val)) {
+ // We append cause messages and stacks to _err, therefore skipping causes here
+ if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {
+ _err[key] = errSerializer$1(val);
+ }
+ } else {
+ _err[key] = val;
+ }
+ }
+ }
+
+ delete err[seen]; // clean up tag in case err is serialized again later
+ _err.raw = err;
+ return _err
+}
+
+var req = {
+ mapHttpRequest: mapHttpRequest$1,
+ reqSerializer
+};
+
+const rawSymbol$1 = Symbol('pino-raw-req-ref');
+const pinoReqProto = Object.create({}, {
+ id: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ method: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ url: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ query: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ params: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ headers: {
+ enumerable: true,
+ writable: true,
+ value: {}
+ },
+ remoteAddress: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ remotePort: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ raw: {
+ enumerable: false,
+ get: function () {
+ return this[rawSymbol$1]
+ },
+ set: function (val) {
+ this[rawSymbol$1] = val;
+ }
+ }
+});
+Object.defineProperty(pinoReqProto, rawSymbol$1, {
+ writable: true,
+ value: {}
+});
+
+function reqSerializer (req) {
+ // req.info is for hapi compat.
+ const connection = req.info || req.socket;
+ const _req = Object.create(pinoReqProto);
+ _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)));
+ _req.method = req.method;
+ // req.originalUrl is for expressjs compat.
+ if (req.originalUrl) {
+ _req.url = req.originalUrl;
+ } else {
+ const path = req.path;
+ // path for safe hapi compat.
+ _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined);
+ }
+
+ if (req.query) {
+ _req.query = req.query;
+ }
+
+ if (req.params) {
+ _req.params = req.params;
+ }
+
+ _req.headers = req.headers;
+ _req.remoteAddress = connection && connection.remoteAddress;
+ _req.remotePort = connection && connection.remotePort;
+ // req.raw is for hapi compat/equivalence
+ _req.raw = req.raw || req;
+ return _req
+}
+
+function mapHttpRequest$1 (req) {
+ return {
+ req: reqSerializer(req)
+ }
+}
+
+var res = {
+ mapHttpResponse: mapHttpResponse$1,
+ resSerializer
+};
+
+const rawSymbol = Symbol('pino-raw-res-ref');
+const pinoResProto = Object.create({}, {
+ statusCode: {
+ enumerable: true,
+ writable: true,
+ value: 0
+ },
+ headers: {
+ enumerable: true,
+ writable: true,
+ value: ''
+ },
+ raw: {
+ enumerable: false,
+ get: function () {
+ return this[rawSymbol]
+ },
+ set: function (val) {
+ this[rawSymbol] = val;
+ }
+ }
+});
+Object.defineProperty(pinoResProto, rawSymbol, {
+ writable: true,
+ value: {}
+});
+
+function resSerializer (res) {
+ const _res = Object.create(pinoResProto);
+ _res.statusCode = res.headersSent ? res.statusCode : null;
+ _res.headers = res.getHeaders ? res.getHeaders() : res._headers;
+ _res.raw = res;
+ return _res
+}
+
+function mapHttpResponse$1 (res) {
+ return {
+ res: resSerializer(res)
+ }
+}
+
+const errSerializer = err;
+const reqSerializers = req;
+const resSerializers = res;
+
+var pinoStdSerializers = {
+ err: errSerializer,
+ mapHttpRequest: reqSerializers.mapHttpRequest,
+ mapHttpResponse: resSerializers.mapHttpResponse,
+ req: reqSerializers.reqSerializer,
+ res: resSerializers.resSerializer,
+
+ wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {
+ if (customSerializer === errSerializer) return customSerializer
+ return function wrapErrSerializer (err) {
+ return customSerializer(errSerializer(err))
+ }
+ },
+
+ wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {
+ if (customSerializer === reqSerializers.reqSerializer) return customSerializer
+ return function wrappedReqSerializer (req) {
+ return customSerializer(reqSerializers.reqSerializer(req))
+ }
+ },
+
+ wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {
+ if (customSerializer === resSerializers.resSerializer) return customSerializer
+ return function wrappedResSerializer (res) {
+ return customSerializer(resSerializers.resSerializer(res))
+ }
+ }
+};
+
+function noOpPrepareStackTrace (_, stack) {
+ return stack
+}
+
+var caller$1 = function getCallers () {
+ const originalPrepare = Error.prepareStackTrace;
+ Error.prepareStackTrace = noOpPrepareStackTrace;
+ const stack = new Error().stack;
+ Error.prepareStackTrace = originalPrepare;
+
+ if (!Array.isArray(stack)) {
+ return undefined
+ }
+
+ const entries = stack.slice(2);
+
+ const fileNames = [];
+
+ for (const entry of entries) {
+ if (!entry) {
+ continue
+ }
+
+ fileNames.push(entry.getFileName());
+ }
+
+ return fileNames
+};
+
+const setLevelSym$2 = Symbol('pino.setLevel');
+const getLevelSym$1 = Symbol('pino.getLevel');
+const levelValSym$2 = Symbol('pino.levelVal');
+const useLevelLabelsSym = Symbol('pino.useLevelLabels');
+const useOnlyCustomLevelsSym$3 = Symbol('pino.useOnlyCustomLevels');
+const mixinSym$2 = Symbol('pino.mixin');
+
+const lsCacheSym$3 = Symbol('pino.lsCache');
+const chindingsSym$3 = Symbol('pino.chindings');
+
+const asJsonSym$1 = Symbol('pino.asJson');
+const writeSym$2 = Symbol('pino.write');
+const redactFmtSym$3 = Symbol('pino.redactFmt');
+
+const timeSym$2 = Symbol('pino.time');
+const timeSliceIndexSym$2 = Symbol('pino.timeSliceIndex');
+const streamSym$3 = Symbol('pino.stream');
+const stringifySym$3 = Symbol('pino.stringify');
+const stringifySafeSym$2 = Symbol('pino.stringifySafe');
+const stringifiersSym$3 = Symbol('pino.stringifiers');
+const endSym$2 = Symbol('pino.end');
+const formatOptsSym$3 = Symbol('pino.formatOpts');
+const messageKeySym$2 = Symbol('pino.messageKey');
+const errorKeySym$3 = Symbol('pino.errorKey');
+const nestedKeySym$2 = Symbol('pino.nestedKey');
+const nestedKeyStrSym$2 = Symbol('pino.nestedKeyStr');
+const mixinMergeStrategySym$2 = Symbol('pino.mixinMergeStrategy');
+const msgPrefixSym$3 = Symbol('pino.msgPrefix');
+
+const wildcardFirstSym$2 = Symbol('pino.wildcardFirst');
+
+// public symbols, no need to use the same pino
+// version for these
+const serializersSym$3 = Symbol.for('pino.serializers');
+const formattersSym$4 = Symbol.for('pino.formatters');
+const hooksSym$2 = Symbol.for('pino.hooks');
+const needsMetadataGsym$1 = Symbol.for('pino.metadata');
+
+var symbols$1 = {
+ setLevelSym: setLevelSym$2,
+ getLevelSym: getLevelSym$1,
+ levelValSym: levelValSym$2,
+ useLevelLabelsSym,
+ mixinSym: mixinSym$2,
+ lsCacheSym: lsCacheSym$3,
+ chindingsSym: chindingsSym$3,
+ asJsonSym: asJsonSym$1,
+ writeSym: writeSym$2,
+ serializersSym: serializersSym$3,
+ redactFmtSym: redactFmtSym$3,
+ timeSym: timeSym$2,
+ timeSliceIndexSym: timeSliceIndexSym$2,
+ streamSym: streamSym$3,
+ stringifySym: stringifySym$3,
+ stringifySafeSym: stringifySafeSym$2,
+ stringifiersSym: stringifiersSym$3,
+ endSym: endSym$2,
+ formatOptsSym: formatOptsSym$3,
+ messageKeySym: messageKeySym$2,
+ errorKeySym: errorKeySym$3,
+ nestedKeySym: nestedKeySym$2,
+ wildcardFirstSym: wildcardFirstSym$2,
+ needsMetadataGsym: needsMetadataGsym$1,
+ useOnlyCustomLevelsSym: useOnlyCustomLevelsSym$3,
+ formattersSym: formattersSym$4,
+ hooksSym: hooksSym$2,
+ nestedKeyStrSym: nestedKeyStrSym$2,
+ mixinMergeStrategySym: mixinMergeStrategySym$2,
+ msgPrefixSym: msgPrefixSym$3
+};
+
+const fastRedact = fastRedact_1;
+const { redactFmtSym: redactFmtSym$2, wildcardFirstSym: wildcardFirstSym$1 } = symbols$1;
+const { rx, validator } = fastRedact;
+
+const validate$1 = validator({
+ ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings',
+ ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})`
+});
+
+const CENSOR = '[Redacted]';
+const strict = false; // TODO should this be configurable?
+
+function redaction$2 (opts, serialize) {
+ const { paths, censor } = handle(opts);
+
+ const shape = paths.reduce((o, str) => {
+ rx.lastIndex = 0;
+ const first = rx.exec(str);
+ const next = rx.exec(str);
+
+ // ns is the top-level path segment, brackets + quoting removed.
+ let ns = first[1] !== undefined
+ ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, '$1')
+ : first[0];
+
+ if (ns === '*') {
+ ns = wildcardFirstSym$1;
+ }
+
+ // top level key:
+ if (next === null) {
+ o[ns] = null;
+ return o
+ }
+
+ // path with at least two segments:
+ // if ns is already redacted at the top level, ignore lower level redactions
+ if (o[ns] === null) {
+ return o
+ }
+
+ const { index } = next;
+ const nextPath = `${str.substr(index, str.length - 1)}`;
+
+ o[ns] = o[ns] || [];
+
+ // shape is a mix of paths beginning with literal values and wildcard
+ // paths [ "a.b.c", "*.b.z" ] should reduce to a shape of
+ // { "a": [ "b.c", "b.z" ], *: [ "b.z" ] }
+ // note: "b.z" is in both "a" and * arrays because "a" matches the wildcard.
+ // (* entry has wildcardFirstSym as key)
+ if (ns !== wildcardFirstSym$1 && o[ns].length === 0) {
+ // first time ns's get all '*' redactions so far
+ o[ns].push(...(o[wildcardFirstSym$1] || []));
+ }
+
+ if (ns === wildcardFirstSym$1) {
+ // new * path gets added to all previously registered literal ns's.
+ Object.keys(o).forEach(function (k) {
+ if (o[k]) {
+ o[k].push(nextPath);
+ }
+ });
+ }
+
+ o[ns].push(nextPath);
+ return o
+ }, {});
+
+ // the redactor assigned to the format symbol key
+ // provides top level redaction for instances where
+ // an object is interpolated into the msg string
+ const result = {
+ [redactFmtSym$2]: fastRedact({ paths, censor, serialize, strict })
+ };
+
+ const topCensor = (...args) => {
+ return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)
+ };
+
+ return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {
+ // top level key:
+ if (shape[k] === null) {
+ o[k] = (value) => topCensor(value, [k]);
+ } else {
+ const wrappedCensor = typeof censor === 'function'
+ ? (value, path) => {
+ return censor(value, [k, ...path])
+ }
+ : censor;
+ o[k] = fastRedact({
+ paths: shape[k],
+ censor: wrappedCensor,
+ serialize,
+ strict
+ });
+ }
+ return o
+ }, result)
+}
+
+function handle (opts) {
+ if (Array.isArray(opts)) {
+ opts = { paths: opts, censor: CENSOR };
+ validate$1(opts);
+ return opts
+ }
+ let { paths, censor = CENSOR, remove } = opts;
+ if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') }
+ if (remove === true) censor = undefined;
+ validate$1({ paths, censor });
+
+ return { paths, censor }
+}
+
+var redaction_1 = redaction$2;
+
+const nullTime$1 = () => '';
+
+const epochTime$1 = () => `,"time":${Date.now()}`;
+
+const unixTime = () => `,"time":${Math.round(Date.now() / 1000.0)}`;
+
+const isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"`; // using Date.now() for testability
+
+var time$1 = { nullTime: nullTime$1, epochTime: epochTime$1, unixTime, isoTime };
+
+const fs$2 = require$$0$e;
+const EventEmitter$3 = require$$0$f;
+const inherits$1 = require$$1$7.inherits;
+const path$1 = require$$0$c;
+const sleep$1 = atomicSleepExports;
+
+const BUSY_WRITE_TIMEOUT = 100;
+
+// 16 KB. Don't write more than docker buffer size.
+// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13
+const MAX_WRITE = 16 * 1024;
+
+function openFile (file, sonic) {
+ sonic._opening = true;
+ sonic._writing = true;
+ sonic._asyncDrainScheduled = false;
+
+ // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false
+ // for sync mode, there is no way to add a listener that will receive these
+
+ function fileOpened (err, fd) {
+ if (err) {
+ sonic._reopening = false;
+ sonic._writing = false;
+ sonic._opening = false;
+
+ if (sonic.sync) {
+ process.nextTick(() => {
+ if (sonic.listenerCount('error') > 0) {
+ sonic.emit('error', err);
+ }
+ });
+ } else {
+ sonic.emit('error', err);
+ }
+ return
+ }
+
+ sonic.fd = fd;
+ sonic.file = file;
+ sonic._reopening = false;
+ sonic._opening = false;
+ sonic._writing = false;
+
+ if (sonic.sync) {
+ process.nextTick(() => sonic.emit('ready'));
+ } else {
+ sonic.emit('ready');
+ }
+
+ if (sonic._reopening) {
+ return
+ }
+
+ // start
+ if (!sonic._writing && sonic._len > sonic.minLength && !sonic.destroyed) {
+ actualWrite(sonic);
+ }
+ }
+
+ const flags = sonic.append ? 'a' : 'w';
+ const mode = sonic.mode;
+
+ if (sonic.sync) {
+ try {
+ if (sonic.mkdir) fs$2.mkdirSync(path$1.dirname(file), { recursive: true });
+ const fd = fs$2.openSync(file, flags, mode);
+ fileOpened(null, fd);
+ } catch (err) {
+ fileOpened(err);
+ throw err
+ }
+ } else if (sonic.mkdir) {
+ fs$2.mkdir(path$1.dirname(file), { recursive: true }, (err) => {
+ if (err) return fileOpened(err)
+ fs$2.open(file, flags, mode, fileOpened);
+ });
+ } else {
+ fs$2.open(file, flags, mode, fileOpened);
+ }
+}
+
+function SonicBoom$1 (opts) {
+ if (!(this instanceof SonicBoom$1)) {
+ return new SonicBoom$1(opts)
+ }
+
+ let { fd, dest, minLength, maxLength, maxWrite, sync, append = true, mode, mkdir, retryEAGAIN, fsync } = opts || {};
+
+ fd = fd || dest;
+
+ this._bufs = [];
+ this._len = 0;
+ this.fd = -1;
+ this._writing = false;
+ this._writingBuf = '';
+ this._ending = false;
+ this._reopening = false;
+ this._asyncDrainScheduled = false;
+ this._hwm = Math.max(minLength || 0, 16387);
+ this.file = null;
+ this.destroyed = false;
+ this.minLength = minLength || 0;
+ this.maxLength = maxLength || 0;
+ this.maxWrite = maxWrite || MAX_WRITE;
+ this.sync = sync || false;
+ this._fsync = fsync || false;
+ this.append = append || false;
+ this.mode = mode;
+ this.retryEAGAIN = retryEAGAIN || (() => true);
+ this.mkdir = mkdir || false;
+
+ if (typeof fd === 'number') {
+ this.fd = fd;
+ process.nextTick(() => this.emit('ready'));
+ } else if (typeof fd === 'string') {
+ openFile(fd, this);
+ } else {
+ throw new Error('SonicBoom supports only file descriptors and files')
+ }
+ if (this.minLength >= this.maxWrite) {
+ throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)
+ }
+
+ this.release = (err, n) => {
+ if (err) {
+ if (err.code === 'EAGAIN' && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {
+ if (this.sync) {
+ // This error code should not happen in sync mode, because it is
+ // not using the underlining operating system asynchronous functions.
+ // However it happens, and so we handle it.
+ // Ref: https://github.com/pinojs/pino/issues/783
+ try {
+ sleep$1(BUSY_WRITE_TIMEOUT);
+ this.release(undefined, 0);
+ } catch (err) {
+ this.release(err);
+ }
+ } else {
+ // Let's give the destination some time to process the chunk.
+ setTimeout(() => {
+ fs$2.write(this.fd, this._writingBuf, 'utf8', this.release);
+ }, BUSY_WRITE_TIMEOUT);
+ }
+ } else {
+ this._writing = false;
+
+ this.emit('error', err);
+ }
+ return
+ }
+
+ this.emit('write', n);
+
+ this._len -= n;
+ // In case of multi-byte characters, the length of the written buffer
+ // may be different from the length of the string. Let's make sure
+ // we do not have an accumulated string with a negative length.
+ // This also mean that ._len is not precise, but it's not a problem as some
+ // writes might be triggered earlier than ._minLength.
+ if (this._len < 0) {
+ this._len = 0;
+ }
+
+ // TODO if we have a multi-byte character in the buffer, we need to
+ // n might not be the same as this._writingBuf.length, so we might loose
+ // characters here. The solution to this problem is to use a Buffer for _writingBuf.
+ this._writingBuf = this._writingBuf.slice(n);
+
+ if (this._writingBuf.length) {
+ if (!this.sync) {
+ fs$2.write(this.fd, this._writingBuf, 'utf8', this.release);
+ return
+ }
+
+ try {
+ do {
+ const n = fs$2.writeSync(this.fd, this._writingBuf, 'utf8');
+ this._len -= n;
+ this._writingBuf = this._writingBuf.slice(n);
+ } while (this._writingBuf)
+ } catch (err) {
+ this.release(err);
+ return
+ }
+ }
+
+ if (this._fsync) {
+ fs$2.fsyncSync(this.fd);
+ }
+
+ const len = this._len;
+ if (this._reopening) {
+ this._writing = false;
+ this._reopening = false;
+ this.reopen();
+ } else if (len > this.minLength) {
+ actualWrite(this);
+ } else if (this._ending) {
+ if (len > 0) {
+ actualWrite(this);
+ } else {
+ this._writing = false;
+ actualClose(this);
+ }
+ } else {
+ this._writing = false;
+ if (this.sync) {
+ if (!this._asyncDrainScheduled) {
+ this._asyncDrainScheduled = true;
+ process.nextTick(emitDrain, this);
+ }
+ } else {
+ this.emit('drain');
+ }
+ }
+ };
+
+ this.on('newListener', function (name) {
+ if (name === 'drain') {
+ this._asyncDrainScheduled = false;
+ }
+ });
+}
+
+function emitDrain (sonic) {
+ const hasListeners = sonic.listenerCount('drain') > 0;
+ if (!hasListeners) return
+ sonic._asyncDrainScheduled = false;
+ sonic.emit('drain');
+}
+
+inherits$1(SonicBoom$1, EventEmitter$3);
+
+SonicBoom$1.prototype.write = function (data) {
+ if (this.destroyed) {
+ throw new Error('SonicBoom destroyed')
+ }
+
+ const len = this._len + data.length;
+ const bufs = this._bufs;
+
+ if (this.maxLength && len > this.maxLength) {
+ this.emit('drop', data);
+ return this._len < this._hwm
+ }
+
+ if (
+ bufs.length === 0 ||
+ bufs[bufs.length - 1].length + data.length > this.maxWrite
+ ) {
+ bufs.push('' + data);
+ } else {
+ bufs[bufs.length - 1] += data;
+ }
+
+ this._len = len;
+
+ if (!this._writing && this._len >= this.minLength) {
+ actualWrite(this);
+ }
+
+ return this._len < this._hwm
+};
+
+SonicBoom$1.prototype.flush = function () {
+ if (this.destroyed) {
+ throw new Error('SonicBoom destroyed')
+ }
+
+ if (this._writing || this.minLength <= 0) {
+ return
+ }
+
+ if (this._bufs.length === 0) {
+ this._bufs.push('');
+ }
+
+ actualWrite(this);
+};
+
+SonicBoom$1.prototype.reopen = function (file) {
+ if (this.destroyed) {
+ throw new Error('SonicBoom destroyed')
+ }
+
+ if (this._opening) {
+ this.once('ready', () => {
+ this.reopen(file);
+ });
+ return
+ }
+
+ if (this._ending) {
+ return
+ }
+
+ if (!this.file) {
+ throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')
+ }
+
+ this._reopening = true;
+
+ if (this._writing) {
+ return
+ }
+
+ const fd = this.fd;
+ this.once('ready', () => {
+ if (fd !== this.fd) {
+ fs$2.close(fd, (err) => {
+ if (err) {
+ return this.emit('error', err)
+ }
+ });
+ }
+ });
+
+ openFile(file || this.file, this);
+};
+
+SonicBoom$1.prototype.end = function () {
+ if (this.destroyed) {
+ throw new Error('SonicBoom destroyed')
+ }
+
+ if (this._opening) {
+ this.once('ready', () => {
+ this.end();
+ });
+ return
+ }
+
+ if (this._ending) {
+ return
+ }
+
+ this._ending = true;
+
+ if (this._writing) {
+ return
+ }
+
+ if (this._len > 0 && this.fd >= 0) {
+ actualWrite(this);
+ } else {
+ actualClose(this);
+ }
+};
+
+SonicBoom$1.prototype.flushSync = function () {
+ if (this.destroyed) {
+ throw new Error('SonicBoom destroyed')
+ }
+
+ if (this.fd < 0) {
+ throw new Error('sonic boom is not ready yet')
+ }
+
+ if (!this._writing && this._writingBuf.length > 0) {
+ this._bufs.unshift(this._writingBuf);
+ this._writingBuf = '';
+ }
+
+ let buf = '';
+ while (this._bufs.length || buf.length) {
+ if (buf.length <= 0) {
+ buf = this._bufs[0];
+ }
+ try {
+ const n = fs$2.writeSync(this.fd, buf, 'utf8');
+ buf = buf.slice(n);
+ this._len = Math.max(this._len - n, 0);
+ if (buf.length <= 0) {
+ this._bufs.shift();
+ }
+ } catch (err) {
+ if (err.code !== 'EAGAIN' || !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {
+ throw err
+ }
+
+ sleep$1(BUSY_WRITE_TIMEOUT);
+ }
+ }
+};
+
+SonicBoom$1.prototype.destroy = function () {
+ if (this.destroyed) {
+ return
+ }
+ actualClose(this);
+};
+
+function actualWrite (sonic) {
+ const release = sonic.release;
+ sonic._writing = true;
+ sonic._writingBuf = sonic._writingBuf || sonic._bufs.shift() || '';
+
+ if (sonic.sync) {
+ try {
+ const written = fs$2.writeSync(sonic.fd, sonic._writingBuf, 'utf8');
+ release(null, written);
+ } catch (err) {
+ release(err);
+ }
+ } else {
+ fs$2.write(sonic.fd, sonic._writingBuf, 'utf8', release);
+ }
+}
+
+function actualClose (sonic) {
+ if (sonic.fd === -1) {
+ sonic.once('ready', actualClose.bind(null, sonic));
+ return
+ }
+
+ sonic.destroyed = true;
+ sonic._bufs = [];
+
+ if (sonic.fd !== 1 && sonic.fd !== 2) {
+ fs$2.close(sonic.fd, done);
+ } else {
+ setImmediate(done);
+ }
+
+ function done (err) {
+ if (err) {
+ sonic.emit('error', err);
+ return
+ }
+
+ if (sonic._ending && !sonic._writing) {
+ sonic.emit('finish');
+ }
+ sonic.emit('close');
+ }
+}
+
+/**
+ * These export configurations enable JS and TS developers
+ * to consumer SonicBoom in whatever way best suits their needs.
+ * Some examples of supported import syntax includes:
+ * - `const SonicBoom = require('SonicBoom')`
+ * - `const { SonicBoom } = require('SonicBoom')`
+ * - `import * as SonicBoom from 'SonicBoom'`
+ * - `import { SonicBoom } from 'SonicBoom'`
+ * - `import SonicBoom from 'SonicBoom'`
+ */
+SonicBoom$1.SonicBoom = SonicBoom$1;
+SonicBoom$1.default = SonicBoom$1;
+var sonicBoom = SonicBoom$1;
+
+const refs = {
+ exit: [],
+ beforeExit: []
+};
+const functions = {
+ exit: onExit$2,
+ beforeExit: onBeforeExit
+};
+const registry$1 = new FinalizationRegistry(clear);
+
+function install (event) {
+ if (refs[event].length > 0) {
+ return
+ }
+
+ process.on(event, functions[event]);
+}
+
+function uninstall (event) {
+ if (refs[event].length > 0) {
+ return
+ }
+ process.removeListener(event, functions[event]);
+}
+
+function onExit$2 () {
+ callRefs('exit');
+}
+
+function onBeforeExit () {
+ callRefs('beforeExit');
+}
+
+function callRefs (event) {
+ for (const ref of refs[event]) {
+ const obj = ref.deref();
+ const fn = ref.fn;
+
+ // This should always happen, however GC is
+ // undeterministic so it might not happen.
+ /* istanbul ignore else */
+ if (obj !== undefined) {
+ fn(obj, event);
+ }
+ }
+}
+
+function clear (ref) {
+ for (const event of ['exit', 'beforeExit']) {
+ const index = refs[event].indexOf(ref);
+ refs[event].splice(index, index + 1);
+ uninstall(event);
+ }
+}
+
+function _register (event, obj, fn) {
+ if (obj === undefined) {
+ throw new Error('the object can\'t be undefined')
+ }
+ install(event);
+ const ref = new WeakRef(obj);
+ ref.fn = fn;
+
+ registry$1.register(obj, ref);
+ refs[event].push(ref);
+}
+
+function register (obj, fn) {
+ _register('exit', obj, fn);
+}
+
+function registerBeforeExit (obj, fn) {
+ _register('beforeExit', obj, fn);
+}
+
+function unregister (obj) {
+ registry$1.unregister(obj);
+ for (const event of ['exit', 'beforeExit']) {
+ refs[event] = refs[event].filter((ref) => {
+ const _obj = ref.deref();
+ return _obj && _obj !== obj
+ });
+ uninstall(event);
+ }
+}
+
+var onExitLeakFree = {
+ register,
+ registerBeforeExit,
+ unregister
+};
+
+var name = "thread-stream";
+var version$4 = "2.3.0";
+var description = "A streaming way to send data to a Node.js Worker Thread";
+var main = "index.js";
+var types = "index.d.ts";
+var dependencies = {
+ "real-require": "^0.2.0"
+};
+var devDependencies = {
+ "@types/node": "^18.0.0",
+ "@types/tap": "^15.0.0",
+ desm: "^1.3.0",
+ fastbench: "^1.0.1",
+ husky: "^8.0.1",
+ "sonic-boom": "^3.0.0",
+ standard: "^17.0.0",
+ tap: "^16.2.0",
+ "ts-node": "^10.8.0",
+ typescript: "^4.7.2",
+ "why-is-node-running": "^2.2.2"
+};
+var scripts = {
+ test: "standard && npm run transpile && tap test/*.test.*js && tap --ts test/*.test.*ts",
+ "test:ci": "standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts",
+ "test:ci:js": "tap --no-check-coverage --coverage-report=lcovonly \"test/**/*.test.*js\"",
+ "test:ci:ts": "tap --ts --no-check-coverage --coverage-report=lcovonly \"test/**/*.test.*ts\"",
+ "test:yarn": "npm run transpile && tap \"test/**/*.test.js\" --no-check-coverage",
+ transpile: "sh ./test/ts/transpile.sh",
+ prepare: "husky install"
+};
+var standard = {
+ ignore: [
+ "test/ts/**/*"
+ ]
+};
+var repository = {
+ type: "git",
+ url: "git+https://github.com/mcollina/thread-stream.git"
+};
+var keywords = [
+ "worker",
+ "thread",
+ "threads",
+ "stream"
+];
+var author = "Matteo Collina ";
+var license = "MIT";
+var bugs = {
+ url: "https://github.com/mcollina/thread-stream/issues"
+};
+var homepage = "https://github.com/mcollina/thread-stream#readme";
+var require$$0 = {
+ name: name,
+ version: version$4,
+ description: description,
+ main: main,
+ types: types,
+ dependencies: dependencies,
+ devDependencies: devDependencies,
+ scripts: scripts,
+ standard: standard,
+ repository: repository,
+ keywords: keywords,
+ author: author,
+ license: license,
+ bugs: bugs,
+ homepage: homepage
+};
+
+const MAX_TIMEOUT = 1000;
+
+function wait$1 (state, index, expected, timeout, done) {
+ const max = Date.now() + timeout;
+ let current = Atomics.load(state, index);
+ if (current === expected) {
+ done(null, 'ok');
+ return
+ }
+ let prior = current;
+ const check = (backoff) => {
+ if (Date.now() > max) {
+ done(null, 'timed-out');
+ } else {
+ setTimeout(() => {
+ prior = current;
+ current = Atomics.load(state, index);
+ if (current === prior) {
+ check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2);
+ } else {
+ if (current === expected) done(null, 'ok');
+ else done(null, 'not-equal');
+ }
+ }, backoff);
+ }
+ };
+ check(1);
+}
+
+// let waitDiffCount = 0
+function waitDiff (state, index, expected, timeout, done) {
+ // const id = waitDiffCount++
+ // process._rawDebug(`>>> waitDiff ${id}`)
+ const max = Date.now() + timeout;
+ let current = Atomics.load(state, index);
+ if (current !== expected) {
+ done(null, 'ok');
+ return
+ }
+ const check = (backoff) => {
+ // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)
+ // process._rawDebug('' + backoff)
+ if (Date.now() > max) {
+ done(null, 'timed-out');
+ } else {
+ setTimeout(() => {
+ current = Atomics.load(state, index);
+ if (current !== expected) {
+ done(null, 'ok');
+ } else {
+ check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2);
+ }
+ }, backoff);
+ }
+ };
+ check(1);
+}
+
+var wait_1 = { wait: wait$1, waitDiff };
+
+const WRITE_INDEX$1 = 4;
+const READ_INDEX$1 = 8;
+
+var indexes = {
+ WRITE_INDEX: WRITE_INDEX$1,
+ READ_INDEX: READ_INDEX$1
+};
+
+const { version: version$3 } = require$$0;
+const { EventEmitter: EventEmitter$2 } = require$$0$f;
+const { Worker } = require$$2$8;
+const { join: join$1 } = require$$0$c;
+const { pathToFileURL } = Url$2;
+const { wait } = wait_1;
+const {
+ WRITE_INDEX,
+ READ_INDEX
+} = indexes;
+const buffer = require$$0$i;
+const assert = require$$5$2;
+
+const kImpl = Symbol('kImpl');
+
+// V8 limit for string size
+const MAX_STRING = buffer.constants.MAX_STRING_LENGTH;
+
+class FakeWeakRef {
+ constructor (value) {
+ this._value = value;
+ }
+
+ deref () {
+ return this._value
+ }
+}
+
+const FinalizationRegistry$1 = commonjsGlobal.FinalizationRegistry || class FakeFinalizationRegistry {
+ register () {}
+
+ unregister () {}
+};
+
+const WeakRef$1 = commonjsGlobal.WeakRef || FakeWeakRef;
+
+const registry = new FinalizationRegistry$1((worker) => {
+ if (worker.exited) {
+ return
+ }
+ worker.terminate();
+});
+
+function createWorker (stream, opts) {
+ const { filename, workerData } = opts;
+
+ const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {};
+ const toExecute = bundlerOverrides['thread-stream-worker'] || join$1(__dirname, 'lib', 'worker.js');
+
+ const worker = new Worker(toExecute, {
+ ...opts.workerOpts,
+ trackUnmanagedFds: false,
+ workerData: {
+ filename: filename.indexOf('file://') === 0
+ ? filename
+ : pathToFileURL(filename).href,
+ dataBuf: stream[kImpl].dataBuf,
+ stateBuf: stream[kImpl].stateBuf,
+ workerData: {
+ $context: {
+ threadStreamVersion: version$3
+ },
+ ...workerData
+ }
+ }
+ });
+
+ // We keep a strong reference for now,
+ // we need to start writing first
+ worker.stream = new FakeWeakRef(stream);
+
+ worker.on('message', onWorkerMessage);
+ worker.on('exit', onWorkerExit);
+ registry.register(stream, worker);
+
+ return worker
+}
+
+function drain (stream) {
+ assert(!stream[kImpl].sync);
+ if (stream[kImpl].needDrain) {
+ stream[kImpl].needDrain = false;
+ stream.emit('drain');
+ }
+}
+
+function nextFlush (stream) {
+ const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX);
+ let leftover = stream[kImpl].data.length - writeIndex;
+
+ if (leftover > 0) {
+ if (stream[kImpl].buf.length === 0) {
+ stream[kImpl].flushing = false;
+
+ if (stream[kImpl].ending) {
+ end(stream);
+ } else if (stream[kImpl].needDrain) {
+ process.nextTick(drain, stream);
+ }
+
+ return
+ }
+
+ let toWrite = stream[kImpl].buf.slice(0, leftover);
+ let toWriteBytes = Buffer.byteLength(toWrite);
+ if (toWriteBytes <= leftover) {
+ stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
+ // process._rawDebug('writing ' + toWrite.length)
+ write$1(stream, toWrite, nextFlush.bind(null, stream));
+ } else {
+ // multi-byte utf-8
+ stream.flush(() => {
+ // err is already handled in flush()
+ if (stream.destroyed) {
+ return
+ }
+
+ Atomics.store(stream[kImpl].state, READ_INDEX, 0);
+ Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
+
+ // Find a toWrite length that fits the buffer
+ // it must exists as the buffer is at least 4 bytes length
+ // and the max utf-8 length for a char is 4 bytes.
+ while (toWriteBytes > stream[kImpl].data.length) {
+ leftover = leftover / 2;
+ toWrite = stream[kImpl].buf.slice(0, leftover);
+ toWriteBytes = Buffer.byteLength(toWrite);
+ }
+ stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
+ write$1(stream, toWrite, nextFlush.bind(null, stream));
+ });
+ }
+ } else if (leftover === 0) {
+ if (writeIndex === 0 && stream[kImpl].buf.length === 0) {
+ // we had a flushSync in the meanwhile
+ return
+ }
+ stream.flush(() => {
+ Atomics.store(stream[kImpl].state, READ_INDEX, 0);
+ Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
+ nextFlush(stream);
+ });
+ } else {
+ // This should never happen
+ destroy(stream, new Error('overwritten'));
+ }
+}
+
+function onWorkerMessage (msg) {
+ const stream = this.stream.deref();
+ if (stream === undefined) {
+ this.exited = true;
+ // Terminate the worker.
+ this.terminate();
+ return
+ }
+
+ switch (msg.code) {
+ case 'READY':
+ // Replace the FakeWeakRef with a
+ // proper one.
+ this.stream = new WeakRef$1(stream);
+
+ stream.flush(() => {
+ stream[kImpl].ready = true;
+ stream.emit('ready');
+ });
+ break
+ case 'ERROR':
+ destroy(stream, msg.err);
+ break
+ case 'EVENT':
+ if (Array.isArray(msg.args)) {
+ stream.emit(msg.name, ...msg.args);
+ } else {
+ stream.emit(msg.name, msg.args);
+ }
+ break
+ default:
+ destroy(stream, new Error('this should not happen: ' + msg.code));
+ }
+}
+
+function onWorkerExit (code) {
+ const stream = this.stream.deref();
+ if (stream === undefined) {
+ // Nothing to do, the worker already exit
+ return
+ }
+ registry.unregister(stream);
+ stream.worker.exited = true;
+ stream.worker.off('exit', onWorkerExit);
+ destroy(stream, code !== 0 ? new Error('the worker thread exited') : null);
+}
+
+let ThreadStream$1 = class ThreadStream extends EventEmitter$2 {
+ constructor (opts = {}) {
+ super();
+
+ if (opts.bufferSize < 4) {
+ throw new Error('bufferSize must at least fit a 4-byte utf-8 char')
+ }
+
+ this[kImpl] = {};
+ this[kImpl].stateBuf = new SharedArrayBuffer(128);
+ this[kImpl].state = new Int32Array(this[kImpl].stateBuf);
+ this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024);
+ this[kImpl].data = Buffer.from(this[kImpl].dataBuf);
+ this[kImpl].sync = opts.sync || false;
+ this[kImpl].ending = false;
+ this[kImpl].ended = false;
+ this[kImpl].needDrain = false;
+ this[kImpl].destroyed = false;
+ this[kImpl].flushing = false;
+ this[kImpl].ready = false;
+ this[kImpl].finished = false;
+ this[kImpl].errored = null;
+ this[kImpl].closed = false;
+ this[kImpl].buf = '';
+
+ // TODO (fix): Make private?
+ this.worker = createWorker(this, opts); // TODO (fix): make private
+ }
+
+ write (data) {
+ if (this[kImpl].destroyed) {
+ error(this, new Error('the worker has exited'));
+ return false
+ }
+
+ if (this[kImpl].ending) {
+ error(this, new Error('the worker is ending'));
+ return false
+ }
+
+ if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {
+ try {
+ writeSync(this);
+ this[kImpl].flushing = true;
+ } catch (err) {
+ destroy(this, err);
+ return false
+ }
+ }
+
+ this[kImpl].buf += data;
+
+ if (this[kImpl].sync) {
+ try {
+ writeSync(this);
+ return true
+ } catch (err) {
+ destroy(this, err);
+ return false
+ }
+ }
+
+ if (!this[kImpl].flushing) {
+ this[kImpl].flushing = true;
+ setImmediate(nextFlush, this);
+ }
+
+ this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0;
+ return !this[kImpl].needDrain
+ }
+
+ end () {
+ if (this[kImpl].destroyed) {
+ return
+ }
+
+ this[kImpl].ending = true;
+ end(this);
+ }
+
+ flush (cb) {
+ if (this[kImpl].destroyed) {
+ if (typeof cb === 'function') {
+ process.nextTick(cb, new Error('the worker has exited'));
+ }
+ return
+ }
+
+ // TODO write all .buf
+ const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX);
+ // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)
+ wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {
+ if (err) {
+ destroy(this, err);
+ process.nextTick(cb, err);
+ return
+ }
+ if (res === 'not-equal') {
+ // TODO handle deadlock
+ this.flush(cb);
+ return
+ }
+ process.nextTick(cb);
+ });
+ }
+
+ flushSync () {
+ if (this[kImpl].destroyed) {
+ return
+ }
+
+ writeSync(this);
+ flushSync(this);
+ }
+
+ unref () {
+ this.worker.unref();
+ }
+
+ ref () {
+ this.worker.ref();
+ }
+
+ get ready () {
+ return this[kImpl].ready
+ }
+
+ get destroyed () {
+ return this[kImpl].destroyed
+ }
+
+ get closed () {
+ return this[kImpl].closed
+ }
+
+ get writable () {
+ return !this[kImpl].destroyed && !this[kImpl].ending
+ }
+
+ get writableEnded () {
+ return this[kImpl].ending
+ }
+
+ get writableFinished () {
+ return this[kImpl].finished
+ }
+
+ get writableNeedDrain () {
+ return this[kImpl].needDrain
+ }
+
+ get writableObjectMode () {
+ return false
+ }
+
+ get writableErrored () {
+ return this[kImpl].errored
+ }
+};
+
+function error (stream, err) {
+ setImmediate(() => {
+ stream.emit('error', err);
+ });
+}
+
+function destroy (stream, err) {
+ if (stream[kImpl].destroyed) {
+ return
+ }
+ stream[kImpl].destroyed = true;
+
+ if (err) {
+ stream[kImpl].errored = err;
+ error(stream, err);
+ }
+
+ if (!stream.worker.exited) {
+ stream.worker.terminate()
+ .catch(() => {})
+ .then(() => {
+ stream[kImpl].closed = true;
+ stream.emit('close');
+ });
+ } else {
+ setImmediate(() => {
+ stream[kImpl].closed = true;
+ stream.emit('close');
+ });
+ }
+}
+
+function write$1 (stream, data, cb) {
+ // data is smaller than the shared buffer length
+ const current = Atomics.load(stream[kImpl].state, WRITE_INDEX);
+ const length = Buffer.byteLength(data);
+ stream[kImpl].data.write(data, current);
+ Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length);
+ Atomics.notify(stream[kImpl].state, WRITE_INDEX);
+ cb();
+ return true
+}
+
+function end (stream) {
+ if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {
+ return
+ }
+ stream[kImpl].ended = true;
+
+ try {
+ stream.flushSync();
+
+ let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX);
+
+ // process._rawDebug('writing index')
+ Atomics.store(stream[kImpl].state, WRITE_INDEX, -1);
+ // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)
+ Atomics.notify(stream[kImpl].state, WRITE_INDEX);
+
+ // Wait for the process to complete
+ let spins = 0;
+ while (readIndex !== -1) {
+ // process._rawDebug(`read = ${read}`)
+ Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000);
+ readIndex = Atomics.load(stream[kImpl].state, READ_INDEX);
+
+ if (readIndex === -2) {
+ destroy(stream, new Error('end() failed'));
+ return
+ }
+
+ if (++spins === 10) {
+ destroy(stream, new Error('end() took too long (10s)'));
+ return
+ }
+ }
+
+ process.nextTick(() => {
+ stream[kImpl].finished = true;
+ stream.emit('finish');
+ });
+ } catch (err) {
+ destroy(stream, err);
+ }
+ // process._rawDebug('end finished...')
+}
+
+function writeSync (stream) {
+ const cb = () => {
+ if (stream[kImpl].ending) {
+ end(stream);
+ } else if (stream[kImpl].needDrain) {
+ process.nextTick(drain, stream);
+ }
+ };
+ stream[kImpl].flushing = false;
+
+ while (stream[kImpl].buf.length !== 0) {
+ const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX);
+ let leftover = stream[kImpl].data.length - writeIndex;
+ if (leftover === 0) {
+ flushSync(stream);
+ Atomics.store(stream[kImpl].state, READ_INDEX, 0);
+ Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
+ continue
+ } else if (leftover < 0) {
+ // stream should never happen
+ throw new Error('overwritten')
+ }
+
+ let toWrite = stream[kImpl].buf.slice(0, leftover);
+ let toWriteBytes = Buffer.byteLength(toWrite);
+ if (toWriteBytes <= leftover) {
+ stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
+ // process._rawDebug('writing ' + toWrite.length)
+ write$1(stream, toWrite, cb);
+ } else {
+ // multi-byte utf-8
+ flushSync(stream);
+ Atomics.store(stream[kImpl].state, READ_INDEX, 0);
+ Atomics.store(stream[kImpl].state, WRITE_INDEX, 0);
+
+ // Find a toWrite length that fits the buffer
+ // it must exists as the buffer is at least 4 bytes length
+ // and the max utf-8 length for a char is 4 bytes.
+ while (toWriteBytes > stream[kImpl].buf.length) {
+ leftover = leftover / 2;
+ toWrite = stream[kImpl].buf.slice(0, leftover);
+ toWriteBytes = Buffer.byteLength(toWrite);
+ }
+ stream[kImpl].buf = stream[kImpl].buf.slice(leftover);
+ write$1(stream, toWrite, cb);
+ }
+ }
+}
+
+function flushSync (stream) {
+ if (stream[kImpl].flushing) {
+ throw new Error('unable to flush while flushing')
+ }
+
+ // process._rawDebug('flushSync started')
+
+ const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX);
+
+ let spins = 0;
+
+ // TODO handle deadlock
+ while (true) {
+ const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX);
+
+ if (readIndex === -2) {
+ throw Error('_flushSync failed')
+ }
+
+ // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)
+ if (readIndex !== writeIndex) {
+ // TODO stream timeouts for some reason.
+ Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000);
+ } else {
+ break
+ }
+
+ if (++spins === 10) {
+ throw new Error('_flushSync took too long (10s)')
+ }
+ }
+ // process._rawDebug('flushSync finished')
+}
+
+var threadStream = ThreadStream$1;
+
+const { createRequire } = require$$0$n;
+const getCallers = caller$1;
+const { join, isAbsolute } = require$$0$c;
+const sleep = atomicSleepExports;
+const onExit$1 = onExitLeakFree;
+const ThreadStream = threadStream;
+
+function setupOnExit (stream) {
+ // This is leak free, it does not leave event handlers
+ onExit$1.register(stream, autoEnd$1);
+ onExit$1.registerBeforeExit(stream, flush$1);
+
+ stream.on('close', function () {
+ onExit$1.unregister(stream);
+ });
+}
+
+function buildStream (filename, workerData, workerOpts) {
+ const stream = new ThreadStream({
+ filename,
+ workerData,
+ workerOpts
+ });
+
+ stream.on('ready', onReady);
+ stream.on('close', function () {
+ process.removeListener('exit', onExit);
+ });
+
+ process.on('exit', onExit);
+
+ function onReady () {
+ process.removeListener('exit', onExit);
+ stream.unref();
+
+ if (workerOpts.autoEnd !== false) {
+ setupOnExit(stream);
+ }
+ }
+
+ function onExit () {
+ /* istanbul ignore next */
+ if (stream.closed) {
+ return
+ }
+ stream.flushSync();
+ // Apparently there is a very sporadic race condition
+ // that in certain OS would prevent the messages to be flushed
+ // because the thread might not have been created still.
+ // Unfortunately we need to sleep(100) in this case.
+ sleep(100);
+ stream.end();
+ }
+
+ return stream
+}
+
+function autoEnd$1 (stream) {
+ stream.ref();
+ stream.flushSync();
+ stream.end();
+ stream.once('close', function () {
+ stream.unref();
+ });
+}
+
+function flush$1 (stream) {
+ stream.flushSync();
+}
+
+function transport$3 (fullOptions) {
+ const { pipeline, targets, levels, dedupe, options = {}, worker = {}, caller = getCallers() } = fullOptions;
+
+ // Backwards compatibility
+ const callers = typeof caller === 'string' ? [caller] : caller;
+
+ // This will be eventually modified by bundlers
+ const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {};
+
+ let target = fullOptions.target;
+
+ if (target && targets) {
+ throw new Error('only one of target or targets can be specified')
+ }
+
+ if (targets) {
+ target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js');
+ options.targets = targets.map((dest) => {
+ return {
+ ...dest,
+ target: fixTarget(dest.target)
+ }
+ });
+ } else if (pipeline) {
+ target = bundlerOverrides['pino-pipeline-worker'] || join(__dirname, 'worker-pipeline.js');
+ options.targets = pipeline.map((dest) => {
+ return {
+ ...dest,
+ target: fixTarget(dest.target)
+ }
+ });
+ }
+
+ if (levels) {
+ options.levels = levels;
+ }
+
+ if (dedupe) {
+ options.dedupe = dedupe;
+ }
+
+ return buildStream(fixTarget(target), options, worker)
+
+ function fixTarget (origin) {
+ origin = bundlerOverrides[origin] || origin;
+
+ if (isAbsolute(origin) || origin.indexOf('file://') === 0) {
+ return origin
+ }
+
+ if (origin === 'pino/file') {
+ return join(__dirname, '..', 'file.js')
+ }
+
+ let fixTarget;
+
+ for (const filePath of callers) {
+ try {
+ fixTarget = createRequire(filePath).resolve(origin);
+ break
+ } catch (err) {
+ // Silent catch
+ continue
+ }
+ }
+
+ if (!fixTarget) {
+ throw new Error(`unable to determine transport target for "${origin}"`)
+ }
+
+ return fixTarget
+ }
+}
+
+var transport_1 = transport$3;
+
+/* eslint no-prototype-builtins: 0 */
+
+const format = quickFormatUnescaped;
+const { mapHttpRequest, mapHttpResponse } = pinoStdSerializers;
+const SonicBoom = sonicBoom;
+const onExit = onExitLeakFree;
+const {
+ lsCacheSym: lsCacheSym$2,
+ chindingsSym: chindingsSym$2,
+ writeSym: writeSym$1,
+ serializersSym: serializersSym$2,
+ formatOptsSym: formatOptsSym$2,
+ endSym: endSym$1,
+ stringifiersSym: stringifiersSym$2,
+ stringifySym: stringifySym$2,
+ stringifySafeSym: stringifySafeSym$1,
+ wildcardFirstSym,
+ nestedKeySym: nestedKeySym$1,
+ formattersSym: formattersSym$3,
+ messageKeySym: messageKeySym$1,
+ errorKeySym: errorKeySym$2,
+ nestedKeyStrSym: nestedKeyStrSym$1,
+ msgPrefixSym: msgPrefixSym$2
+} = symbols$1;
+const { isMainThread } = require$$2$8;
+const transport$2 = transport_1;
+
+function noop$3 () {
+}
+
+function genLog$1 (level, hook) {
+ if (!hook) return LOG
+
+ return function hookWrappedLog (...args) {
+ hook.call(this, args, LOG, level);
+ }
+
+ function LOG (o, ...n) {
+ if (typeof o === 'object') {
+ let msg = o;
+ if (o !== null) {
+ if (o.method && o.headers && o.socket) {
+ o = mapHttpRequest(o);
+ } else if (typeof o.setHeader === 'function') {
+ o = mapHttpResponse(o);
+ }
+ }
+ let formatParams;
+ if (msg === null && n.length === 0) {
+ formatParams = [null];
+ } else {
+ msg = n.shift();
+ formatParams = n;
+ }
+ // We do not use a coercive check for `msg` as it is
+ // measurably slower than the explicit checks.
+ if (typeof this[msgPrefixSym$2] === 'string' && msg !== undefined && msg !== null) {
+ msg = this[msgPrefixSym$2] + msg;
+ }
+ this[writeSym$1](o, format(msg, formatParams, this[formatOptsSym$2]), level);
+ } else {
+ let msg = o === undefined ? n.shift() : o;
+
+ // We do not use a coercive check for `msg` as it is
+ // measurably slower than the explicit checks.
+ if (typeof this[msgPrefixSym$2] === 'string' && msg !== undefined && msg !== null) {
+ msg = this[msgPrefixSym$2] + msg;
+ }
+ this[writeSym$1](null, format(msg, n, this[formatOptsSym$2]), level);
+ }
+ }
+}
+
+// magically escape strings for json
+// relying on their charCodeAt
+// everything below 32 needs JSON.stringify()
+// 34 and 92 happens all the time, so we
+// have a fast case for them
+function asString (str) {
+ let result = '';
+ let last = 0;
+ let found = false;
+ let point = 255;
+ const l = str.length;
+ if (l > 100) {
+ return JSON.stringify(str)
+ }
+ for (var i = 0; i < l && point >= 32; i++) {
+ point = str.charCodeAt(i);
+ if (point === 34 || point === 92) {
+ result += str.slice(last, i) + '\\';
+ last = i;
+ found = true;
+ }
+ }
+ if (!found) {
+ result = str;
+ } else {
+ result += str.slice(last);
+ }
+ return point < 32 ? JSON.stringify(str) : '"' + result + '"'
+}
+
+function asJson$1 (obj, msg, num, time) {
+ const stringify = this[stringifySym$2];
+ const stringifySafe = this[stringifySafeSym$1];
+ const stringifiers = this[stringifiersSym$2];
+ const end = this[endSym$1];
+ const chindings = this[chindingsSym$2];
+ const serializers = this[serializersSym$2];
+ const formatters = this[formattersSym$3];
+ const messageKey = this[messageKeySym$1];
+ const errorKey = this[errorKeySym$2];
+ let data = this[lsCacheSym$2][num] + time;
+
+ // we need the child bindings added to the output first so instance logged
+ // objects can take precedence when JSON.parse-ing the resulting log line
+ data = data + chindings;
+
+ let value;
+ if (formatters.log) {
+ obj = formatters.log(obj);
+ }
+ const wildcardStringifier = stringifiers[wildcardFirstSym];
+ let propStr = '';
+ for (const key in obj) {
+ value = obj[key];
+ if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {
+ if (serializers[key]) {
+ value = serializers[key](value);
+ } else if (key === errorKey && serializers.err) {
+ value = serializers.err(value);
+ }
+
+ const stringifier = stringifiers[key] || wildcardStringifier;
+
+ switch (typeof value) {
+ case 'undefined':
+ case 'function':
+ continue
+ case 'number':
+ /* eslint no-fallthrough: "off" */
+ if (Number.isFinite(value) === false) {
+ value = null;
+ }
+ // this case explicitly falls through to the next one
+ case 'boolean':
+ if (stringifier) value = stringifier(value);
+ break
+ case 'string':
+ value = (stringifier || asString)(value);
+ break
+ default:
+ value = (stringifier || stringify)(value, stringifySafe);
+ }
+ if (value === undefined) continue
+ propStr += ',"' + key + '":' + value;
+ }
+ }
+
+ let msgStr = '';
+ if (msg !== undefined) {
+ value = serializers[messageKey] ? serializers[messageKey](msg) : msg;
+ const stringifier = stringifiers[messageKey] || wildcardStringifier;
+
+ switch (typeof value) {
+ case 'function':
+ break
+ case 'number':
+ /* eslint no-fallthrough: "off" */
+ if (Number.isFinite(value) === false) {
+ value = null;
+ }
+ // this case explicitly falls through to the next one
+ case 'boolean':
+ if (stringifier) value = stringifier(value);
+ msgStr = ',"' + messageKey + '":' + value;
+ break
+ case 'string':
+ value = (stringifier || asString)(value);
+ msgStr = ',"' + messageKey + '":' + value;
+ break
+ default:
+ value = (stringifier || stringify)(value, stringifySafe);
+ msgStr = ',"' + messageKey + '":' + value;
+ }
+ }
+
+ if (this[nestedKeySym$1] && propStr) {
+ // place all the obj properties under the specified key
+ // the nested key is already formatted from the constructor
+ return data + this[nestedKeyStrSym$1] + propStr.slice(1) + '}' + msgStr + end
+ } else {
+ return data + propStr + msgStr + end
+ }
+}
+
+function asChindings$2 (instance, bindings) {
+ let value;
+ let data = instance[chindingsSym$2];
+ const stringify = instance[stringifySym$2];
+ const stringifySafe = instance[stringifySafeSym$1];
+ const stringifiers = instance[stringifiersSym$2];
+ const wildcardStringifier = stringifiers[wildcardFirstSym];
+ const serializers = instance[serializersSym$2];
+ const formatter = instance[formattersSym$3].bindings;
+ bindings = formatter(bindings);
+
+ for (const key in bindings) {
+ value = bindings[key];
+ const valid = key !== 'level' &&
+ key !== 'serializers' &&
+ key !== 'formatters' &&
+ key !== 'customLevels' &&
+ bindings.hasOwnProperty(key) &&
+ value !== undefined;
+ if (valid === true) {
+ value = serializers[key] ? serializers[key](value) : value;
+ value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe);
+ if (value === undefined) continue
+ data += ',"' + key + '":' + value;
+ }
+ }
+ return data
+}
+
+function hasBeenTampered (stream) {
+ return stream.write !== stream.constructor.prototype.write
+}
+
+function buildSafeSonicBoom$1 (opts) {
+ const stream = new SonicBoom(opts);
+ stream.on('error', filterBrokenPipe);
+ // if we are sync: false, we must flush on exit
+ if (!opts.sync && isMainThread) {
+ onExit.register(stream, autoEnd);
+
+ stream.on('close', function () {
+ onExit.unregister(stream);
+ });
+ }
+ return stream
+
+ function filterBrokenPipe (err) {
+ // Impossible to replicate across all operating systems
+ /* istanbul ignore next */
+ if (err.code === 'EPIPE') {
+ // If we get EPIPE, we should stop logging here
+ // however we have no control to the consumer of
+ // SonicBoom, so we just overwrite the write method
+ stream.write = noop$3;
+ stream.end = noop$3;
+ stream.flushSync = noop$3;
+ stream.destroy = noop$3;
+ return
+ }
+ stream.removeListener('error', filterBrokenPipe);
+ stream.emit('error', err);
+ }
+}
+
+function autoEnd (stream, eventName) {
+ // This check is needed only on some platforms
+ /* istanbul ignore next */
+ if (stream.destroyed) {
+ return
+ }
+
+ if (eventName === 'beforeExit') {
+ // We still have an event loop, let's use it
+ stream.flush();
+ stream.on('drain', function () {
+ stream.end();
+ });
+ } else {
+ // For some reason istanbul is not detecting this, but it's there
+ /* istanbul ignore next */
+ // We do not have an event loop, so flush synchronously
+ stream.flushSync();
+ }
+}
+
+function createArgsNormalizer$1 (defaultOptions) {
+ return function normalizeArgs (instance, caller, opts = {}, stream) {
+ // support stream as a string
+ if (typeof opts === 'string') {
+ stream = buildSafeSonicBoom$1({ dest: opts });
+ opts = {};
+ } else if (typeof stream === 'string') {
+ if (opts && opts.transport) {
+ throw Error('only one of option.transport or stream can be specified')
+ }
+ stream = buildSafeSonicBoom$1({ dest: stream });
+ } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {
+ stream = opts;
+ opts = {};
+ } else if (opts.transport) {
+ if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {
+ throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')
+ }
+ if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {
+ throw Error('option.transport.targets do not allow custom level formatters')
+ }
+
+ let customLevels;
+ if (opts.customLevels) {
+ customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels);
+ }
+ stream = transport$2({ caller, ...opts.transport, levels: customLevels });
+ }
+ opts = Object.assign({}, defaultOptions, opts);
+ opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers);
+ opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters);
+
+ if (opts.prettyPrint) {
+ throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')
+ }
+
+ const { enabled, onChild } = opts;
+ if (enabled === false) opts.level = 'silent';
+ if (!onChild) opts.onChild = noop$3;
+ if (!stream) {
+ if (!hasBeenTampered(process.stdout)) {
+ // If process.stdout.fd is undefined, it means that we are running
+ // in a worker thread. Let's assume we are logging to file descriptor 1.
+ stream = buildSafeSonicBoom$1({ fd: process.stdout.fd || 1 });
+ } else {
+ stream = process.stdout;
+ }
+ }
+ return { opts, stream }
+ }
+}
+
+function stringify$3 (obj, stringifySafeFn) {
+ try {
+ return JSON.stringify(obj)
+ } catch (_) {
+ try {
+ const stringify = stringifySafeFn || this[stringifySafeSym$1];
+ return stringify(obj)
+ } catch (_) {
+ return '"[unable to serialize, circular reference is too complex to analyze]"'
+ }
+ }
+}
+
+function buildFormatters$2 (level, bindings, log) {
+ return {
+ level,
+ bindings,
+ log
+ }
+}
+
+/**
+ * Convert a string integer file descriptor to a proper native integer
+ * file descriptor.
+ *
+ * @param {string} destination The file descriptor string to attempt to convert.
+ *
+ * @returns {Number}
+ */
+function normalizeDestFileDescriptor$1 (destination) {
+ const fd = Number(destination);
+ if (typeof destination === 'string' && Number.isFinite(fd)) {
+ return fd
+ }
+ // destination could be undefined if we are in a worker
+ if (destination === undefined) {
+ // This is stdout in UNIX systems
+ return 1
+ }
+ return destination
+}
+
+var tools = {
+ noop: noop$3,
+ buildSafeSonicBoom: buildSafeSonicBoom$1,
+ asChindings: asChindings$2,
+ asJson: asJson$1,
+ genLog: genLog$1,
+ createArgsNormalizer: createArgsNormalizer$1,
+ stringify: stringify$3,
+ buildFormatters: buildFormatters$2,
+ normalizeDestFileDescriptor: normalizeDestFileDescriptor$1
+};
+
+/* eslint no-prototype-builtins: 0 */
+const {
+ lsCacheSym: lsCacheSym$1,
+ levelValSym: levelValSym$1,
+ useOnlyCustomLevelsSym: useOnlyCustomLevelsSym$2,
+ streamSym: streamSym$2,
+ formattersSym: formattersSym$2,
+ hooksSym: hooksSym$1
+} = symbols$1;
+const { noop: noop$2, genLog } = tools;
+
+const levels$1 = {
+ trace: 10,
+ debug: 20,
+ info: 30,
+ warn: 40,
+ error: 50,
+ fatal: 60
+};
+const levelMethods = {
+ fatal: (hook) => {
+ const logFatal = genLog(levels$1.fatal, hook);
+ return function (...args) {
+ const stream = this[streamSym$2];
+ logFatal.call(this, ...args);
+ if (typeof stream.flushSync === 'function') {
+ try {
+ stream.flushSync();
+ } catch (e) {
+ // https://github.com/pinojs/pino/pull/740#discussion_r346788313
+ }
+ }
+ }
+ },
+ error: (hook) => genLog(levels$1.error, hook),
+ warn: (hook) => genLog(levels$1.warn, hook),
+ info: (hook) => genLog(levels$1.info, hook),
+ debug: (hook) => genLog(levels$1.debug, hook),
+ trace: (hook) => genLog(levels$1.trace, hook)
+};
+
+const nums = Object.keys(levels$1).reduce((o, k) => {
+ o[levels$1[k]] = k;
+ return o
+}, {});
+
+const initialLsCache$1 = Object.keys(nums).reduce((o, k) => {
+ o[k] = '{"level":' + Number(k);
+ return o
+}, {});
+
+function genLsCache$2 (instance) {
+ const formatter = instance[formattersSym$2].level;
+ const { labels } = instance.levels;
+ const cache = {};
+ for (const label in labels) {
+ const level = formatter(labels[label], Number(label));
+ cache[label] = JSON.stringify(level).slice(0, -1);
+ }
+ instance[lsCacheSym$1] = cache;
+ return instance
+}
+
+function isStandardLevel (level, useOnlyCustomLevels) {
+ if (useOnlyCustomLevels) {
+ return false
+ }
+
+ switch (level) {
+ case 'fatal':
+ case 'error':
+ case 'warn':
+ case 'info':
+ case 'debug':
+ case 'trace':
+ return true
+ default:
+ return false
+ }
+}
+
+function setLevel$1 (level) {
+ const { labels, values } = this.levels;
+ if (typeof level === 'number') {
+ if (labels[level] === undefined) throw Error('unknown level value' + level)
+ level = labels[level];
+ }
+ if (values[level] === undefined) throw Error('unknown level ' + level)
+ const preLevelVal = this[levelValSym$1];
+ const levelVal = this[levelValSym$1] = values[level];
+ const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym$2];
+ const hook = this[hooksSym$1].logMethod;
+
+ for (const key in values) {
+ if (levelVal > values[key]) {
+ this[key] = noop$2;
+ continue
+ }
+ this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook);
+ }
+
+ this.emit(
+ 'level-change',
+ level,
+ levelVal,
+ labels[preLevelVal],
+ preLevelVal,
+ this
+ );
+}
+
+function getLevel$1 (level) {
+ const { levels, levelVal } = this;
+ // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)
+ return (levels && levels.labels) ? levels.labels[levelVal] : ''
+}
+
+function isLevelEnabled$1 (logLevel) {
+ const { values } = this.levels;
+ const logLevelVal = values[logLevel];
+ return logLevelVal !== undefined && (logLevelVal >= this[levelValSym$1])
+}
+
+function mappings$2 (customLevels = null, useOnlyCustomLevels = false) {
+ const customNums = customLevels
+ /* eslint-disable */
+ ? Object.keys(customLevels).reduce((o, k) => {
+ o[customLevels[k]] = k;
+ return o
+ }, {})
+ : null;
+ /* eslint-enable */
+
+ const labels = Object.assign(
+ Object.create(Object.prototype, { Infinity: { value: 'silent' } }),
+ useOnlyCustomLevels ? null : nums,
+ customNums
+ );
+ const values = Object.assign(
+ Object.create(Object.prototype, { silent: { value: Infinity } }),
+ useOnlyCustomLevels ? null : levels$1,
+ customLevels
+ );
+ return { labels, values }
+}
+
+function assertDefaultLevelFound$1 (defaultLevel, customLevels, useOnlyCustomLevels) {
+ if (typeof defaultLevel === 'number') {
+ const values = [].concat(
+ Object.keys(customLevels || {}).map(key => customLevels[key]),
+ useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),
+ Infinity
+ );
+ if (!values.includes(defaultLevel)) {
+ throw Error(`default level:${defaultLevel} must be included in custom levels`)
+ }
+ return
+ }
+
+ const labels = Object.assign(
+ Object.create(Object.prototype, { silent: { value: Infinity } }),
+ useOnlyCustomLevels ? null : levels$1,
+ customLevels
+ );
+ if (!(defaultLevel in labels)) {
+ throw Error(`default level:${defaultLevel} must be included in custom levels`)
+ }
+}
+
+function assertNoLevelCollisions$1 (levels, customLevels) {
+ const { labels, values } = levels;
+ for (const k in customLevels) {
+ if (k in values) {
+ throw Error('levels cannot be overridden')
+ }
+ if (customLevels[k] in labels) {
+ throw Error('pre-existing level values cannot be used for new levels')
+ }
+ }
+}
+
+var levels_1 = {
+ initialLsCache: initialLsCache$1,
+ genLsCache: genLsCache$2,
+ levelMethods,
+ getLevel: getLevel$1,
+ setLevel: setLevel$1,
+ isLevelEnabled: isLevelEnabled$1,
+ mappings: mappings$2,
+ levels: levels$1,
+ assertNoLevelCollisions: assertNoLevelCollisions$1,
+ assertDefaultLevelFound: assertDefaultLevelFound$1
+};
+
+var meta = { version: '8.10.0' };
+
+/* eslint no-prototype-builtins: 0 */
+
+const { EventEmitter: EventEmitter$1 } = require$$0$f;
+const {
+ lsCacheSym,
+ levelValSym,
+ setLevelSym: setLevelSym$1,
+ getLevelSym,
+ chindingsSym: chindingsSym$1,
+ parsedChindingsSym,
+ mixinSym: mixinSym$1,
+ asJsonSym,
+ writeSym,
+ mixinMergeStrategySym: mixinMergeStrategySym$1,
+ timeSym: timeSym$1,
+ timeSliceIndexSym: timeSliceIndexSym$1,
+ streamSym: streamSym$1,
+ serializersSym: serializersSym$1,
+ formattersSym: formattersSym$1,
+ errorKeySym: errorKeySym$1,
+ useOnlyCustomLevelsSym: useOnlyCustomLevelsSym$1,
+ needsMetadataGsym,
+ redactFmtSym: redactFmtSym$1,
+ stringifySym: stringifySym$1,
+ formatOptsSym: formatOptsSym$1,
+ stringifiersSym: stringifiersSym$1,
+ msgPrefixSym: msgPrefixSym$1
+} = symbols$1;
+const {
+ getLevel,
+ setLevel,
+ isLevelEnabled,
+ mappings: mappings$1,
+ initialLsCache,
+ genLsCache: genLsCache$1,
+ assertNoLevelCollisions
+} = levels_1;
+const {
+ asChindings: asChindings$1,
+ asJson,
+ buildFormatters: buildFormatters$1,
+ stringify: stringify$2
+} = tools;
+const {
+ version: version$2
+} = meta;
+const redaction$1 = redaction_1;
+
+// note: use of class is satirical
+// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127
+const constructor = class Pino {};
+const prototype = {
+ constructor,
+ child,
+ bindings,
+ setBindings,
+ flush,
+ isLevelEnabled,
+ version: version$2,
+ get level () { return this[getLevelSym]() },
+ set level (lvl) { this[setLevelSym$1](lvl); },
+ get levelVal () { return this[levelValSym] },
+ set levelVal (n) { throw Error('levelVal is read-only') },
+ [lsCacheSym]: initialLsCache,
+ [writeSym]: write,
+ [asJsonSym]: asJson,
+ [getLevelSym]: getLevel,
+ [setLevelSym$1]: setLevel
+};
+
+Object.setPrototypeOf(prototype, EventEmitter$1.prototype);
+
+// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing
+var proto$1 = function () {
+ return Object.create(prototype)
+};
+
+const resetChildingsFormatter = bindings => bindings;
+function child (bindings, options) {
+ if (!bindings) {
+ throw Error('missing bindings for child Pino')
+ }
+ options = options || {}; // default options to empty object
+ const serializers = this[serializersSym$1];
+ const formatters = this[formattersSym$1];
+ const instance = Object.create(this);
+
+ if (options.hasOwnProperty('serializers') === true) {
+ instance[serializersSym$1] = Object.create(null);
+
+ for (const k in serializers) {
+ instance[serializersSym$1][k] = serializers[k];
+ }
+ const parentSymbols = Object.getOwnPropertySymbols(serializers);
+ /* eslint no-var: off */
+ for (var i = 0; i < parentSymbols.length; i++) {
+ const ks = parentSymbols[i];
+ instance[serializersSym$1][ks] = serializers[ks];
+ }
+
+ for (const bk in options.serializers) {
+ instance[serializersSym$1][bk] = options.serializers[bk];
+ }
+ const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers);
+ for (var bi = 0; bi < bindingsSymbols.length; bi++) {
+ const bks = bindingsSymbols[bi];
+ instance[serializersSym$1][bks] = options.serializers[bks];
+ }
+ } else instance[serializersSym$1] = serializers;
+ if (options.hasOwnProperty('formatters')) {
+ const { level, bindings: chindings, log } = options.formatters;
+ instance[formattersSym$1] = buildFormatters$1(
+ level || formatters.level,
+ chindings || resetChildingsFormatter,
+ log || formatters.log
+ );
+ } else {
+ instance[formattersSym$1] = buildFormatters$1(
+ formatters.level,
+ resetChildingsFormatter,
+ formatters.log
+ );
+ }
+ if (options.hasOwnProperty('customLevels') === true) {
+ assertNoLevelCollisions(this.levels, options.customLevels);
+ instance.levels = mappings$1(options.customLevels, instance[useOnlyCustomLevelsSym$1]);
+ genLsCache$1(instance);
+ }
+
+ // redact must place before asChindings and only replace if exist
+ if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {
+ instance.redact = options.redact; // replace redact directly
+ const stringifiers = redaction$1(instance.redact, stringify$2);
+ const formatOpts = { stringify: stringifiers[redactFmtSym$1] };
+ instance[stringifySym$1] = stringify$2;
+ instance[stringifiersSym$1] = stringifiers;
+ instance[formatOptsSym$1] = formatOpts;
+ }
+
+ if (typeof options.msgPrefix === 'string') {
+ instance[msgPrefixSym$1] = (this[msgPrefixSym$1] || '') + options.msgPrefix;
+ }
+
+ instance[chindingsSym$1] = asChindings$1(instance, bindings);
+ const childLevel = options.level || this.level;
+ instance[setLevelSym$1](childLevel);
+ this.onChild(instance);
+ return instance
+}
+
+function bindings () {
+ const chindings = this[chindingsSym$1];
+ const chindingsJson = `{${chindings.substr(1)}}`; // at least contains ,"pid":7068,"hostname":"myMac"
+ const bindingsFromJson = JSON.parse(chindingsJson);
+ delete bindingsFromJson.pid;
+ delete bindingsFromJson.hostname;
+ return bindingsFromJson
+}
+
+function setBindings (newBindings) {
+ const chindings = asChindings$1(this, newBindings);
+ this[chindingsSym$1] = chindings;
+ delete this[parsedChindingsSym];
+}
+
+/**
+ * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.
+ * Fields from `mergeObject` have higher priority in this strategy.
+ *
+ * @param {Object} mergeObject The object a user has supplied to the logging function.
+ * @param {Object} mixinObject The result of the `mixin` method.
+ * @return {Object}
+ */
+function defaultMixinMergeStrategy (mergeObject, mixinObject) {
+ return Object.assign(mixinObject, mergeObject)
+}
+
+function write (_obj, msg, num) {
+ const t = this[timeSym$1]();
+ const mixin = this[mixinSym$1];
+ const errorKey = this[errorKeySym$1];
+ const mixinMergeStrategy = this[mixinMergeStrategySym$1] || defaultMixinMergeStrategy;
+ let obj;
+
+ if (_obj === undefined || _obj === null) {
+ obj = {};
+ } else if (_obj instanceof Error) {
+ obj = { [errorKey]: _obj };
+ if (msg === undefined) {
+ msg = _obj.message;
+ }
+ } else {
+ obj = _obj;
+ if (msg === undefined && _obj[errorKey]) {
+ msg = _obj[errorKey].message;
+ }
+ }
+
+ if (mixin) {
+ obj = mixinMergeStrategy(obj, mixin(obj, num));
+ }
+
+ const s = this[asJsonSym](obj, msg, num, t);
+
+ const stream = this[streamSym$1];
+ if (stream[needsMetadataGsym] === true) {
+ stream.lastLevel = num;
+ stream.lastObj = obj;
+ stream.lastMsg = msg;
+ stream.lastTime = t.slice(this[timeSliceIndexSym$1]);
+ stream.lastLogger = this; // for child loggers
+ }
+ stream.write(s);
+}
+
+function noop$1 () {}
+
+function flush () {
+ const stream = this[streamSym$1];
+ if ('flush' in stream) stream.flush(noop$1);
+}
+
+var safeStableStringifyExports = {};
+var safeStableStringify = {
+ get exports(){ return safeStableStringifyExports; },
+ set exports(v){ safeStableStringifyExports = v; },
+};
+
+(function (module, exports) {
+
+ const { hasOwnProperty } = Object.prototype;
+
+ const stringify = configure();
+
+ // @ts-expect-error
+ stringify.configure = configure;
+ // @ts-expect-error
+ stringify.stringify = stringify;
+
+ // @ts-expect-error
+ stringify.default = stringify;
+
+ // @ts-expect-error used for named export
+ exports.stringify = stringify;
+ // @ts-expect-error used for named export
+ exports.configure = configure;
+
+ module.exports = stringify;
+
+ // eslint-disable-next-line no-control-regex
+ const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/;
+ const strEscapeSequencesReplacer = new RegExp(strEscapeSequencesRegExp, 'g');
+
+ // Escaped special characters. Use empty strings to fill up unused entries.
+ const meta = [
+ '\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004',
+ '\\u0005', '\\u0006', '\\u0007', '\\b', '\\t',
+ '\\n', '\\u000b', '\\f', '\\r', '\\u000e',
+ '\\u000f', '\\u0010', '\\u0011', '\\u0012', '\\u0013',
+ '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018',
+ '\\u0019', '\\u001a', '\\u001b', '\\u001c', '\\u001d',
+ '\\u001e', '\\u001f', '', '', '\\"',
+ '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '\\\\'
+ ];
+
+ function escapeFn (str) {
+ if (str.length === 2) {
+ const charCode = str.charCodeAt(1);
+ return `${str[0]}\\u${charCode.toString(16)}`
+ }
+ const charCode = str.charCodeAt(0);
+ return meta.length > charCode
+ ? meta[charCode]
+ : `\\u${charCode.toString(16)}`
+ }
+
+ // Escape C0 control characters, double quotes, the backslash and every code
+ // unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.
+ function strEscape (str) {
+ // Some magic numbers that worked out fine while benchmarking with v8 8.0
+ if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {
+ return str
+ }
+ if (str.length > 100) {
+ return str.replace(strEscapeSequencesReplacer, escapeFn)
+ }
+ let result = '';
+ let last = 0;
+ for (let i = 0; i < str.length; i++) {
+ const point = str.charCodeAt(i);
+ if (point === 34 || point === 92 || point < 32) {
+ result += `${str.slice(last, i)}${meta[point]}`;
+ last = i + 1;
+ } else if (point >= 0xd800 && point <= 0xdfff) {
+ if (point <= 0xdbff && i + 1 < str.length) {
+ const nextPoint = str.charCodeAt(i + 1);
+ if (nextPoint >= 0xdc00 && nextPoint <= 0xdfff) {
+ i++;
+ continue
+ }
+ }
+ result += `${str.slice(last, i)}\\u${point.toString(16)}`;
+ last = i + 1;
+ }
+ }
+ result += str.slice(last);
+ return result
+ }
+
+ function insertSort (array) {
+ // Insertion sort is very efficient for small input sizes but it has a bad
+ // worst case complexity. Thus, use native array sort for bigger values.
+ if (array.length > 2e2) {
+ return array.sort()
+ }
+ for (let i = 1; i < array.length; i++) {
+ const currentValue = array[i];
+ let position = i;
+ while (position !== 0 && array[position - 1] > currentValue) {
+ array[position] = array[position - 1];
+ position--;
+ }
+ array[position] = currentValue;
+ }
+ return array
+ }
+
+ const typedArrayPrototypeGetSymbolToStringTag =
+ Object.getOwnPropertyDescriptor(
+ Object.getPrototypeOf(
+ Object.getPrototypeOf(
+ new Int8Array()
+ )
+ ),
+ Symbol.toStringTag
+ ).get;
+
+ function isTypedArrayWithEntries (value) {
+ return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0
+ }
+
+ function stringifyTypedArray (array, separator, maximumBreadth) {
+ if (array.length < maximumBreadth) {
+ maximumBreadth = array.length;
+ }
+ const whitespace = separator === ',' ? '' : ' ';
+ let res = `"0":${whitespace}${array[0]}`;
+ for (let i = 1; i < maximumBreadth; i++) {
+ res += `${separator}"${i}":${whitespace}${array[i]}`;
+ }
+ return res
+ }
+
+ function getCircularValueOption (options) {
+ if (hasOwnProperty.call(options, 'circularValue')) {
+ const circularValue = options.circularValue;
+ if (typeof circularValue === 'string') {
+ return `"${circularValue}"`
+ }
+ if (circularValue == null) {
+ return circularValue
+ }
+ if (circularValue === Error || circularValue === TypeError) {
+ return {
+ toString () {
+ throw new TypeError('Converting circular structure to JSON')
+ }
+ }
+ }
+ throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')
+ }
+ return '"[Circular]"'
+ }
+
+ function getBooleanOption (options, key) {
+ let value;
+ if (hasOwnProperty.call(options, key)) {
+ value = options[key];
+ if (typeof value !== 'boolean') {
+ throw new TypeError(`The "${key}" argument must be of type boolean`)
+ }
+ }
+ return value === undefined ? true : value
+ }
+
+ function getPositiveIntegerOption (options, key) {
+ let value;
+ if (hasOwnProperty.call(options, key)) {
+ value = options[key];
+ if (typeof value !== 'number') {
+ throw new TypeError(`The "${key}" argument must be of type number`)
+ }
+ if (!Number.isInteger(value)) {
+ throw new TypeError(`The "${key}" argument must be an integer`)
+ }
+ if (value < 1) {
+ throw new RangeError(`The "${key}" argument must be >= 1`)
+ }
+ }
+ return value === undefined ? Infinity : value
+ }
+
+ function getItemCount (number) {
+ if (number === 1) {
+ return '1 item'
+ }
+ return `${number} items`
+ }
+
+ function getUniqueReplacerSet (replacerArray) {
+ const replacerSet = new Set();
+ for (const value of replacerArray) {
+ if (typeof value === 'string' || typeof value === 'number') {
+ replacerSet.add(String(value));
+ }
+ }
+ return replacerSet
+ }
+
+ function getStrictOption (options) {
+ if (hasOwnProperty.call(options, 'strict')) {
+ const value = options.strict;
+ if (typeof value !== 'boolean') {
+ throw new TypeError('The "strict" argument must be of type boolean')
+ }
+ if (value) {
+ return (value) => {
+ let message = `Object can not safely be stringified. Received type ${typeof value}`;
+ if (typeof value !== 'function') message += ` (${value.toString()})`;
+ throw new Error(message)
+ }
+ }
+ }
+ }
+
+ function configure (options) {
+ options = { ...options };
+ const fail = getStrictOption(options);
+ if (fail) {
+ if (options.bigint === undefined) {
+ options.bigint = false;
+ }
+ if (!('circularValue' in options)) {
+ options.circularValue = Error;
+ }
+ }
+ const circularValue = getCircularValueOption(options);
+ const bigint = getBooleanOption(options, 'bigint');
+ const deterministic = getBooleanOption(options, 'deterministic');
+ const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth');
+ const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth');
+
+ function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {
+ let value = parent[key];
+
+ if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+ value = replacer.call(parent, key, value);
+
+ switch (typeof value) {
+ case 'string':
+ return `"${strEscape(value)}"`
+ case 'object': {
+ if (value === null) {
+ return 'null'
+ }
+ if (stack.indexOf(value) !== -1) {
+ return circularValue
+ }
+
+ let res = '';
+ let join = ',';
+ const originalIndentation = indentation;
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ return '[]'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Array]"'
+ }
+ stack.push(value);
+ if (spacer !== '') {
+ indentation += spacer;
+ res += `\n${indentation}`;
+ join = `,\n${indentation}`;
+ }
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
+ let i = 0;
+ for (; i < maximumValuesToStringify - 1; i++) {
+ const tmp = stringifyFnReplacer(i, value, stack, replacer, spacer, indentation);
+ res += tmp !== undefined ? tmp : 'null';
+ res += join;
+ }
+ const tmp = stringifyFnReplacer(i, value, stack, replacer, spacer, indentation);
+ res += tmp !== undefined ? tmp : 'null';
+ if (value.length - 1 > maximumBreadth) {
+ const removedKeys = value.length - maximumBreadth - 1;
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
+ }
+ if (spacer !== '') {
+ res += `\n${originalIndentation}`;
+ }
+ stack.pop();
+ return `[${res}]`
+ }
+
+ let keys = Object.keys(value);
+ const keyLength = keys.length;
+ if (keyLength === 0) {
+ return '{}'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Object]"'
+ }
+ let whitespace = '';
+ let separator = '';
+ if (spacer !== '') {
+ indentation += spacer;
+ join = `,\n${indentation}`;
+ whitespace = ' ';
+ }
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
+ if (isTypedArrayWithEntries(value)) {
+ res += stringifyTypedArray(value, join, maximumBreadth);
+ keys = keys.slice(value.length);
+ maximumPropertiesToStringify -= value.length;
+ separator = join;
+ }
+ if (deterministic) {
+ keys = insertSort(keys);
+ }
+ stack.push(value);
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
+ const key = keys[i];
+ const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation);
+ if (tmp !== undefined) {
+ res += `${separator}"${strEscape(key)}":${whitespace}${tmp}`;
+ separator = join;
+ }
+ }
+ if (keyLength > maximumBreadth) {
+ const removedKeys = keyLength - maximumBreadth;
+ res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
+ separator = join;
+ }
+ if (spacer !== '' && separator.length > 1) {
+ res = `\n${indentation}${res}\n${originalIndentation}`;
+ }
+ stack.pop();
+ return `{${res}}`
+ }
+ case 'number':
+ return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
+ case 'boolean':
+ return value === true ? 'true' : 'false'
+ case 'undefined':
+ return undefined
+ case 'bigint':
+ if (bigint) {
+ return String(value)
+ }
+ // fallthrough
+ default:
+ return fail ? fail(value) : undefined
+ }
+ }
+
+ function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {
+ if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ }
+
+ switch (typeof value) {
+ case 'string':
+ return `"${strEscape(value)}"`
+ case 'object': {
+ if (value === null) {
+ return 'null'
+ }
+ if (stack.indexOf(value) !== -1) {
+ return circularValue
+ }
+
+ const originalIndentation = indentation;
+ let res = '';
+ let join = ',';
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ return '[]'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Array]"'
+ }
+ stack.push(value);
+ if (spacer !== '') {
+ indentation += spacer;
+ res += `\n${indentation}`;
+ join = `,\n${indentation}`;
+ }
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
+ let i = 0;
+ for (; i < maximumValuesToStringify - 1; i++) {
+ const tmp = stringifyArrayReplacer(i, value[i], stack, replacer, spacer, indentation);
+ res += tmp !== undefined ? tmp : 'null';
+ res += join;
+ }
+ const tmp = stringifyArrayReplacer(i, value[i], stack, replacer, spacer, indentation);
+ res += tmp !== undefined ? tmp : 'null';
+ if (value.length - 1 > maximumBreadth) {
+ const removedKeys = value.length - maximumBreadth - 1;
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
+ }
+ if (spacer !== '') {
+ res += `\n${originalIndentation}`;
+ }
+ stack.pop();
+ return `[${res}]`
+ }
+ stack.push(value);
+ let whitespace = '';
+ if (spacer !== '') {
+ indentation += spacer;
+ join = `,\n${indentation}`;
+ whitespace = ' ';
+ }
+ let separator = '';
+ for (const key of replacer) {
+ const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation);
+ if (tmp !== undefined) {
+ res += `${separator}"${strEscape(key)}":${whitespace}${tmp}`;
+ separator = join;
+ }
+ }
+ if (spacer !== '' && separator.length > 1) {
+ res = `\n${indentation}${res}\n${originalIndentation}`;
+ }
+ stack.pop();
+ return `{${res}}`
+ }
+ case 'number':
+ return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
+ case 'boolean':
+ return value === true ? 'true' : 'false'
+ case 'undefined':
+ return undefined
+ case 'bigint':
+ if (bigint) {
+ return String(value)
+ }
+ // fallthrough
+ default:
+ return fail ? fail(value) : undefined
+ }
+ }
+
+ function stringifyIndent (key, value, stack, spacer, indentation) {
+ switch (typeof value) {
+ case 'string':
+ return `"${strEscape(value)}"`
+ case 'object': {
+ if (value === null) {
+ return 'null'
+ }
+ if (typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ // Prevent calling `toJSON` again.
+ if (typeof value !== 'object') {
+ return stringifyIndent(key, value, stack, spacer, indentation)
+ }
+ if (value === null) {
+ return 'null'
+ }
+ }
+ if (stack.indexOf(value) !== -1) {
+ return circularValue
+ }
+ const originalIndentation = indentation;
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ return '[]'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Array]"'
+ }
+ stack.push(value);
+ indentation += spacer;
+ let res = `\n${indentation}`;
+ const join = `,\n${indentation}`;
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
+ let i = 0;
+ for (; i < maximumValuesToStringify - 1; i++) {
+ const tmp = stringifyIndent(i, value[i], stack, spacer, indentation);
+ res += tmp !== undefined ? tmp : 'null';
+ res += join;
+ }
+ const tmp = stringifyIndent(i, value[i], stack, spacer, indentation);
+ res += tmp !== undefined ? tmp : 'null';
+ if (value.length - 1 > maximumBreadth) {
+ const removedKeys = value.length - maximumBreadth - 1;
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
+ }
+ res += `\n${originalIndentation}`;
+ stack.pop();
+ return `[${res}]`
+ }
+
+ let keys = Object.keys(value);
+ const keyLength = keys.length;
+ if (keyLength === 0) {
+ return '{}'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Object]"'
+ }
+ indentation += spacer;
+ const join = `,\n${indentation}`;
+ let res = '';
+ let separator = '';
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
+ if (isTypedArrayWithEntries(value)) {
+ res += stringifyTypedArray(value, join, maximumBreadth);
+ keys = keys.slice(value.length);
+ maximumPropertiesToStringify -= value.length;
+ separator = join;
+ }
+ if (deterministic) {
+ keys = insertSort(keys);
+ }
+ stack.push(value);
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
+ const key = keys[i];
+ const tmp = stringifyIndent(key, value[key], stack, spacer, indentation);
+ if (tmp !== undefined) {
+ res += `${separator}"${strEscape(key)}": ${tmp}`;
+ separator = join;
+ }
+ }
+ if (keyLength > maximumBreadth) {
+ const removedKeys = keyLength - maximumBreadth;
+ res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
+ separator = join;
+ }
+ if (separator !== '') {
+ res = `\n${indentation}${res}\n${originalIndentation}`;
+ }
+ stack.pop();
+ return `{${res}}`
+ }
+ case 'number':
+ return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
+ case 'boolean':
+ return value === true ? 'true' : 'false'
+ case 'undefined':
+ return undefined
+ case 'bigint':
+ if (bigint) {
+ return String(value)
+ }
+ // fallthrough
+ default:
+ return fail ? fail(value) : undefined
+ }
+ }
+
+ function stringifySimple (key, value, stack) {
+ switch (typeof value) {
+ case 'string':
+ return `"${strEscape(value)}"`
+ case 'object': {
+ if (value === null) {
+ return 'null'
+ }
+ if (typeof value.toJSON === 'function') {
+ value = value.toJSON(key);
+ // Prevent calling `toJSON` again
+ if (typeof value !== 'object') {
+ return stringifySimple(key, value, stack)
+ }
+ if (value === null) {
+ return 'null'
+ }
+ }
+ if (stack.indexOf(value) !== -1) {
+ return circularValue
+ }
+
+ let res = '';
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ return '[]'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Array]"'
+ }
+ stack.push(value);
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
+ let i = 0;
+ for (; i < maximumValuesToStringify - 1; i++) {
+ const tmp = stringifySimple(i, value[i], stack);
+ res += tmp !== undefined ? tmp : 'null';
+ res += ',';
+ }
+ const tmp = stringifySimple(i, value[i], stack);
+ res += tmp !== undefined ? tmp : 'null';
+ if (value.length - 1 > maximumBreadth) {
+ const removedKeys = value.length - maximumBreadth - 1;
+ res += `,"... ${getItemCount(removedKeys)} not stringified"`;
+ }
+ stack.pop();
+ return `[${res}]`
+ }
+
+ let keys = Object.keys(value);
+ const keyLength = keys.length;
+ if (keyLength === 0) {
+ return '{}'
+ }
+ if (maximumDepth < stack.length + 1) {
+ return '"[Object]"'
+ }
+ let separator = '';
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
+ if (isTypedArrayWithEntries(value)) {
+ res += stringifyTypedArray(value, ',', maximumBreadth);
+ keys = keys.slice(value.length);
+ maximumPropertiesToStringify -= value.length;
+ separator = ',';
+ }
+ if (deterministic) {
+ keys = insertSort(keys);
+ }
+ stack.push(value);
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
+ const key = keys[i];
+ const tmp = stringifySimple(key, value[key], stack);
+ if (tmp !== undefined) {
+ res += `${separator}"${strEscape(key)}":${tmp}`;
+ separator = ',';
+ }
+ }
+ if (keyLength > maximumBreadth) {
+ const removedKeys = keyLength - maximumBreadth;
+ res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
+ }
+ stack.pop();
+ return `{${res}}`
+ }
+ case 'number':
+ return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
+ case 'boolean':
+ return value === true ? 'true' : 'false'
+ case 'undefined':
+ return undefined
+ case 'bigint':
+ if (bigint) {
+ return String(value)
+ }
+ // fallthrough
+ default:
+ return fail ? fail(value) : undefined
+ }
+ }
+
+ function stringify (value, replacer, space) {
+ if (arguments.length > 1) {
+ let spacer = '';
+ if (typeof space === 'number') {
+ spacer = ' '.repeat(Math.min(space, 10));
+ } else if (typeof space === 'string') {
+ spacer = space.slice(0, 10);
+ }
+ if (replacer != null) {
+ if (typeof replacer === 'function') {
+ return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')
+ }
+ if (Array.isArray(replacer)) {
+ return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')
+ }
+ }
+ if (spacer.length !== 0) {
+ return stringifyIndent('', value, [], spacer, '')
+ }
+ }
+ return stringifySimple('', value, [])
+ }
+
+ return stringify
+ }
+} (safeStableStringify, safeStableStringifyExports));
+
+var multistream_1;
+var hasRequiredMultistream;
+
+function requireMultistream () {
+ if (hasRequiredMultistream) return multistream_1;
+ hasRequiredMultistream = 1;
+
+ const metadata = Symbol.for('pino.metadata');
+ const { levels } = levels_1;
+
+ const defaultLevels = Object.create(levels);
+ defaultLevels.silent = Infinity;
+
+ const DEFAULT_INFO_LEVEL = levels.info;
+
+ function multistream (streamsArray, opts) {
+ let counter = 0;
+ streamsArray = streamsArray || [];
+ opts = opts || { dedupe: false };
+
+ let levels = defaultLevels;
+ if (opts.levels && typeof opts.levels === 'object') {
+ levels = opts.levels;
+ }
+
+ const res = {
+ write,
+ add,
+ flushSync,
+ end,
+ minLevel: 0,
+ streams: [],
+ clone,
+ [metadata]: true
+ };
+
+ if (Array.isArray(streamsArray)) {
+ streamsArray.forEach(add, res);
+ } else {
+ add.call(res, streamsArray);
+ }
+
+ // clean this object up
+ // or it will stay allocated forever
+ // as it is closed on the following closures
+ streamsArray = null;
+
+ return res
+
+ // we can exit early because the streams are ordered by level
+ function write (data) {
+ let dest;
+ const level = this.lastLevel;
+ const { streams } = this;
+ // for handling situation when several streams has the same level
+ let recordedLevel = 0;
+ let stream;
+
+ // if dedupe set to true we send logs to the stream with the highest level
+ // therefore, we have to change sorting order
+ for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {
+ dest = streams[i];
+ if (dest.level <= level) {
+ if (recordedLevel !== 0 && recordedLevel !== dest.level) {
+ break
+ }
+ stream = dest.stream;
+ if (stream[metadata]) {
+ const { lastTime, lastMsg, lastObj, lastLogger } = this;
+ stream.lastLevel = level;
+ stream.lastTime = lastTime;
+ stream.lastMsg = lastMsg;
+ stream.lastObj = lastObj;
+ stream.lastLogger = lastLogger;
+ }
+ stream.write(data);
+ if (opts.dedupe) {
+ recordedLevel = dest.level;
+ }
+ } else if (!opts.dedupe) {
+ break
+ }
+ }
+ }
+
+ function flushSync () {
+ for (const { stream } of this.streams) {
+ if (typeof stream.flushSync === 'function') {
+ stream.flushSync();
+ }
+ }
+ }
+
+ function add (dest) {
+ if (!dest) {
+ return res
+ }
+
+ // Check that dest implements either StreamEntry or DestinationStream
+ const isStream = typeof dest.write === 'function' || dest.stream;
+ const stream_ = dest.write ? dest : dest.stream;
+ // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()
+ if (!isStream) {
+ throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')
+ }
+
+ const { streams } = this;
+
+ let level;
+ if (typeof dest.levelVal === 'number') {
+ level = dest.levelVal;
+ } else if (typeof dest.level === 'string') {
+ level = levels[dest.level];
+ } else if (typeof dest.level === 'number') {
+ level = dest.level;
+ } else {
+ level = DEFAULT_INFO_LEVEL;
+ }
+
+ const dest_ = {
+ stream: stream_,
+ level,
+ levelVal: undefined,
+ id: counter++
+ };
+
+ streams.unshift(dest_);
+ streams.sort(compareByLevel);
+
+ this.minLevel = streams[0].level;
+
+ return res
+ }
+
+ function end () {
+ for (const { stream } of this.streams) {
+ if (typeof stream.flushSync === 'function') {
+ stream.flushSync();
+ }
+ stream.end();
+ }
+ }
+
+ function clone (level) {
+ const streams = new Array(this.streams.length);
+
+ for (let i = 0; i < streams.length; i++) {
+ streams[i] = {
+ level,
+ stream: this.streams[i].stream
+ };
+ }
+
+ return {
+ write,
+ add,
+ minLevel: level,
+ streams,
+ clone,
+ flushSync,
+ [metadata]: true
+ }
+ }
+ }
+
+ function compareByLevel (a, b) {
+ return a.level - b.level
+ }
+
+ function initLoopVar (length, dedupe) {
+ return dedupe ? length - 1 : 0
+ }
+
+ function adjustLoopVar (i, dedupe) {
+ return dedupe ? i - 1 : i + 1
+ }
+
+ function checkLoopVar (i, length, dedupe) {
+ return dedupe ? i >= 0 : i < length
+ }
+
+ multistream_1 = multistream;
+ return multistream_1;
+}
+
+/* eslint no-prototype-builtins: 0 */
+const os$2 = require$$0$h;
+const stdSerializers = pinoStdSerializers;
+const caller = caller$1;
+const redaction = redaction_1;
+const time = time$1;
+const proto = proto$1;
+const symbols = symbols$1;
+const { configure } = safeStableStringifyExports;
+const { assertDefaultLevelFound, mappings, genLsCache, levels } = levels_1;
+const {
+ createArgsNormalizer,
+ asChindings,
+ buildSafeSonicBoom,
+ buildFormatters,
+ stringify: stringify$1,
+ normalizeDestFileDescriptor,
+ noop
+} = tools;
+const { version: version$1 } = meta;
+const {
+ chindingsSym,
+ redactFmtSym,
+ serializersSym,
+ timeSym,
+ timeSliceIndexSym,
+ streamSym,
+ stringifySym,
+ stringifySafeSym,
+ stringifiersSym,
+ setLevelSym,
+ endSym,
+ formatOptsSym,
+ messageKeySym,
+ errorKeySym,
+ nestedKeySym,
+ mixinSym,
+ useOnlyCustomLevelsSym,
+ formattersSym,
+ hooksSym,
+ nestedKeyStrSym,
+ mixinMergeStrategySym,
+ msgPrefixSym
+} = symbols;
+const { epochTime, nullTime } = time;
+const { pid } = process;
+const hostname = os$2.hostname();
+const defaultErrorSerializer = stdSerializers.err;
+const defaultOptions = {
+ level: 'info',
+ levels,
+ messageKey: 'msg',
+ errorKey: 'err',
+ nestedKey: null,
+ enabled: true,
+ base: { pid, hostname },
+ serializers: Object.assign(Object.create(null), {
+ err: defaultErrorSerializer
+ }),
+ formatters: Object.assign(Object.create(null), {
+ bindings (bindings) {
+ return bindings
+ },
+ level (label, number) {
+ return { level: number }
+ }
+ }),
+ hooks: {
+ logMethod: undefined
+ },
+ timestamp: epochTime,
+ name: undefined,
+ redact: null,
+ customLevels: null,
+ useOnlyCustomLevels: false,
+ depthLimit: 5,
+ edgeLimit: 100
+};
+
+const normalize = createArgsNormalizer(defaultOptions);
+
+const serializers = Object.assign(Object.create(null), stdSerializers);
+
+function pino$2 (...args) {
+ const instance = {};
+ const { opts, stream } = normalize(instance, caller(), ...args);
+ const {
+ redact,
+ crlf,
+ serializers,
+ timestamp,
+ messageKey,
+ errorKey,
+ nestedKey,
+ base,
+ name,
+ level,
+ customLevels,
+ mixin,
+ mixinMergeStrategy,
+ useOnlyCustomLevels,
+ formatters,
+ hooks,
+ depthLimit,
+ edgeLimit,
+ onChild,
+ msgPrefix
+ } = opts;
+
+ const stringifySafe = configure({
+ maximumDepth: depthLimit,
+ maximumBreadth: edgeLimit
+ });
+
+ const allFormatters = buildFormatters(
+ formatters.level,
+ formatters.bindings,
+ formatters.log
+ );
+
+ const stringifyFn = stringify$1.bind({
+ [stringifySafeSym]: stringifySafe
+ });
+ const stringifiers = redact ? redaction(redact, stringifyFn) : {};
+ const formatOpts = redact
+ ? { stringify: stringifiers[redactFmtSym] }
+ : { stringify: stringifyFn };
+ const end = '}' + (crlf ? '\r\n' : '\n');
+ const coreChindings = asChindings.bind(null, {
+ [chindingsSym]: '',
+ [serializersSym]: serializers,
+ [stringifiersSym]: stringifiers,
+ [stringifySym]: stringify$1,
+ [stringifySafeSym]: stringifySafe,
+ [formattersSym]: allFormatters
+ });
+
+ let chindings = '';
+ if (base !== null) {
+ if (name === undefined) {
+ chindings = coreChindings(base);
+ } else {
+ chindings = coreChindings(Object.assign({}, base, { name }));
+ }
+ }
+
+ const time = (timestamp instanceof Function)
+ ? timestamp
+ : (timestamp ? epochTime : nullTime);
+ const timeSliceIndex = time().indexOf(':') + 1;
+
+ if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')
+ if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`)
+ if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`)
+
+ assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels);
+ const levels = mappings(customLevels, useOnlyCustomLevels);
+
+ Object.assign(instance, {
+ levels,
+ [useOnlyCustomLevelsSym]: useOnlyCustomLevels,
+ [streamSym]: stream,
+ [timeSym]: time,
+ [timeSliceIndexSym]: timeSliceIndex,
+ [stringifySym]: stringify$1,
+ [stringifySafeSym]: stringifySafe,
+ [stringifiersSym]: stringifiers,
+ [endSym]: end,
+ [formatOptsSym]: formatOpts,
+ [messageKeySym]: messageKey,
+ [errorKeySym]: errorKey,
+ [nestedKeySym]: nestedKey,
+ // protect against injection
+ [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',
+ [serializersSym]: serializers,
+ [mixinSym]: mixin,
+ [mixinMergeStrategySym]: mixinMergeStrategy,
+ [chindingsSym]: chindings,
+ [formattersSym]: allFormatters,
+ [hooksSym]: hooks,
+ silent: noop,
+ onChild,
+ [msgPrefixSym]: msgPrefix
+ });
+
+ Object.setPrototypeOf(instance, proto());
+
+ genLsCache(instance);
+
+ instance[setLevelSym](level);
+
+ return instance
+}
+
+pino$3.exports = pino$2;
+
+pinoExports.destination = (dest = process.stdout.fd) => {
+ if (typeof dest === 'object') {
+ dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd);
+ return buildSafeSonicBoom(dest)
+ } else {
+ return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })
+ }
+};
+
+pinoExports.transport = transport_1;
+pinoExports.multistream = requireMultistream();
+
+pinoExports.levels = mappings();
+pinoExports.stdSerializers = serializers;
+pinoExports.stdTimeFunctions = Object.assign({}, time);
+pinoExports.symbols = symbols;
+pinoExports.version = version$1;
+
+// Enables default and name export with TypeScript and Babel
+pinoExports.default = pino$2;
+pinoExports.pino = pino$2;
+
+var through2Exports = {};
+var through2$1 = {
+ get exports(){ return through2Exports; },
+ set exports(v){ through2Exports = v; },
+};
+
+const { Transform } = readableExports;
+
+function inherits (fn, sup) {
+ fn.super_ = sup;
+ fn.prototype = Object.create(sup.prototype, {
+ constructor: { value: fn, enumerable: false, writable: true, configurable: true }
+ });
+}
+
+// create a new export function, used by both the main export and
+// the .ctor export, contains common logic for dealing with arguments
+function through2 (construct) {
+ return (options, transform, flush) => {
+ if (typeof options === 'function') {
+ flush = transform;
+ transform = options;
+ options = {};
+ }
+
+ if (typeof transform !== 'function') {
+ // noop
+ transform = (chunk, enc, cb) => cb(null, chunk);
+ }
+
+ if (typeof flush !== 'function') {
+ flush = null;
+ }
+
+ return construct(options, transform, flush)
+ }
+}
+
+// main export, just make me a transform stream!
+const make = through2((options, transform, flush) => {
+ const t2 = new Transform(options);
+
+ t2._transform = transform;
+
+ if (flush) {
+ t2._flush = flush;
+ }
+
+ return t2
+});
+
+// make me a reusable prototype that I can `new`, or implicitly `new`
+// with a constructor call
+const ctor = through2((options, transform, flush) => {
+ function Through2 (override) {
+ if (!(this instanceof Through2)) {
+ return new Through2(override)
+ }
+
+ this.options = Object.assign({}, options, override);
+
+ Transform.call(this, this.options);
+
+ this._transform = transform;
+ if (flush) {
+ this._flush = flush;
+ }
+ }
+
+ inherits(Through2, Transform);
+
+ return Through2
+});
+
+const obj = through2(function (options, transform, flush) {
+ const t2 = new Transform(Object.assign({ objectMode: true, highWaterMark: 16 }, options));
+
+ t2._transform = transform;
+
+ if (flush) {
+ t2._flush = flush;
+ }
+
+ return t2
+});
+
+through2$1.exports = make;
+through2Exports.ctor = ctor;
+through2Exports.obj = obj;
+
+var core$1 = {};
+
+var command = {};
+
+var utils = {};
+
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+Object.defineProperty(utils, "__esModule", { value: true });
+utils.toCommandProperties = utils.toCommandValue = void 0;
+/**
+ * Sanitizes an input into a string so it can be passed into issueCommand safely
+ * @param input input to sanitize into a string
+ */
+function toCommandValue(input) {
+ if (input === null || input === undefined) {
+ return '';
+ }
+ else if (typeof input === 'string' || input instanceof String) {
+ return input;
+ }
+ return JSON.stringify(input);
+}
+utils.toCommandValue = toCommandValue;
+/**
+ *
+ * @param annotationProperties
+ * @returns The command properties to send with the actual annotation command
+ * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
+ */
+function toCommandProperties(annotationProperties) {
+ if (!Object.keys(annotationProperties).length) {
+ return {};
+ }
+ return {
+ title: annotationProperties.title,
+ file: annotationProperties.file,
+ line: annotationProperties.startLine,
+ endLine: annotationProperties.endLine,
+ col: annotationProperties.startColumn,
+ endColumn: annotationProperties.endColumn
+ };
+}
+utils.toCommandProperties = toCommandProperties;
+
+var __createBinding$1 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault$1 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar$1 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding$1(result, mod, k);
+ __setModuleDefault$1(result, mod);
+ return result;
+};
+Object.defineProperty(command, "__esModule", { value: true });
+command.issue = command.issueCommand = void 0;
+const os$1 = __importStar$1(require$$0$h);
+const utils_1$1 = utils;
+/**
+ * Commands
+ *
+ * Command Format:
+ * ::name key=value,key=value::message
+ *
+ * Examples:
+ * ::warning::This is the message
+ * ::set-env name=MY_VAR::some value
+ */
+function issueCommand(command, properties, message) {
+ const cmd = new Command(command, properties, message);
+ process.stdout.write(cmd.toString() + os$1.EOL);
+}
+command.issueCommand = issueCommand;
+function issue(name, message = '') {
+ issueCommand(name, {}, message);
+}
+command.issue = issue;
+const CMD_STRING = '::';
+class Command {
+ constructor(command, properties, message) {
+ if (!command) {
+ command = 'missing.command';
+ }
+ this.command = command;
+ this.properties = properties;
+ this.message = message;
+ }
+ toString() {
+ let cmdStr = CMD_STRING + this.command;
+ if (this.properties && Object.keys(this.properties).length > 0) {
+ cmdStr += ' ';
+ let first = true;
+ for (const key in this.properties) {
+ if (this.properties.hasOwnProperty(key)) {
+ const val = this.properties[key];
+ if (val) {
+ if (first) {
+ first = false;
+ }
+ else {
+ cmdStr += ',';
+ }
+ cmdStr += `${key}=${escapeProperty(val)}`;
+ }
+ }
+ }
+ }
+ cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
+ return cmdStr;
+ }
+}
+function escapeData(s) {
+ return utils_1$1.toCommandValue(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A');
+}
+function escapeProperty(s) {
+ return utils_1$1.toCommandValue(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A')
+ .replace(/:/g, '%3A')
+ .replace(/,/g, '%2C');
+}
+
+var fileCommand = {};
+
+// Unique ID creation requires a high quality random # generator. In the browser we therefore
+// require the crypto API and do not support built-in fallback to lower quality random number
+// generators (like Math.random()).
+var getRandomValues$1;
+var rnds8$1 = new Uint8Array(16);
+function rng$1() {
+ // lazy load so that environments that need to polyfill have a chance to do so
+ if (!getRandomValues$1) {
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
+ // find the complete implementation of crypto (msCrypto) on IE11.
+ getRandomValues$1 = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
+
+ if (!getRandomValues$1) {
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
+ }
+ }
+
+ return getRandomValues$1(rnds8$1);
+}
+
+var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
+
+function validate(uuid) {
+ return typeof uuid === 'string' && REGEX.test(uuid);
+}
+
+/**
+ * Convert array of 16 byte values to UUID string format of the form:
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+ */
+
+var byteToHex$1 = [];
+
+for (var i$1 = 0; i$1 < 256; ++i$1) {
+ byteToHex$1.push((i$1 + 0x100).toString(16).substr(1));
+}
+
+function stringify(arr) {
+ var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
+ // Note: Be careful editing this code! It's been tuned for performance
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
+ var uuid = (byteToHex$1[arr[offset + 0]] + byteToHex$1[arr[offset + 1]] + byteToHex$1[arr[offset + 2]] + byteToHex$1[arr[offset + 3]] + '-' + byteToHex$1[arr[offset + 4]] + byteToHex$1[arr[offset + 5]] + '-' + byteToHex$1[arr[offset + 6]] + byteToHex$1[arr[offset + 7]] + '-' + byteToHex$1[arr[offset + 8]] + byteToHex$1[arr[offset + 9]] + '-' + byteToHex$1[arr[offset + 10]] + byteToHex$1[arr[offset + 11]] + byteToHex$1[arr[offset + 12]] + byteToHex$1[arr[offset + 13]] + byteToHex$1[arr[offset + 14]] + byteToHex$1[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
+ // of the following:
+ // - One or more input array values don't map to a hex octet (leading to
+ // "undefined" in the uuid)
+ // - Invalid input values for the RFC `version` or `variant` fields
+
+ if (!validate(uuid)) {
+ throw TypeError('Stringified UUID is invalid');
+ }
+
+ return uuid;
+}
+
+//
+// Inspired by https://github.com/LiosK/UUID.js
+// and http://docs.python.org/library/uuid.html
+
+var _nodeId;
+
+var _clockseq; // Previous uuid creation time
+
+
+var _lastMSecs = 0;
+var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
+
+function v1(options, buf, offset) {
+ var i = buf && offset || 0;
+ var b = buf || new Array(16);
+ options = options || {};
+ var node = options.node || _nodeId;
+ var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
+ // specified. We do this lazily to minimize issues related to insufficient
+ // system entropy. See #189
+
+ if (node == null || clockseq == null) {
+ var seedBytes = options.random || (options.rng || rng$1)();
+
+ if (node == null) {
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
+ node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
+ }
+
+ if (clockseq == null) {
+ // Per 4.2.2, randomize (14 bit) clockseq
+ clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
+ }
+ } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+
+
+ var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
+ // cycle to simulate higher resolution clock
+
+ var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
+
+ var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
+
+ if (dt < 0 && options.clockseq === undefined) {
+ clockseq = clockseq + 1 & 0x3fff;
+ } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
+ // time interval
+
+
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
+ nsecs = 0;
+ } // Per 4.2.1.2 Throw error if too many uuids are requested
+
+
+ if (nsecs >= 10000) {
+ throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
+ }
+
+ _lastMSecs = msecs;
+ _lastNSecs = nsecs;
+ _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+
+ msecs += 12219292800000; // `time_low`
+
+ var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
+ b[i++] = tl >>> 24 & 0xff;
+ b[i++] = tl >>> 16 & 0xff;
+ b[i++] = tl >>> 8 & 0xff;
+ b[i++] = tl & 0xff; // `time_mid`
+
+ var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
+ b[i++] = tmh >>> 8 & 0xff;
+ b[i++] = tmh & 0xff; // `time_high_and_version`
+
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+
+ b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+
+ b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
+
+ b[i++] = clockseq & 0xff; // `node`
+
+ for (var n = 0; n < 6; ++n) {
+ b[i + n] = node[n];
+ }
+
+ return buf || stringify(b);
+}
+
+function parse(uuid) {
+ if (!validate(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ var v;
+ var arr = new Uint8Array(16); // Parse ########-....-....-....-............
+
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
+ arr[1] = v >>> 16 & 0xff;
+ arr[2] = v >>> 8 & 0xff;
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
+
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
+
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
+
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
+
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
+ arr[11] = v / 0x100000000 & 0xff;
+ arr[12] = v >>> 24 & 0xff;
+ arr[13] = v >>> 16 & 0xff;
+ arr[14] = v >>> 8 & 0xff;
+ arr[15] = v & 0xff;
+ return arr;
+}
+
+function stringToBytes(str) {
+ str = unescape(encodeURIComponent(str)); // UTF8 escape
+
+ var bytes = [];
+
+ for (var i = 0; i < str.length; ++i) {
+ bytes.push(str.charCodeAt(i));
+ }
+
+ return bytes;
+}
+
+var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
+function v35 (name, version, hashfunc) {
+ function generateUUID(value, namespace, buf, offset) {
+ if (typeof value === 'string') {
+ value = stringToBytes(value);
+ }
+
+ if (typeof namespace === 'string') {
+ namespace = parse(namespace);
+ }
+
+ if (namespace.length !== 16) {
+ throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
+ } // Compute hash of namespace and value, Per 4.3
+ // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
+ // hashfunc([...namespace, ... value])`
+
+
+ var bytes = new Uint8Array(16 + value.length);
+ bytes.set(namespace);
+ bytes.set(value, namespace.length);
+ bytes = hashfunc(bytes);
+ bytes[6] = bytes[6] & 0x0f | version;
+ bytes[8] = bytes[8] & 0x3f | 0x80;
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (var i = 0; i < 16; ++i) {
+ buf[offset + i] = bytes[i];
+ }
+
+ return buf;
+ }
+
+ return stringify(bytes);
+ } // Function#name is not settable on some platforms (#270)
+
+
+ try {
+ generateUUID.name = name; // eslint-disable-next-line no-empty
+ } catch (err) {} // For CommonJS default export support
+
+
+ generateUUID.DNS = DNS;
+ generateUUID.URL = URL$1;
+ return generateUUID;
+}
+
+/*
+ * Browser-compatible JavaScript MD5
+ *
+ * Modification of JavaScript MD5
+ * https://github.com/blueimp/JavaScript-MD5
+ *
+ * Copyright 2011, Sebastian Tschan
+ * https://blueimp.net
+ *
+ * Licensed under the MIT license:
+ * https://opensource.org/licenses/MIT
+ *
+ * Based on
+ * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
+ * Digest Algorithm, as defined in RFC 1321.
+ * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
+ * Distributed under the BSD License
+ * See http://pajhome.org.uk/crypt/md5 for more info.
+ */
+function md5(bytes) {
+ if (typeof bytes === 'string') {
+ var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
+
+ bytes = new Uint8Array(msg.length);
+
+ for (var i = 0; i < msg.length; ++i) {
+ bytes[i] = msg.charCodeAt(i);
+ }
+ }
+
+ return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
+}
+/*
+ * Convert an array of little-endian words to an array of bytes
+ */
+
+
+function md5ToHexEncodedArray(input) {
+ var output = [];
+ var length32 = input.length * 32;
+ var hexTab = '0123456789abcdef';
+
+ for (var i = 0; i < length32; i += 8) {
+ var x = input[i >> 5] >>> i % 32 & 0xff;
+ var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
+ output.push(hex);
+ }
+
+ return output;
+}
+/**
+ * Calculate output length with padding and bit length
+ */
+
+
+function getOutputLength(inputLength8) {
+ return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
+}
+/*
+ * Calculate the MD5 of an array of little-endian words, and a bit length.
+ */
+
+
+function wordsToMd5(x, len) {
+ /* append padding */
+ x[len >> 5] |= 0x80 << len % 32;
+ x[getOutputLength(len) - 1] = len;
+ var a = 1732584193;
+ var b = -271733879;
+ var c = -1732584194;
+ var d = 271733878;
+
+ for (var i = 0; i < x.length; i += 16) {
+ var olda = a;
+ var oldb = b;
+ var oldc = c;
+ var oldd = d;
+ a = md5ff(a, b, c, d, x[i], 7, -680876936);
+ d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
+ c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
+ b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
+ a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
+ d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
+ c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
+ b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
+ a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
+ d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
+ c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
+ b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
+ a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
+ d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
+ c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
+ b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
+ a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
+ d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
+ c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
+ b = md5gg(b, c, d, a, x[i], 20, -373897302);
+ a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
+ d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
+ c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
+ b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
+ a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
+ d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
+ c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
+ b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
+ a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
+ d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
+ c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
+ b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
+ a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
+ d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
+ c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
+ b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
+ a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
+ d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
+ c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
+ b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
+ a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
+ d = md5hh(d, a, b, c, x[i], 11, -358537222);
+ c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
+ b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
+ a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
+ d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
+ c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
+ b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
+ a = md5ii(a, b, c, d, x[i], 6, -198630844);
+ d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
+ c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
+ b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
+ a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
+ d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
+ c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
+ b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
+ a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
+ d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
+ c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
+ b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
+ a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
+ d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
+ c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
+ b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
+ a = safeAdd(a, olda);
+ b = safeAdd(b, oldb);
+ c = safeAdd(c, oldc);
+ d = safeAdd(d, oldd);
+ }
+
+ return [a, b, c, d];
+}
+/*
+ * Convert an array bytes to an array of little-endian words
+ * Characters >255 have their high-byte silently ignored.
+ */
+
+
+function bytesToWords(input) {
+ if (input.length === 0) {
+ return [];
+ }
+
+ var length8 = input.length * 8;
+ var output = new Uint32Array(getOutputLength(length8));
+
+ for (var i = 0; i < length8; i += 8) {
+ output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
+ }
+
+ return output;
+}
+/*
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
+ * to work around bugs in some JS interpreters.
+ */
+
+
+function safeAdd(x, y) {
+ var lsw = (x & 0xffff) + (y & 0xffff);
+ var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+ return msw << 16 | lsw & 0xffff;
+}
+/*
+ * Bitwise rotate a 32-bit number to the left.
+ */
+
+
+function bitRotateLeft(num, cnt) {
+ return num << cnt | num >>> 32 - cnt;
+}
+/*
+ * These functions implement the four basic operations the algorithm uses.
+ */
+
+
+function md5cmn(q, a, b, x, s, t) {
+ return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
+}
+
+function md5ff(a, b, c, d, x, s, t) {
+ return md5cmn(b & c | ~b & d, a, b, x, s, t);
+}
+
+function md5gg(a, b, c, d, x, s, t) {
+ return md5cmn(b & d | c & ~d, a, b, x, s, t);
+}
+
+function md5hh(a, b, c, d, x, s, t) {
+ return md5cmn(b ^ c ^ d, a, b, x, s, t);
+}
+
+function md5ii(a, b, c, d, x, s, t) {
+ return md5cmn(c ^ (b | ~d), a, b, x, s, t);
+}
+
+var v3 = v35('v3', 0x30, md5);
+var v3$1 = v3;
+
+function v4$1(options, buf, offset) {
+ options = options || {};
+ var rnds = options.random || (options.rng || rng$1)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
+ rnds[6] = rnds[6] & 0x0f | 0x40;
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (var i = 0; i < 16; ++i) {
+ buf[offset + i] = rnds[i];
+ }
+
+ return buf;
+ }
+
+ return stringify(rnds);
+}
+
+// Adapted from Chris Veness' SHA1 code at
+// http://www.movable-type.co.uk/scripts/sha1.html
+function f$1(s, x, y, z) {
+ switch (s) {
+ case 0:
+ return x & y ^ ~x & z;
+
+ case 1:
+ return x ^ y ^ z;
+
+ case 2:
+ return x & y ^ x & z ^ y & z;
+
+ case 3:
+ return x ^ y ^ z;
+ }
+}
+
+function ROTL(x, n) {
+ return x << n | x >>> 32 - n;
+}
+
+function sha1(bytes) {
+ var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
+ var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
+
+ if (typeof bytes === 'string') {
+ var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
+
+ bytes = [];
+
+ for (var i = 0; i < msg.length; ++i) {
+ bytes.push(msg.charCodeAt(i));
+ }
+ } else if (!Array.isArray(bytes)) {
+ // Convert Array-like to Array
+ bytes = Array.prototype.slice.call(bytes);
+ }
+
+ bytes.push(0x80);
+ var l = bytes.length / 4 + 2;
+ var N = Math.ceil(l / 16);
+ var M = new Array(N);
+
+ for (var _i = 0; _i < N; ++_i) {
+ var arr = new Uint32Array(16);
+
+ for (var j = 0; j < 16; ++j) {
+ arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
+ }
+
+ M[_i] = arr;
+ }
+
+ M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
+ M[N - 1][14] = Math.floor(M[N - 1][14]);
+ M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
+
+ for (var _i2 = 0; _i2 < N; ++_i2) {
+ var W = new Uint32Array(80);
+
+ for (var t = 0; t < 16; ++t) {
+ W[t] = M[_i2][t];
+ }
+
+ for (var _t = 16; _t < 80; ++_t) {
+ W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
+ }
+
+ var a = H[0];
+ var b = H[1];
+ var c = H[2];
+ var d = H[3];
+ var e = H[4];
+
+ for (var _t2 = 0; _t2 < 80; ++_t2) {
+ var s = Math.floor(_t2 / 20);
+ var T = ROTL(a, 5) + f$1(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
+ e = d;
+ d = c;
+ c = ROTL(b, 30) >>> 0;
+ b = a;
+ a = T;
+ }
+
+ H[0] = H[0] + a >>> 0;
+ H[1] = H[1] + b >>> 0;
+ H[2] = H[2] + c >>> 0;
+ H[3] = H[3] + d >>> 0;
+ H[4] = H[4] + e >>> 0;
+ }
+
+ return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
+}
+
+var v5 = v35('v5', 0x50, sha1);
+var v5$1 = v5;
+
+var nil = '00000000-0000-0000-0000-000000000000';
+
+function version(uuid) {
+ if (!validate(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ return parseInt(uuid.substr(14, 1), 16);
+}
+
+var esmBrowser = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ NIL: nil,
+ parse: parse,
+ stringify: stringify,
+ v1: v1,
+ v3: v3$1,
+ v4: v4$1,
+ v5: v5$1,
+ validate: validate,
+ version: version
+});
+
+var require$$2 = /*@__PURE__*/getAugmentedNamespace(esmBrowser);
+
+// For internal use, subject to change.
+var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(fileCommand, "__esModule", { value: true });
+fileCommand.prepareKeyValueMessage = fileCommand.issueFileCommand = void 0;
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+const fs$1 = __importStar(require$$0$e);
+const os = __importStar(require$$0$h);
+const uuid_1 = require$$2;
+const utils_1 = utils;
+function issueFileCommand(command, message) {
+ const filePath = process.env[`GITHUB_${command}`];
+ if (!filePath) {
+ throw new Error(`Unable to find environment variable for file command ${command}`);
+ }
+ if (!fs$1.existsSync(filePath)) {
+ throw new Error(`Missing file at path: ${filePath}`);
+ }
+ fs$1.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
+ encoding: 'utf8'
+ });
+}
+fileCommand.issueFileCommand = issueFileCommand;
+function prepareKeyValueMessage(key, value) {
+ const delimiter = `ghadelimiter_${uuid_1.v4()}`;
+ const convertedValue = utils_1.toCommandValue(value);
+ // These should realistically never happen, but just in case someone finds a
+ // way to exploit uuid generation let's not allow keys or values that contain
+ // the delimiter.
+ if (key.includes(delimiter)) {
+ throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
+ }
+ if (convertedValue.includes(delimiter)) {
+ throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
+ }
+ return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
+}
+fileCommand.prepareKeyValueMessage = prepareKeyValueMessage;
+
+var oidcUtils = {};
+
+var lib = {};
+
+var proxy = {};
+
+Object.defineProperty(proxy, "__esModule", { value: true });
+proxy.checkBypass = proxy.getProxyUrl = void 0;
+function getProxyUrl(reqUrl) {
+ const usingSsl = reqUrl.protocol === 'https:';
+ if (checkBypass(reqUrl)) {
+ return undefined;
+ }
+ const proxyVar = (() => {
+ if (usingSsl) {
+ return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
+ }
+ else {
+ return process.env['http_proxy'] || process.env['HTTP_PROXY'];
+ }
+ })();
+ if (proxyVar) {
+ return new URL(proxyVar);
+ }
+ else {
+ return undefined;
+ }
+}
+proxy.getProxyUrl = getProxyUrl;
+function checkBypass(reqUrl) {
+ if (!reqUrl.hostname) {
+ return false;
+ }
+ const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
+ if (!noProxy) {
+ return false;
+ }
+ // Determine the request port
+ let reqPort;
+ if (reqUrl.port) {
+ reqPort = Number(reqUrl.port);
+ }
+ else if (reqUrl.protocol === 'http:') {
+ reqPort = 80;
+ }
+ else if (reqUrl.protocol === 'https:') {
+ reqPort = 443;
+ }
+ // Format the request hostname and hostname with port
+ const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+ if (typeof reqPort === 'number') {
+ upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+ }
+ // Compare request host against noproxy
+ for (const upperNoProxyItem of noProxy
+ .split(',')
+ .map(x => x.trim().toUpperCase())
+ .filter(x => x)) {
+ if (upperReqHosts.some(x => x === upperNoProxyItem)) {
+ return true;
+ }
+ }
+ return false;
+}
+proxy.checkBypass = checkBypass;
+
+var tunnelExports = {};
+var tunnel$1 = {
+ get exports(){ return tunnelExports; },
+ set exports(v){ tunnelExports = v; },
+};
+
+var tunnel = {};
+
+var tls = require$$1$9;
+var http = http$6;
+var https = https$3;
+var events = require$$0$f;
+var util = require$$1$7;
+
+
+tunnel.httpOverHttp = httpOverHttp;
+tunnel.httpsOverHttp = httpsOverHttp;
+tunnel.httpOverHttps = httpOverHttps;
+tunnel.httpsOverHttps = httpsOverHttps;
+
+
+function httpOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ return agent;
+}
+
+function httpsOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
+
+function httpOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ return agent;
+}
+
+function httpsOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
+
+
+function TunnelingAgent(options) {
+ var self = this;
+ self.options = options || {};
+ self.proxyOptions = self.options.proxy || {};
+ self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
+ self.requests = [];
+ self.sockets = [];
+
+ self.on('free', function onFree(socket, host, port, localAddress) {
+ var options = toOptions(host, port, localAddress);
+ for (var i = 0, len = self.requests.length; i < len; ++i) {
+ var pending = self.requests[i];
+ if (pending.host === options.host && pending.port === options.port) {
+ // Detect the request to connect same origin server,
+ // reuse the connection.
+ self.requests.splice(i, 1);
+ pending.request.onSocket(socket);
+ return;
+ }
+ }
+ socket.destroy();
+ self.removeSocket(socket);
+ });
+}
+util.inherits(TunnelingAgent, events.EventEmitter);
+
+TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
+ var self = this;
+ var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
+
+ if (self.sockets.length >= this.maxSockets) {
+ // We are over limit so we'll add it to the queue.
+ self.requests.push(options);
+ return;
+ }
+
+ // If we are under maxSockets create a new one.
+ self.createSocket(options, function(socket) {
+ socket.on('free', onFree);
+ socket.on('close', onCloseOrRemove);
+ socket.on('agentRemove', onCloseOrRemove);
+ req.onSocket(socket);
+
+ function onFree() {
+ self.emit('free', socket, options);
+ }
+
+ function onCloseOrRemove(err) {
+ self.removeSocket(socket);
+ socket.removeListener('free', onFree);
+ socket.removeListener('close', onCloseOrRemove);
+ socket.removeListener('agentRemove', onCloseOrRemove);
+ }
+ });
+};
+
+TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
+ var self = this;
+ var placeholder = {};
+ self.sockets.push(placeholder);
+
+ var connectOptions = mergeOptions({}, self.proxyOptions, {
+ method: 'CONNECT',
+ path: options.host + ':' + options.port,
+ agent: false,
+ headers: {
+ host: options.host + ':' + options.port
+ }
+ });
+ if (options.localAddress) {
+ connectOptions.localAddress = options.localAddress;
+ }
+ if (connectOptions.proxyAuth) {
+ connectOptions.headers = connectOptions.headers || {};
+ connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
+ new Buffer(connectOptions.proxyAuth).toString('base64');
+ }
+
+ debug('making CONNECT request');
+ var connectReq = self.request(connectOptions);
+ connectReq.useChunkedEncodingByDefault = false; // for v0.6
+ connectReq.once('response', onResponse); // for v0.6
+ connectReq.once('upgrade', onUpgrade); // for v0.6
+ connectReq.once('connect', onConnect); // for v0.7 or later
+ connectReq.once('error', onError);
+ connectReq.end();
+
+ function onResponse(res) {
+ // Very hacky. This is necessary to avoid http-parser leaks.
+ res.upgrade = true;
+ }
+
+ function onUpgrade(res, socket, head) {
+ // Hacky.
+ process.nextTick(function() {
+ onConnect(res, socket, head);
+ });
+ }
+
+ function onConnect(res, socket, head) {
+ connectReq.removeAllListeners();
+ socket.removeAllListeners();
+
+ if (res.statusCode !== 200) {
+ debug('tunneling socket could not be established, statusCode=%d',
+ res.statusCode);
+ socket.destroy();
+ var error = new Error('tunneling socket could not be established, ' +
+ 'statusCode=' + res.statusCode);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ if (head.length > 0) {
+ debug('got illegal response body from proxy');
+ socket.destroy();
+ var error = new Error('got illegal response body from proxy');
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ debug('tunneling connection has established');
+ self.sockets[self.sockets.indexOf(placeholder)] = socket;
+ return cb(socket);
+ }
+
+ function onError(cause) {
+ connectReq.removeAllListeners();
+
+ debug('tunneling socket could not be established, cause=%s\n',
+ cause.message, cause.stack);
+ var error = new Error('tunneling socket could not be established, ' +
+ 'cause=' + cause.message);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ }
+};
+
+TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
+ var pos = this.sockets.indexOf(socket);
+ if (pos === -1) {
+ return;
+ }
+ this.sockets.splice(pos, 1);
+
+ var pending = this.requests.shift();
+ if (pending) {
+ // If we have pending requests and a socket gets closed a new one
+ // needs to be created to take over in the pool for the one that closed.
+ this.createSocket(pending, function(socket) {
+ pending.request.onSocket(socket);
+ });
+ }
+};
+
+function createSecureSocket(options, cb) {
+ var self = this;
+ TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
+ var hostHeader = options.request.getHeader('host');
+ var tlsOptions = mergeOptions({}, self.options, {
+ socket: socket,
+ servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
+ });
+
+ // 0 is dummy port for v0.6
+ var secureSocket = tls.connect(0, tlsOptions);
+ self.sockets[self.sockets.indexOf(socket)] = secureSocket;
+ cb(secureSocket);
+ });
+}
+
+
+function toOptions(host, port, localAddress) {
+ if (typeof host === 'string') { // since v0.10
+ return {
+ host: host,
+ port: port,
+ localAddress: localAddress
+ };
+ }
+ return host; // for v0.11 or later
+}
+
+function mergeOptions(target) {
+ for (var i = 1, len = arguments.length; i < len; ++i) {
+ var overrides = arguments[i];
+ if (typeof overrides === 'object') {
+ var keys = Object.keys(overrides);
+ for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
+ var k = keys[j];
+ if (overrides[k] !== undefined) {
+ target[k] = overrides[k];
+ }
+ }
+ }
+ }
+ return target;
+}
+
+
+var debug;
+if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
+ debug = function() {
+ var args = Array.prototype.slice.call(arguments);
+ if (typeof args[0] === 'string') {
+ args[0] = 'TUNNEL: ' + args[0];
+ } else {
+ args.unshift('TUNNEL:');
+ }
+ console.error.apply(console, args);
+ };
+} else {
+ debug = function() {};
+}
+tunnel.debug = debug; // for test
+
+(function (module) {
+ module.exports = tunnel;
+} (tunnel$1));
+
+(function (exports) {
+ /* eslint-disable @typescript-eslint/no-explicit-any */
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ }));
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ });
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
+ const http = __importStar(http$6);
+ const https = __importStar(https$3);
+ const pm = __importStar(proxy);
+ const tunnel = __importStar(tunnelExports);
+ var HttpCodes;
+ (function (HttpCodes) {
+ HttpCodes[HttpCodes["OK"] = 200] = "OK";
+ HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
+ HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
+ HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
+ HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
+ HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
+ HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
+ HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
+ HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+ HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
+ HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
+ HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
+ HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
+ HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
+ HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
+ HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+ HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
+ HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+ HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
+ HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
+ HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
+ HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
+ HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
+ HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
+ HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
+ HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+ HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
+ })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
+ var Headers;
+ (function (Headers) {
+ Headers["Accept"] = "accept";
+ Headers["ContentType"] = "content-type";
+ })(Headers = exports.Headers || (exports.Headers = {}));
+ var MediaTypes;
+ (function (MediaTypes) {
+ MediaTypes["ApplicationJson"] = "application/json";
+ })(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
+ /**
+ * Returns the proxy URL, depending upon the supplied url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+ function getProxyUrl(serverUrl) {
+ const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+ return proxyUrl ? proxyUrl.href : '';
+ }
+ exports.getProxyUrl = getProxyUrl;
+ const HttpRedirectCodes = [
+ HttpCodes.MovedPermanently,
+ HttpCodes.ResourceMoved,
+ HttpCodes.SeeOther,
+ HttpCodes.TemporaryRedirect,
+ HttpCodes.PermanentRedirect
+ ];
+ const HttpResponseRetryCodes = [
+ HttpCodes.BadGateway,
+ HttpCodes.ServiceUnavailable,
+ HttpCodes.GatewayTimeout
+ ];
+ const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
+ const ExponentialBackoffCeiling = 10;
+ const ExponentialBackoffTimeSlice = 5;
+ class HttpClientError extends Error {
+ constructor(message, statusCode) {
+ super(message);
+ this.name = 'HttpClientError';
+ this.statusCode = statusCode;
+ Object.setPrototypeOf(this, HttpClientError.prototype);
+ }
+ }
+ exports.HttpClientError = HttpClientError;
+ class HttpClientResponse {
+ constructor(message) {
+ this.message = message;
+ }
+ readBody() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ let output = Buffer.alloc(0);
+ this.message.on('data', (chunk) => {
+ output = Buffer.concat([output, chunk]);
+ });
+ this.message.on('end', () => {
+ resolve(output.toString());
+ });
+ }));
+ });
+ }
+ }
+ exports.HttpClientResponse = HttpClientResponse;
+ function isHttps(requestUrl) {
+ const parsedUrl = new URL(requestUrl);
+ return parsedUrl.protocol === 'https:';
+ }
+ exports.isHttps = isHttps;
+ class HttpClient {
+ constructor(userAgent, handlers, requestOptions) {
+ this._ignoreSslError = false;
+ this._allowRedirects = true;
+ this._allowRedirectDowngrade = false;
+ this._maxRedirects = 50;
+ this._allowRetries = false;
+ this._maxRetries = 1;
+ this._keepAlive = false;
+ this._disposed = false;
+ this.userAgent = userAgent;
+ this.handlers = handlers || [];
+ this.requestOptions = requestOptions;
+ if (requestOptions) {
+ if (requestOptions.ignoreSslError != null) {
+ this._ignoreSslError = requestOptions.ignoreSslError;
+ }
+ this._socketTimeout = requestOptions.socketTimeout;
+ if (requestOptions.allowRedirects != null) {
+ this._allowRedirects = requestOptions.allowRedirects;
+ }
+ if (requestOptions.allowRedirectDowngrade != null) {
+ this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+ }
+ if (requestOptions.maxRedirects != null) {
+ this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+ }
+ if (requestOptions.keepAlive != null) {
+ this._keepAlive = requestOptions.keepAlive;
+ }
+ if (requestOptions.allowRetries != null) {
+ this._allowRetries = requestOptions.allowRetries;
+ }
+ if (requestOptions.maxRetries != null) {
+ this._maxRetries = requestOptions.maxRetries;
+ }
+ }
+ }
+ options(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ get(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('GET', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ del(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('DELETE', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ post(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('POST', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ patch(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PATCH', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ put(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PUT', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ head(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('HEAD', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ sendStream(verb, requestUrl, stream, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request(verb, requestUrl, stream, additionalHeaders);
+ });
+ }
+ /**
+ * Gets a typed object from an endpoint
+ * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
+ */
+ getJson(requestUrl, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ const res = yield this.get(requestUrl, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ postJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.post(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ putJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.put(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ patchJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.patch(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ /**
+ * Makes a raw http request.
+ * All other methods such as get, post, patch, and request ultimately call this.
+ * Prefer get, del, post and patch
+ */
+ request(verb, requestUrl, data, headers) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this._disposed) {
+ throw new Error('Client has already been disposed.');
+ }
+ const parsedUrl = new URL(requestUrl);
+ let info = this._prepareRequest(verb, parsedUrl, headers);
+ // Only perform retries on reads since writes may not be idempotent.
+ const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
+ ? this._maxRetries + 1
+ : 1;
+ let numTries = 0;
+ let response;
+ do {
+ response = yield this.requestRaw(info, data);
+ // Check if it's an authentication challenge
+ if (response &&
+ response.message &&
+ response.message.statusCode === HttpCodes.Unauthorized) {
+ let authenticationHandler;
+ for (const handler of this.handlers) {
+ if (handler.canHandleAuthentication(response)) {
+ authenticationHandler = handler;
+ break;
+ }
+ }
+ if (authenticationHandler) {
+ return authenticationHandler.handleAuthentication(this, info, data);
+ }
+ else {
+ // We have received an unauthorized response but have no handlers to handle it.
+ // Let the response return to the caller.
+ return response;
+ }
+ }
+ let redirectsRemaining = this._maxRedirects;
+ while (response.message.statusCode &&
+ HttpRedirectCodes.includes(response.message.statusCode) &&
+ this._allowRedirects &&
+ redirectsRemaining > 0) {
+ const redirectUrl = response.message.headers['location'];
+ if (!redirectUrl) {
+ // if there's no location to redirect to, we won't
+ break;
+ }
+ const parsedRedirectUrl = new URL(redirectUrl);
+ if (parsedUrl.protocol === 'https:' &&
+ parsedUrl.protocol !== parsedRedirectUrl.protocol &&
+ !this._allowRedirectDowngrade) {
+ throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
+ }
+ // we need to finish reading the response before reassigning response
+ // which will leak the open socket.
+ yield response.readBody();
+ // strip authorization header if redirected to a different hostname
+ if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+ for (const header in headers) {
+ // header names are case insensitive
+ if (header.toLowerCase() === 'authorization') {
+ delete headers[header];
+ }
+ }
+ }
+ // let's make the request with the new redirectUrl
+ info = this._prepareRequest(verb, parsedRedirectUrl, headers);
+ response = yield this.requestRaw(info, data);
+ redirectsRemaining--;
+ }
+ if (!response.message.statusCode ||
+ !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+ // If not a retry code, return immediately instead of retrying
+ return response;
+ }
+ numTries += 1;
+ if (numTries < maxTries) {
+ yield response.readBody();
+ yield this._performExponentialBackoff(numTries);
+ }
+ } while (numTries < maxTries);
+ return response;
+ });
+ }
+ /**
+ * Needs to be called if keepAlive is set to true in request options.
+ */
+ dispose() {
+ if (this._agent) {
+ this._agent.destroy();
+ }
+ this._disposed = true;
+ }
+ /**
+ * Raw request.
+ * @param info
+ * @param data
+ */
+ requestRaw(info, data) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => {
+ function callbackForResult(err, res) {
+ if (err) {
+ reject(err);
+ }
+ else if (!res) {
+ // If `err` is not passed, then `res` must be passed.
+ reject(new Error('Unknown error'));
+ }
+ else {
+ resolve(res);
+ }
+ }
+ this.requestRawWithCallback(info, data, callbackForResult);
+ });
+ });
+ }
+ /**
+ * Raw request with callback.
+ * @param info
+ * @param data
+ * @param onResult
+ */
+ requestRawWithCallback(info, data, onResult) {
+ if (typeof data === 'string') {
+ if (!info.options.headers) {
+ info.options.headers = {};
+ }
+ info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
+ }
+ let callbackCalled = false;
+ function handleResult(err, res) {
+ if (!callbackCalled) {
+ callbackCalled = true;
+ onResult(err, res);
+ }
+ }
+ const req = info.httpModule.request(info.options, (msg) => {
+ const res = new HttpClientResponse(msg);
+ handleResult(undefined, res);
+ });
+ let socket;
+ req.on('socket', sock => {
+ socket = sock;
+ });
+ // If we ever get disconnected, we want the socket to timeout eventually
+ req.setTimeout(this._socketTimeout || 3 * 60000, () => {
+ if (socket) {
+ socket.end();
+ }
+ handleResult(new Error(`Request timeout: ${info.options.path}`));
+ });
+ req.on('error', function (err) {
+ // err has statusCode property
+ // res should have headers
+ handleResult(err);
+ });
+ if (data && typeof data === 'string') {
+ req.write(data, 'utf8');
+ }
+ if (data && typeof data !== 'string') {
+ data.on('close', function () {
+ req.end();
+ });
+ data.pipe(req);
+ }
+ else {
+ req.end();
+ }
+ }
+ /**
+ * Gets an http agent. This function is useful when you need an http agent that handles
+ * routing through a proxy server - depending upon the url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+ getAgent(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ return this._getAgent(parsedUrl);
+ }
+ _prepareRequest(method, requestUrl, headers) {
+ const info = {};
+ info.parsedUrl = requestUrl;
+ const usingSsl = info.parsedUrl.protocol === 'https:';
+ info.httpModule = usingSsl ? https : http;
+ const defaultPort = usingSsl ? 443 : 80;
+ info.options = {};
+ info.options.host = info.parsedUrl.hostname;
+ info.options.port = info.parsedUrl.port
+ ? parseInt(info.parsedUrl.port)
+ : defaultPort;
+ info.options.path =
+ (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
+ info.options.method = method;
+ info.options.headers = this._mergeHeaders(headers);
+ if (this.userAgent != null) {
+ info.options.headers['user-agent'] = this.userAgent;
+ }
+ info.options.agent = this._getAgent(info.parsedUrl);
+ // gives handlers an opportunity to participate
+ if (this.handlers) {
+ for (const handler of this.handlers) {
+ handler.prepareRequest(info.options);
+ }
+ }
+ return info;
+ }
+ _mergeHeaders(headers) {
+ if (this.requestOptions && this.requestOptions.headers) {
+ return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+ }
+ return lowercaseKeys(headers || {});
+ }
+ _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
+ let clientHeader;
+ if (this.requestOptions && this.requestOptions.headers) {
+ clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
+ }
+ return additionalHeaders[header] || clientHeader || _default;
+ }
+ _getAgent(parsedUrl) {
+ let agent;
+ const proxyUrl = pm.getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (this._keepAlive && useProxy) {
+ agent = this._proxyAgent;
+ }
+ if (this._keepAlive && !useProxy) {
+ agent = this._agent;
+ }
+ // if agent is already assigned use that agent.
+ if (agent) {
+ return agent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ let maxSockets = 100;
+ if (this.requestOptions) {
+ maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+ }
+ // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
+ if (proxyUrl && proxyUrl.hostname) {
+ const agentOptions = {
+ maxSockets,
+ keepAlive: this._keepAlive,
+ proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
+ proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+ })), { host: proxyUrl.hostname, port: proxyUrl.port })
+ };
+ let tunnelAgent;
+ const overHttps = proxyUrl.protocol === 'https:';
+ if (usingSsl) {
+ tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+ }
+ else {
+ tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+ }
+ agent = tunnelAgent(agentOptions);
+ this._proxyAgent = agent;
+ }
+ // if reusing agent across request and tunneling agent isn't assigned create a new agent
+ if (this._keepAlive && !agent) {
+ const options = { keepAlive: this._keepAlive, maxSockets };
+ agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
+ this._agent = agent;
+ }
+ // if not using private agent and tunnel agent isn't setup then use global agent
+ if (!agent) {
+ agent = usingSsl ? https.globalAgent : http.globalAgent;
+ }
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ agent.options = Object.assign(agent.options || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return agent;
+ }
+ _performExponentialBackoff(retryNumber) {
+ return __awaiter(this, void 0, void 0, function* () {
+ retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+ const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+ return new Promise(resolve => setTimeout(() => resolve(), ms));
+ });
+ }
+ _processResponse(res, options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
+ const statusCode = res.message.statusCode || 0;
+ const response = {
+ statusCode,
+ result: null,
+ headers: {}
+ };
+ // not found leads to null obj returned
+ if (statusCode === HttpCodes.NotFound) {
+ resolve(response);
+ }
+ // get the result from the body
+ function dateTimeDeserializer(key, value) {
+ if (typeof value === 'string') {
+ const a = new Date(value);
+ if (!isNaN(a.valueOf())) {
+ return a;
+ }
+ }
+ return value;
+ }
+ let obj;
+ let contents;
+ try {
+ contents = yield res.readBody();
+ if (contents && contents.length > 0) {
+ if (options && options.deserializeDates) {
+ obj = JSON.parse(contents, dateTimeDeserializer);
+ }
+ else {
+ obj = JSON.parse(contents);
+ }
+ response.result = obj;
+ }
+ response.headers = res.message.headers;
+ }
+ catch (err) {
+ // Invalid resource (contents not json); leaving result obj null
+ }
+ // note that 3xx redirects are handled by the http layer.
+ if (statusCode > 299) {
+ let msg;
+ // if exception/error in body, attempt to get better error
+ if (obj && obj.message) {
+ msg = obj.message;
+ }
+ else if (contents && contents.length > 0) {
+ // it may be the case that the exception is in the body message as string
+ msg = contents;
+ }
+ else {
+ msg = `Failed request: (${statusCode})`;
+ }
+ const err = new HttpClientError(msg, statusCode);
+ err.result = response.result;
+ reject(err);
+ }
+ else {
+ resolve(response);
+ }
+ }));
+ });
+ }
+ }
+ exports.HttpClient = HttpClient;
+ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
+
+} (lib));
+
+var auth = {};
+
+var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(auth, "__esModule", { value: true });
+auth.PersonalAccessTokenCredentialHandler = auth.BearerCredentialHandler = auth.BasicCredentialHandler = void 0;
+class BasicCredentialHandler {
+ constructor(username, password) {
+ this.username = username;
+ this.password = password;
+ }
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
+}
+auth.BasicCredentialHandler = BasicCredentialHandler;
+class BearerCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Bearer ${this.token}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
+}
+auth.BearerCredentialHandler = BearerCredentialHandler;
+class PersonalAccessTokenCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
+}
+auth.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
+
+var hasRequiredOidcUtils;
+
+function requireOidcUtils () {
+ if (hasRequiredOidcUtils) return oidcUtils;
+ hasRequiredOidcUtils = 1;
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+ Object.defineProperty(oidcUtils, "__esModule", { value: true });
+ oidcUtils.OidcClient = void 0;
+ const http_client_1 = lib;
+ const auth_1 = auth;
+ const core_1 = requireCore();
+ class OidcClient {
+ static createHttpClient(allowRetry = true, maxRetry = 10) {
+ const requestOptions = {
+ allowRetries: allowRetry,
+ maxRetries: maxRetry
+ };
+ return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
+ }
+ static getRequestToken() {
+ const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
+ if (!token) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
+ }
+ return token;
+ }
+ static getIDTokenUrl() {
+ const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
+ if (!runtimeUrl) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
+ }
+ return runtimeUrl;
+ }
+ static getCall(id_token_url) {
+ var _a;
+ return __awaiter(this, void 0, void 0, function* () {
+ const httpclient = OidcClient.createHttpClient();
+ const res = yield httpclient
+ .getJson(id_token_url)
+ .catch(error => {
+ throw new Error(`Failed to get ID Token. \n
+ Error Code : ${error.statusCode}\n
+ Error Message: ${error.result.message}`);
+ });
+ const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
+ if (!id_token) {
+ throw new Error('Response json body do not have ID Token field');
+ }
+ return id_token;
+ });
+ }
+ static getIDToken(audience) {
+ return __awaiter(this, void 0, void 0, function* () {
+ try {
+ // New ID Token is requested from action service
+ let id_token_url = OidcClient.getIDTokenUrl();
+ if (audience) {
+ const encodedAudience = encodeURIComponent(audience);
+ id_token_url = `${id_token_url}&audience=${encodedAudience}`;
+ }
+ core_1.debug(`ID token url is ${id_token_url}`);
+ const id_token = yield OidcClient.getCall(id_token_url);
+ core_1.setSecret(id_token);
+ return id_token;
+ }
+ catch (error) {
+ throw new Error(`Error message: ${error.message}`);
+ }
+ });
+ }
+ }
+ oidcUtils.OidcClient = OidcClient;
+
+ return oidcUtils;
+}
+
+var summary = {};
+
+var hasRequiredSummary;
+
+function requireSummary () {
+ if (hasRequiredSummary) return summary;
+ hasRequiredSummary = 1;
+ (function (exports) {
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
+ const os_1 = require$$0$h;
+ const fs_1 = require$$0$e;
+ const { access, appendFile, writeFile } = fs_1.promises;
+ exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
+ exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
+ class Summary {
+ constructor() {
+ this._buffer = '';
+ }
+ /**
+ * Finds the summary file path from the environment, rejects if env var is not found or file does not exist
+ * Also checks r/w permissions.
+ *
+ * @returns step summary file path
+ */
+ filePath() {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this._filePath) {
+ return this._filePath;
+ }
+ const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];
+ if (!pathFromEnv) {
+ throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
+ }
+ try {
+ yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);
+ }
+ catch (_a) {
+ throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
+ }
+ this._filePath = pathFromEnv;
+ return this._filePath;
+ });
+ }
+ /**
+ * Wraps content in an HTML tag, adding any HTML attributes
+ *
+ * @param {string} tag HTML tag to wrap
+ * @param {string | null} content content within the tag
+ * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
+ *
+ * @returns {string} content wrapped in HTML element
+ */
+ wrap(tag, content, attrs = {}) {
+ const htmlAttrs = Object.entries(attrs)
+ .map(([key, value]) => ` ${key}="${value}"`)
+ .join('');
+ if (!content) {
+ return `<${tag}${htmlAttrs}>`;
+ }
+ return `<${tag}${htmlAttrs}>${content}${tag}>`;
+ }
+ /**
+ * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
+ *
+ * @param {SummaryWriteOptions} [options] (optional) options for write operation
+ *
+ * @returns {Promise} summary instance
+ */
+ write(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
+ const filePath = yield this.filePath();
+ const writeFunc = overwrite ? writeFile : appendFile;
+ yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
+ return this.emptyBuffer();
+ });
+ }
+ /**
+ * Clears the summary buffer and wipes the summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ clear() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.emptyBuffer().write({ overwrite: true });
+ });
+ }
+ /**
+ * Returns the current summary buffer as a string
+ *
+ * @returns {string} string of summary buffer
+ */
+ stringify() {
+ return this._buffer;
+ }
+ /**
+ * If the summary buffer is empty
+ *
+ * @returns {boolen} true if the buffer is empty
+ */
+ isEmptyBuffer() {
+ return this._buffer.length === 0;
+ }
+ /**
+ * Resets the summary buffer without writing to summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ emptyBuffer() {
+ this._buffer = '';
+ return this;
+ }
+ /**
+ * Adds raw text to the summary buffer
+ *
+ * @param {string} text content to add
+ * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addRaw(text, addEOL = false) {
+ this._buffer += text;
+ return addEOL ? this.addEOL() : this;
+ }
+ /**
+ * Adds the operating system-specific end-of-line marker to the buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addEOL() {
+ return this.addRaw(os_1.EOL);
+ }
+ /**
+ * Adds an HTML codeblock to the summary buffer
+ *
+ * @param {string} code content to render within fenced code block
+ * @param {string} lang (optional) language to syntax highlight code
+ *
+ * @returns {Summary} summary instance
+ */
+ addCodeBlock(code, lang) {
+ const attrs = Object.assign({}, (lang && { lang }));
+ const element = this.wrap('pre', this.wrap('code', code), attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML list to the summary buffer
+ *
+ * @param {string[]} items list of items to render
+ * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addList(items, ordered = false) {
+ const tag = ordered ? 'ol' : 'ul';
+ const listItems = items.map(item => this.wrap('li', item)).join('');
+ const element = this.wrap(tag, listItems);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML table to the summary buffer
+ *
+ * @param {SummaryTableCell[]} rows table rows
+ *
+ * @returns {Summary} summary instance
+ */
+ addTable(rows) {
+ const tableBody = rows
+ .map(row => {
+ const cells = row
+ .map(cell => {
+ if (typeof cell === 'string') {
+ return this.wrap('td', cell);
+ }
+ const { header, data, colspan, rowspan } = cell;
+ const tag = header ? 'th' : 'td';
+ const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
+ return this.wrap(tag, data, attrs);
+ })
+ .join('');
+ return this.wrap('tr', cells);
+ })
+ .join('');
+ const element = this.wrap('table', tableBody);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds a collapsable HTML details element to the summary buffer
+ *
+ * @param {string} label text for the closed state
+ * @param {string} content collapsable content
+ *
+ * @returns {Summary} summary instance
+ */
+ addDetails(label, content) {
+ const element = this.wrap('details', this.wrap('summary', label) + content);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML image tag to the summary buffer
+ *
+ * @param {string} src path to the image you to embed
+ * @param {string} alt text description of the image
+ * @param {SummaryImageOptions} options (optional) addition image attributes
+ *
+ * @returns {Summary} summary instance
+ */
+ addImage(src, alt, options) {
+ const { width, height } = options || {};
+ const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
+ const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML section heading element
+ *
+ * @param {string} text heading text
+ * @param {number | string} [level=1] (optional) the heading level, default: 1
+ *
+ * @returns {Summary} summary instance
+ */
+ addHeading(text, level) {
+ const tag = `h${level}`;
+ const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
+ ? tag
+ : 'h1';
+ const element = this.wrap(allowedTag, text);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML thematic break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addSeparator() {
+ const element = this.wrap('hr', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML line break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addBreak() {
+ const element = this.wrap('br', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML blockquote to the summary buffer
+ *
+ * @param {string} text quote text
+ * @param {string} cite (optional) citation url
+ *
+ * @returns {Summary} summary instance
+ */
+ addQuote(text, cite) {
+ const attrs = Object.assign({}, (cite && { cite }));
+ const element = this.wrap('blockquote', text, attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML anchor tag to the summary buffer
+ *
+ * @param {string} text link text/content
+ * @param {string} href hyperlink
+ *
+ * @returns {Summary} summary instance
+ */
+ addLink(text, href) {
+ const element = this.wrap('a', text, { href });
+ return this.addRaw(element).addEOL();
+ }
+ }
+ const _summary = new Summary();
+ /**
+ * @deprecated use `core.summary`
+ */
+ exports.markdownSummary = _summary;
+ exports.summary = _summary;
+
+} (summary));
+ return summary;
+}
+
+var pathUtils = {};
+
+var hasRequiredPathUtils;
+
+function requirePathUtils () {
+ if (hasRequiredPathUtils) return pathUtils;
+ hasRequiredPathUtils = 1;
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ }));
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ });
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+ Object.defineProperty(pathUtils, "__esModule", { value: true });
+ pathUtils.toPlatformPath = pathUtils.toWin32Path = pathUtils.toPosixPath = void 0;
+ const path = __importStar(require$$0$c);
+ /**
+ * toPosixPath converts the given path to the posix form. On Windows, \\ will be
+ * replaced with /.
+ *
+ * @param pth. Path to transform.
+ * @return string Posix path.
+ */
+ function toPosixPath(pth) {
+ return pth.replace(/[\\]/g, '/');
+ }
+ pathUtils.toPosixPath = toPosixPath;
+ /**
+ * toWin32Path converts the given path to the win32 form. On Linux, / will be
+ * replaced with \\.
+ *
+ * @param pth. Path to transform.
+ * @return string Win32 path.
+ */
+ function toWin32Path(pth) {
+ return pth.replace(/[/]/g, '\\');
+ }
+ pathUtils.toWin32Path = toWin32Path;
+ /**
+ * toPlatformPath converts the given path to a platform-specific path. It does
+ * this by replacing instances of / and \ with the platform-specific path
+ * separator.
+ *
+ * @param pth The path to platformize.
+ * @return string The platform-specific path.
+ */
+ function toPlatformPath(pth) {
+ return pth.replace(/[/\\]/g, path.sep);
+ }
+ pathUtils.toPlatformPath = toPlatformPath;
+
+ return pathUtils;
+}
+
+var hasRequiredCore;
+
+function requireCore () {
+ if (hasRequiredCore) return core$1;
+ hasRequiredCore = 1;
+ (function (exports) {
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ }));
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ });
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
+ const command_1 = command;
+ const file_command_1 = fileCommand;
+ const utils_1 = utils;
+ const os = __importStar(require$$0$h);
+ const path = __importStar(require$$0$c);
+ const oidc_utils_1 = requireOidcUtils();
+ /**
+ * The code to exit an action
+ */
+ var ExitCode;
+ (function (ExitCode) {
+ /**
+ * A code indicating that the action was successful
+ */
+ ExitCode[ExitCode["Success"] = 0] = "Success";
+ /**
+ * A code indicating that the action was a failure
+ */
+ ExitCode[ExitCode["Failure"] = 1] = "Failure";
+ })(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
+ //-----------------------------------------------------------------------
+ // Variables
+ //-----------------------------------------------------------------------
+ /**
+ * Sets env variable for this action and future actions in the job
+ * @param name the name of the variable to set
+ * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ function exportVariable(name, val) {
+ const convertedVal = utils_1.toCommandValue(val);
+ process.env[name] = convertedVal;
+ const filePath = process.env['GITHUB_ENV'] || '';
+ if (filePath) {
+ return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));
+ }
+ command_1.issueCommand('set-env', { name }, convertedVal);
+ }
+ exports.exportVariable = exportVariable;
+ /**
+ * Registers a secret which will get masked from logs
+ * @param secret value of the secret
+ */
+ function setSecret(secret) {
+ command_1.issueCommand('add-mask', {}, secret);
+ }
+ exports.setSecret = setSecret;
+ /**
+ * Prepends inputPath to the PATH (for this action and future actions)
+ * @param inputPath
+ */
+ function addPath(inputPath) {
+ const filePath = process.env['GITHUB_PATH'] || '';
+ if (filePath) {
+ file_command_1.issueFileCommand('PATH', inputPath);
+ }
+ else {
+ command_1.issueCommand('add-path', {}, inputPath);
+ }
+ process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
+ }
+ exports.addPath = addPath;
+ /**
+ * Gets the value of an input.
+ * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
+ * Returns an empty string if the value is not defined.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string
+ */
+ function getInput(name, options) {
+ const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
+ if (options && options.required && !val) {
+ throw new Error(`Input required and not supplied: ${name}`);
+ }
+ if (options && options.trimWhitespace === false) {
+ return val;
+ }
+ return val.trim();
+ }
+ exports.getInput = getInput;
+ /**
+ * Gets the values of an multiline input. Each value is also trimmed.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string[]
+ *
+ */
+ function getMultilineInput(name, options) {
+ const inputs = getInput(name, options)
+ .split('\n')
+ .filter(x => x !== '');
+ if (options && options.trimWhitespace === false) {
+ return inputs;
+ }
+ return inputs.map(input => input.trim());
+ }
+ exports.getMultilineInput = getMultilineInput;
+ /**
+ * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
+ * Support boolean input list: `true | True | TRUE | false | False | FALSE` .
+ * The return value is also in boolean type.
+ * ref: https://yaml.org/spec/1.2/spec.html#id2804923
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns boolean
+ */
+ function getBooleanInput(name, options) {
+ const trueValue = ['true', 'True', 'TRUE'];
+ const falseValue = ['false', 'False', 'FALSE'];
+ const val = getInput(name, options);
+ if (trueValue.includes(val))
+ return true;
+ if (falseValue.includes(val))
+ return false;
+ throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
+ `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
+ }
+ exports.getBooleanInput = getBooleanInput;
+ /**
+ * Sets the value of an output.
+ *
+ * @param name name of the output to set
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ function setOutput(name, value) {
+ const filePath = process.env['GITHUB_OUTPUT'] || '';
+ if (filePath) {
+ return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));
+ }
+ process.stdout.write(os.EOL);
+ command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));
+ }
+ exports.setOutput = setOutput;
+ /**
+ * Enables or disables the echoing of commands into stdout for the rest of the step.
+ * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
+ *
+ */
+ function setCommandEcho(enabled) {
+ command_1.issue('echo', enabled ? 'on' : 'off');
+ }
+ exports.setCommandEcho = setCommandEcho;
+ //-----------------------------------------------------------------------
+ // Results
+ //-----------------------------------------------------------------------
+ /**
+ * Sets the action status to failed.
+ * When the action exits it will be with an exit code of 1
+ * @param message add error issue message
+ */
+ function setFailed(message) {
+ process.exitCode = ExitCode.Failure;
+ error(message);
+ }
+ exports.setFailed = setFailed;
+ //-----------------------------------------------------------------------
+ // Logging Commands
+ //-----------------------------------------------------------------------
+ /**
+ * Gets whether Actions Step Debug is on or not
+ */
+ function isDebug() {
+ return process.env['RUNNER_DEBUG'] === '1';
+ }
+ exports.isDebug = isDebug;
+ /**
+ * Writes debug message to user log
+ * @param message debug message
+ */
+ function debug(message) {
+ command_1.issueCommand('debug', {}, message);
+ }
+ exports.debug = debug;
+ /**
+ * Adds an error issue
+ * @param message error issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+ function error(message, properties = {}) {
+ command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+ }
+ exports.error = error;
+ /**
+ * Adds a warning issue
+ * @param message warning issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+ function warning(message, properties = {}) {
+ command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+ }
+ exports.warning = warning;
+ /**
+ * Adds a notice issue
+ * @param message notice issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+ function notice(message, properties = {}) {
+ command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+ }
+ exports.notice = notice;
+ /**
+ * Writes info to log with console.log.
+ * @param message info message
+ */
+ function info(message) {
+ process.stdout.write(message + os.EOL);
+ }
+ exports.info = info;
+ /**
+ * Begin an output group.
+ *
+ * Output until the next `groupEnd` will be foldable in this group
+ *
+ * @param name The name of the output group
+ */
+ function startGroup(name) {
+ command_1.issue('group', name);
+ }
+ exports.startGroup = startGroup;
+ /**
+ * End an output group.
+ */
+ function endGroup() {
+ command_1.issue('endgroup');
+ }
+ exports.endGroup = endGroup;
+ /**
+ * Wrap an asynchronous function call in a group.
+ *
+ * Returns the same type as the function itself.
+ *
+ * @param name The name of the group
+ * @param fn The function to wrap in the group
+ */
+ function group(name, fn) {
+ return __awaiter(this, void 0, void 0, function* () {
+ startGroup(name);
+ let result;
+ try {
+ result = yield fn();
+ }
+ finally {
+ endGroup();
+ }
+ return result;
+ });
+ }
+ exports.group = group;
+ //-----------------------------------------------------------------------
+ // Wrapper action state
+ //-----------------------------------------------------------------------
+ /**
+ * Saves state for current action, the state can only be retrieved by this action's post job execution.
+ *
+ * @param name name of the state to store
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ function saveState(name, value) {
+ const filePath = process.env['GITHUB_STATE'] || '';
+ if (filePath) {
+ return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));
+ }
+ command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));
+ }
+ exports.saveState = saveState;
+ /**
+ * Gets the value of an state set by this action's main execution.
+ *
+ * @param name name of the state to get
+ * @returns string
+ */
+ function getState(name) {
+ return process.env[`STATE_${name}`] || '';
+ }
+ exports.getState = getState;
+ function getIDToken(aud) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return yield oidc_utils_1.OidcClient.getIDToken(aud);
+ });
+ }
+ exports.getIDToken = getIDToken;
+ /**
+ * Summary exports
+ */
+ var summary_1 = requireSummary();
+ Object.defineProperty(exports, "summary", { enumerable: true, get: function () { return summary_1.summary; } });
+ /**
+ * @deprecated use core.summary
+ */
+ var summary_2 = requireSummary();
+ Object.defineProperty(exports, "markdownSummary", { enumerable: true, get: function () { return summary_2.markdownSummary; } });
+ /**
+ * Path exports
+ */
+ var path_utils_1 = requirePathUtils();
+ Object.defineProperty(exports, "toPosixPath", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } });
+ Object.defineProperty(exports, "toWin32Path", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } });
+ Object.defineProperty(exports, "toPlatformPath", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } });
+
+} (core$1));
+ return core$1;
+}
+
+const { inspect } = require$$1$7;
+
+const through = through2Exports;
+const core = requireCore();
+const pino$1 = pinoExports;
+
+const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = {
+ trace: "debug",
+ debug: "debug",
+ info: "info",
+ warn: "warning",
+ error: "error",
+ fatal: "error",
+};
+
+const transport$1 = through.obj(function (chunk, enc, cb) {
+ const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk);
+ const levelLabel = pino$1.levels.labels[level] || level;
+ const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel];
+
+ const output = [
+ msg,
+ Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "",
+ ]
+ .join("\n")
+ .trim();
+
+ if (logMethodName in core) {
+ core[logMethodName](output);
+ } else {
+ core.error(`"${level}" is not a known log level - ${output}`);
+ }
+
+ cb();
+});
+
+var pinoTransportGithubActions = { transport: transport$1 };
+
+const ProbotExports = requireLib();
+const pino = pinoExports;
+
+const { transport } = pinoTransportGithubActions;
+
+var adapterGithubActions = { ...ProbotExports, run };
+
+async function run(app) {
+ const log = pino({}, transport);
+
+ const githubToken =
+ process.env.GITHUB_TOKEN ||
+ process.env.INPUT_GITHUB_TOKEN ||
+ process.env.INPUT_TOKEN;
+
+ if (!githubToken) {
+ log.error(
+ "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage"
+ );
+ return;
+ }
+
+ const envVariablesMissing = [
+ "GITHUB_RUN_ID",
+ "GITHUB_EVENT_NAME",
+ "GITHUB_EVENT_PATH",
+ ].filter((name) => !process.env[name]);
+
+ if (envVariablesMissing.length) {
+ log.error(
+ `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join(
+ ", "
+ )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables`
+ );
+ return;
+ }
+
+ const probot = ProbotExports.createProbot({
+ overrides: {
+ githubToken,
+ log,
+ },
+ });
+
+ await probot.load(app);
+
+ return probot
+ .receive({
+ id: process.env.GITHUB_RUN_ID,
+ name: process.env.GITHUB_EVENT_NAME,
+ payload: commonjsRequire(process.env.GITHUB_EVENT_PATH),
+ })
+ .catch((error) => {
+ probot.log.error(error);
+ });
+}
+
+/**
+ * Returns a `Buffer` instance from the given data URI `uri`.
+ *
+ * @param {String} uri Data URI to turn into a Buffer instance
+ * @returns {Buffer} Buffer instance from Data URI
+ * @api public
+ */
+function dataUriToBuffer(uri) {
+ if (!/^data:/i.test(uri)) {
+ throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
+ }
+ // strip newlines
+ uri = uri.replace(/\r?\n/g, '');
+ // split the URI up into the "metadata" and the "data" portions
+ const firstComma = uri.indexOf(',');
+ if (firstComma === -1 || firstComma <= 4) {
+ throw new TypeError('malformed data: URI');
+ }
+ // remove the "data:" scheme and parse the metadata
+ const meta = uri.substring(5, firstComma).split(';');
+ let charset = '';
+ let base64 = false;
+ const type = meta[0] || 'text/plain';
+ let typeFull = type;
+ for (let i = 1; i < meta.length; i++) {
+ if (meta[i] === 'base64') {
+ base64 = true;
+ }
+ else if (meta[i]) {
+ typeFull += `;${meta[i]}`;
+ if (meta[i].indexOf('charset=') === 0) {
+ charset = meta[i].substring(8);
+ }
+ }
+ }
+ // defaults to US-ASCII only if type is not provided
+ if (!meta[0] && !charset.length) {
+ typeFull += ';charset=US-ASCII';
+ charset = 'US-ASCII';
+ }
+ // get the encoded data portion and decode URI-encoded chars
+ const encoding = base64 ? 'base64' : 'ascii';
+ const data = unescape(uri.substring(firstComma + 1));
+ const buffer = Buffer.from(data, encoding);
+ // set `.type` and `.typeFull` properties to MIME type
+ buffer.type = type;
+ buffer.typeFull = typeFull;
+ // set the `.charset` property
+ buffer.charset = charset;
+ return buffer;
+}
+
+var ponyfill_es2018Exports = {};
+var ponyfill_es2018 = {
+ get exports(){ return ponyfill_es2018Exports; },
+ set exports(v){ ponyfill_es2018Exports = v; },
+};
+
+/**
+ * web-streams-polyfill v3.2.1
+ */
+
+var hasRequiredPonyfill_es2018;
+
+function requirePonyfill_es2018 () {
+ if (hasRequiredPonyfill_es2018) return ponyfill_es2018Exports;
+ hasRequiredPonyfill_es2018 = 1;
+ (function (module, exports) {
+ (function (global, factory) {
+ factory(exports) ;
+ }(commonjsGlobal, (function (exports) {
+ ///
+ const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
+ Symbol :
+ description => `Symbol(${description})`;
+
+ ///
+ function noop() {
+ return undefined;
+ }
+ function getGlobals() {
+ if (typeof self !== 'undefined') {
+ return self;
+ }
+ else if (typeof window !== 'undefined') {
+ return window;
+ }
+ else if (typeof commonjsGlobal !== 'undefined') {
+ return commonjsGlobal;
+ }
+ return undefined;
+ }
+ const globals = getGlobals();
+
+ function typeIsObject(x) {
+ return (typeof x === 'object' && x !== null) || typeof x === 'function';
+ }
+ const rethrowAssertionErrorRejection = noop;
+
+ const originalPromise = Promise;
+ const originalPromiseThen = Promise.prototype.then;
+ const originalPromiseResolve = Promise.resolve.bind(originalPromise);
+ const originalPromiseReject = Promise.reject.bind(originalPromise);
+ function newPromise(executor) {
+ return new originalPromise(executor);
+ }
+ function promiseResolvedWith(value) {
+ return originalPromiseResolve(value);
+ }
+ function promiseRejectedWith(reason) {
+ return originalPromiseReject(reason);
+ }
+ function PerformPromiseThen(promise, onFulfilled, onRejected) {
+ // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
+ // approximation.
+ return originalPromiseThen.call(promise, onFulfilled, onRejected);
+ }
+ function uponPromise(promise, onFulfilled, onRejected) {
+ PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
+ }
+ function uponFulfillment(promise, onFulfilled) {
+ uponPromise(promise, onFulfilled);
+ }
+ function uponRejection(promise, onRejected) {
+ uponPromise(promise, undefined, onRejected);
+ }
+ function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
+ return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
+ }
+ function setPromiseIsHandledToTrue(promise) {
+ PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
+ }
+ const queueMicrotask = (() => {
+ const globalQueueMicrotask = globals && globals.queueMicrotask;
+ if (typeof globalQueueMicrotask === 'function') {
+ return globalQueueMicrotask;
+ }
+ const resolvedPromise = promiseResolvedWith(undefined);
+ return (fn) => PerformPromiseThen(resolvedPromise, fn);
+ })();
+ function reflectCall(F, V, args) {
+ if (typeof F !== 'function') {
+ throw new TypeError('Argument is not a function');
+ }
+ return Function.prototype.apply.call(F, V, args);
+ }
+ function promiseCall(F, V, args) {
+ try {
+ return promiseResolvedWith(reflectCall(F, V, args));
+ }
+ catch (value) {
+ return promiseRejectedWith(value);
+ }
+ }
+
+ // Original from Chromium
+ // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
+ const QUEUE_MAX_ARRAY_SIZE = 16384;
+ /**
+ * Simple queue structure.
+ *
+ * Avoids scalability issues with using a packed array directly by using
+ * multiple arrays in a linked list and keeping the array size bounded.
+ */
+ class SimpleQueue {
+ constructor() {
+ this._cursor = 0;
+ this._size = 0;
+ // _front and _back are always defined.
+ this._front = {
+ _elements: [],
+ _next: undefined
+ };
+ this._back = this._front;
+ // The cursor is used to avoid calling Array.shift().
+ // It contains the index of the front element of the array inside the
+ // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
+ this._cursor = 0;
+ // When there is only one node, size === elements.length - cursor.
+ this._size = 0;
+ }
+ get length() {
+ return this._size;
+ }
+ // For exception safety, this method is structured in order:
+ // 1. Read state
+ // 2. Calculate required state mutations
+ // 3. Perform state mutations
+ push(element) {
+ const oldBack = this._back;
+ let newBack = oldBack;
+ if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
+ newBack = {
+ _elements: [],
+ _next: undefined
+ };
+ }
+ // push() is the mutation most likely to throw an exception, so it
+ // goes first.
+ oldBack._elements.push(element);
+ if (newBack !== oldBack) {
+ this._back = newBack;
+ oldBack._next = newBack;
+ }
+ ++this._size;
+ }
+ // Like push(), shift() follows the read -> calculate -> mutate pattern for
+ // exception safety.
+ shift() { // must not be called on an empty queue
+ const oldFront = this._front;
+ let newFront = oldFront;
+ const oldCursor = this._cursor;
+ let newCursor = oldCursor + 1;
+ const elements = oldFront._elements;
+ const element = elements[oldCursor];
+ if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
+ newFront = oldFront._next;
+ newCursor = 0;
+ }
+ // No mutations before this point.
+ --this._size;
+ this._cursor = newCursor;
+ if (oldFront !== newFront) {
+ this._front = newFront;
+ }
+ // Permit shifted element to be garbage collected.
+ elements[oldCursor] = undefined;
+ return element;
+ }
+ // The tricky thing about forEach() is that it can be called
+ // re-entrantly. The queue may be mutated inside the callback. It is easy to
+ // see that push() within the callback has no negative effects since the end
+ // of the queue is checked for on every iteration. If shift() is called
+ // repeatedly within the callback then the next iteration may return an
+ // element that has been removed. In this case the callback will be called
+ // with undefined values until we either "catch up" with elements that still
+ // exist or reach the back of the queue.
+ forEach(callback) {
+ let i = this._cursor;
+ let node = this._front;
+ let elements = node._elements;
+ while (i !== elements.length || node._next !== undefined) {
+ if (i === elements.length) {
+ node = node._next;
+ elements = node._elements;
+ i = 0;
+ if (elements.length === 0) {
+ break;
+ }
+ }
+ callback(elements[i]);
+ ++i;
+ }
+ }
+ // Return the element that would be returned if shift() was called now,
+ // without modifying the queue.
+ peek() { // must not be called on an empty queue
+ const front = this._front;
+ const cursor = this._cursor;
+ return front._elements[cursor];
+ }
+ }
+
+ function ReadableStreamReaderGenericInitialize(reader, stream) {
+ reader._ownerReadableStream = stream;
+ stream._reader = reader;
+ if (stream._state === 'readable') {
+ defaultReaderClosedPromiseInitialize(reader);
+ }
+ else if (stream._state === 'closed') {
+ defaultReaderClosedPromiseInitializeAsResolved(reader);
+ }
+ else {
+ defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
+ }
+ }
+ // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
+ // check.
+ function ReadableStreamReaderGenericCancel(reader, reason) {
+ const stream = reader._ownerReadableStream;
+ return ReadableStreamCancel(stream, reason);
+ }
+ function ReadableStreamReaderGenericRelease(reader) {
+ if (reader._ownerReadableStream._state === 'readable') {
+ defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
+ }
+ else {
+ defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
+ }
+ reader._ownerReadableStream._reader = undefined;
+ reader._ownerReadableStream = undefined;
+ }
+ // Helper functions for the readers.
+ function readerLockException(name) {
+ return new TypeError('Cannot ' + name + ' a stream using a released reader');
+ }
+ // Helper functions for the ReadableStreamDefaultReader.
+ function defaultReaderClosedPromiseInitialize(reader) {
+ reader._closedPromise = newPromise((resolve, reject) => {
+ reader._closedPromise_resolve = resolve;
+ reader._closedPromise_reject = reject;
+ });
+ }
+ function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
+ defaultReaderClosedPromiseInitialize(reader);
+ defaultReaderClosedPromiseReject(reader, reason);
+ }
+ function defaultReaderClosedPromiseInitializeAsResolved(reader) {
+ defaultReaderClosedPromiseInitialize(reader);
+ defaultReaderClosedPromiseResolve(reader);
+ }
+ function defaultReaderClosedPromiseReject(reader, reason) {
+ if (reader._closedPromise_reject === undefined) {
+ return;
+ }
+ setPromiseIsHandledToTrue(reader._closedPromise);
+ reader._closedPromise_reject(reason);
+ reader._closedPromise_resolve = undefined;
+ reader._closedPromise_reject = undefined;
+ }
+ function defaultReaderClosedPromiseResetToRejected(reader, reason) {
+ defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
+ }
+ function defaultReaderClosedPromiseResolve(reader) {
+ if (reader._closedPromise_resolve === undefined) {
+ return;
+ }
+ reader._closedPromise_resolve(undefined);
+ reader._closedPromise_resolve = undefined;
+ reader._closedPromise_reject = undefined;
+ }
+
+ const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
+ const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
+ const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
+ const PullSteps = SymbolPolyfill('[[PullSteps]]');
+
+ ///
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
+ const NumberIsFinite = Number.isFinite || function (x) {
+ return typeof x === 'number' && isFinite(x);
+ };
+
+ ///
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
+ const MathTrunc = Math.trunc || function (v) {
+ return v < 0 ? Math.ceil(v) : Math.floor(v);
+ };
+
+ // https://heycam.github.io/webidl/#idl-dictionaries
+ function isDictionary(x) {
+ return typeof x === 'object' || typeof x === 'function';
+ }
+ function assertDictionary(obj, context) {
+ if (obj !== undefined && !isDictionary(obj)) {
+ throw new TypeError(`${context} is not an object.`);
+ }
+ }
+ // https://heycam.github.io/webidl/#idl-callback-functions
+ function assertFunction(x, context) {
+ if (typeof x !== 'function') {
+ throw new TypeError(`${context} is not a function.`);
+ }
+ }
+ // https://heycam.github.io/webidl/#idl-object
+ function isObject(x) {
+ return (typeof x === 'object' && x !== null) || typeof x === 'function';
+ }
+ function assertObject(x, context) {
+ if (!isObject(x)) {
+ throw new TypeError(`${context} is not an object.`);
+ }
+ }
+ function assertRequiredArgument(x, position, context) {
+ if (x === undefined) {
+ throw new TypeError(`Parameter ${position} is required in '${context}'.`);
+ }
+ }
+ function assertRequiredField(x, field, context) {
+ if (x === undefined) {
+ throw new TypeError(`${field} is required in '${context}'.`);
+ }
+ }
+ // https://heycam.github.io/webidl/#idl-unrestricted-double
+ function convertUnrestrictedDouble(value) {
+ return Number(value);
+ }
+ function censorNegativeZero(x) {
+ return x === 0 ? 0 : x;
+ }
+ function integerPart(x) {
+ return censorNegativeZero(MathTrunc(x));
+ }
+ // https://heycam.github.io/webidl/#idl-unsigned-long-long
+ function convertUnsignedLongLongWithEnforceRange(value, context) {
+ const lowerBound = 0;
+ const upperBound = Number.MAX_SAFE_INTEGER;
+ let x = Number(value);
+ x = censorNegativeZero(x);
+ if (!NumberIsFinite(x)) {
+ throw new TypeError(`${context} is not a finite number`);
+ }
+ x = integerPart(x);
+ if (x < lowerBound || x > upperBound) {
+ throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
+ }
+ if (!NumberIsFinite(x) || x === 0) {
+ return 0;
+ }
+ // TODO Use BigInt if supported?
+ // let xBigInt = BigInt(integerPart(x));
+ // xBigInt = BigInt.asUintN(64, xBigInt);
+ // return Number(xBigInt);
+ return x;
+ }
+
+ function assertReadableStream(x, context) {
+ if (!IsReadableStream(x)) {
+ throw new TypeError(`${context} is not a ReadableStream.`);
+ }
+ }
+
+ // Abstract operations for the ReadableStream.
+ function AcquireReadableStreamDefaultReader(stream) {
+ return new ReadableStreamDefaultReader(stream);
+ }
+ // ReadableStream API exposed for controllers.
+ function ReadableStreamAddReadRequest(stream, readRequest) {
+ stream._reader._readRequests.push(readRequest);
+ }
+ function ReadableStreamFulfillReadRequest(stream, chunk, done) {
+ const reader = stream._reader;
+ const readRequest = reader._readRequests.shift();
+ if (done) {
+ readRequest._closeSteps();
+ }
+ else {
+ readRequest._chunkSteps(chunk);
+ }
+ }
+ function ReadableStreamGetNumReadRequests(stream) {
+ return stream._reader._readRequests.length;
+ }
+ function ReadableStreamHasDefaultReader(stream) {
+ const reader = stream._reader;
+ if (reader === undefined) {
+ return false;
+ }
+ if (!IsReadableStreamDefaultReader(reader)) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * A default reader vended by a {@link ReadableStream}.
+ *
+ * @public
+ */
+ class ReadableStreamDefaultReader {
+ constructor(stream) {
+ assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
+ assertReadableStream(stream, 'First parameter');
+ if (IsReadableStreamLocked(stream)) {
+ throw new TypeError('This stream has already been locked for exclusive reading by another reader');
+ }
+ ReadableStreamReaderGenericInitialize(this, stream);
+ this._readRequests = new SimpleQueue();
+ }
+ /**
+ * Returns a promise that will be fulfilled when the stream becomes closed,
+ * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
+ */
+ get closed() {
+ if (!IsReadableStreamDefaultReader(this)) {
+ return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
+ }
+ return this._closedPromise;
+ }
+ /**
+ * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
+ */
+ cancel(reason = undefined) {
+ if (!IsReadableStreamDefaultReader(this)) {
+ return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
+ }
+ if (this._ownerReadableStream === undefined) {
+ return promiseRejectedWith(readerLockException('cancel'));
+ }
+ return ReadableStreamReaderGenericCancel(this, reason);
+ }
+ /**
+ * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
+ *
+ * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
+ */
+ read() {
+ if (!IsReadableStreamDefaultReader(this)) {
+ return promiseRejectedWith(defaultReaderBrandCheckException('read'));
+ }
+ if (this._ownerReadableStream === undefined) {
+ return promiseRejectedWith(readerLockException('read from'));
+ }
+ let resolvePromise;
+ let rejectPromise;
+ const promise = newPromise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ const readRequest = {
+ _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
+ _closeSteps: () => resolvePromise({ value: undefined, done: true }),
+ _errorSteps: e => rejectPromise(e)
+ };
+ ReadableStreamDefaultReaderRead(this, readRequest);
+ return promise;
+ }
+ /**
+ * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
+ * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
+ * from now on; otherwise, the reader will appear closed.
+ *
+ * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
+ * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
+ * do so will throw a `TypeError` and leave the reader locked to the stream.
+ */
+ releaseLock() {
+ if (!IsReadableStreamDefaultReader(this)) {
+ throw defaultReaderBrandCheckException('releaseLock');
+ }
+ if (this._ownerReadableStream === undefined) {
+ return;
+ }
+ if (this._readRequests.length > 0) {
+ throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
+ }
+ ReadableStreamReaderGenericRelease(this);
+ }
+ }
+ Object.defineProperties(ReadableStreamDefaultReader.prototype, {
+ cancel: { enumerable: true },
+ read: { enumerable: true },
+ releaseLock: { enumerable: true },
+ closed: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ReadableStreamDefaultReader',
+ configurable: true
+ });
+ }
+ // Abstract operations for the readers.
+ function IsReadableStreamDefaultReader(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
+ return false;
+ }
+ return x instanceof ReadableStreamDefaultReader;
+ }
+ function ReadableStreamDefaultReaderRead(reader, readRequest) {
+ const stream = reader._ownerReadableStream;
+ stream._disturbed = true;
+ if (stream._state === 'closed') {
+ readRequest._closeSteps();
+ }
+ else if (stream._state === 'errored') {
+ readRequest._errorSteps(stream._storedError);
+ }
+ else {
+ stream._readableStreamController[PullSteps](readRequest);
+ }
+ }
+ // Helper functions for the ReadableStreamDefaultReader.
+ function defaultReaderBrandCheckException(name) {
+ return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
+ }
+
+ ///
+ /* eslint-disable @typescript-eslint/no-empty-function */
+ const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype);
+
+ ///
+ class ReadableStreamAsyncIteratorImpl {
+ constructor(reader, preventCancel) {
+ this._ongoingPromise = undefined;
+ this._isFinished = false;
+ this._reader = reader;
+ this._preventCancel = preventCancel;
+ }
+ next() {
+ const nextSteps = () => this._nextSteps();
+ this._ongoingPromise = this._ongoingPromise ?
+ transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
+ nextSteps();
+ return this._ongoingPromise;
+ }
+ return(value) {
+ const returnSteps = () => this._returnSteps(value);
+ return this._ongoingPromise ?
+ transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
+ returnSteps();
+ }
+ _nextSteps() {
+ if (this._isFinished) {
+ return Promise.resolve({ value: undefined, done: true });
+ }
+ const reader = this._reader;
+ if (reader._ownerReadableStream === undefined) {
+ return promiseRejectedWith(readerLockException('iterate'));
+ }
+ let resolvePromise;
+ let rejectPromise;
+ const promise = newPromise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ const readRequest = {
+ _chunkSteps: chunk => {
+ this._ongoingPromise = undefined;
+ // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
+ // FIXME Is this a bug in the specification, or in the test?
+ queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
+ },
+ _closeSteps: () => {
+ this._ongoingPromise = undefined;
+ this._isFinished = true;
+ ReadableStreamReaderGenericRelease(reader);
+ resolvePromise({ value: undefined, done: true });
+ },
+ _errorSteps: reason => {
+ this._ongoingPromise = undefined;
+ this._isFinished = true;
+ ReadableStreamReaderGenericRelease(reader);
+ rejectPromise(reason);
+ }
+ };
+ ReadableStreamDefaultReaderRead(reader, readRequest);
+ return promise;
+ }
+ _returnSteps(value) {
+ if (this._isFinished) {
+ return Promise.resolve({ value, done: true });
+ }
+ this._isFinished = true;
+ const reader = this._reader;
+ if (reader._ownerReadableStream === undefined) {
+ return promiseRejectedWith(readerLockException('finish iterating'));
+ }
+ if (!this._preventCancel) {
+ const result = ReadableStreamReaderGenericCancel(reader, value);
+ ReadableStreamReaderGenericRelease(reader);
+ return transformPromiseWith(result, () => ({ value, done: true }));
+ }
+ ReadableStreamReaderGenericRelease(reader);
+ return promiseResolvedWith({ value, done: true });
+ }
+ }
+ const ReadableStreamAsyncIteratorPrototype = {
+ next() {
+ if (!IsReadableStreamAsyncIterator(this)) {
+ return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
+ }
+ return this._asyncIteratorImpl.next();
+ },
+ return(value) {
+ if (!IsReadableStreamAsyncIterator(this)) {
+ return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
+ }
+ return this._asyncIteratorImpl.return(value);
+ }
+ };
+ if (AsyncIteratorPrototype !== undefined) {
+ Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
+ }
+ // Abstract operations for the ReadableStream.
+ function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
+ const reader = AcquireReadableStreamDefaultReader(stream);
+ const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
+ const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
+ iterator._asyncIteratorImpl = impl;
+ return iterator;
+ }
+ function IsReadableStreamAsyncIterator(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
+ return false;
+ }
+ try {
+ // noinspection SuspiciousTypeOfGuard
+ return x._asyncIteratorImpl instanceof
+ ReadableStreamAsyncIteratorImpl;
+ }
+ catch (_a) {
+ return false;
+ }
+ }
+ // Helper functions for the ReadableStream.
+ function streamAsyncIteratorBrandCheckException(name) {
+ return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
+ }
+
+ ///
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
+ const NumberIsNaN = Number.isNaN || function (x) {
+ // eslint-disable-next-line no-self-compare
+ return x !== x;
+ };
+
+ function CreateArrayFromList(elements) {
+ // We use arrays to represent lists, so this is basically a no-op.
+ // Do a slice though just in case we happen to depend on the unique-ness.
+ return elements.slice();
+ }
+ function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
+ new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
+ }
+ // Not implemented correctly
+ function TransferArrayBuffer(O) {
+ return O;
+ }
+ // Not implemented correctly
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ function IsDetachedBuffer(O) {
+ return false;
+ }
+ function ArrayBufferSlice(buffer, begin, end) {
+ // ArrayBuffer.prototype.slice is not available on IE10
+ // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
+ if (buffer.slice) {
+ return buffer.slice(begin, end);
+ }
+ const length = end - begin;
+ const slice = new ArrayBuffer(length);
+ CopyDataBlockBytes(slice, 0, buffer, begin, length);
+ return slice;
+ }
+
+ function IsNonNegativeNumber(v) {
+ if (typeof v !== 'number') {
+ return false;
+ }
+ if (NumberIsNaN(v)) {
+ return false;
+ }
+ if (v < 0) {
+ return false;
+ }
+ return true;
+ }
+ function CloneAsUint8Array(O) {
+ const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
+ return new Uint8Array(buffer);
+ }
+
+ function DequeueValue(container) {
+ const pair = container._queue.shift();
+ container._queueTotalSize -= pair.size;
+ if (container._queueTotalSize < 0) {
+ container._queueTotalSize = 0;
+ }
+ return pair.value;
+ }
+ function EnqueueValueWithSize(container, value, size) {
+ if (!IsNonNegativeNumber(size) || size === Infinity) {
+ throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
+ }
+ container._queue.push({ value, size });
+ container._queueTotalSize += size;
+ }
+ function PeekQueueValue(container) {
+ const pair = container._queue.peek();
+ return pair.value;
+ }
+ function ResetQueue(container) {
+ container._queue = new SimpleQueue();
+ container._queueTotalSize = 0;
+ }
+
+ /**
+ * A pull-into request in a {@link ReadableByteStreamController}.
+ *
+ * @public
+ */
+ class ReadableStreamBYOBRequest {
+ constructor() {
+ throw new TypeError('Illegal constructor');
+ }
+ /**
+ * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
+ */
+ get view() {
+ if (!IsReadableStreamBYOBRequest(this)) {
+ throw byobRequestBrandCheckException('view');
+ }
+ return this._view;
+ }
+ respond(bytesWritten) {
+ if (!IsReadableStreamBYOBRequest(this)) {
+ throw byobRequestBrandCheckException('respond');
+ }
+ assertRequiredArgument(bytesWritten, 1, 'respond');
+ bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
+ if (this._associatedReadableByteStreamController === undefined) {
+ throw new TypeError('This BYOB request has been invalidated');
+ }
+ if (IsDetachedBuffer(this._view.buffer)) ;
+ ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
+ }
+ respondWithNewView(view) {
+ if (!IsReadableStreamBYOBRequest(this)) {
+ throw byobRequestBrandCheckException('respondWithNewView');
+ }
+ assertRequiredArgument(view, 1, 'respondWithNewView');
+ if (!ArrayBuffer.isView(view)) {
+ throw new TypeError('You can only respond with array buffer views');
+ }
+ if (this._associatedReadableByteStreamController === undefined) {
+ throw new TypeError('This BYOB request has been invalidated');
+ }
+ if (IsDetachedBuffer(view.buffer)) ;
+ ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
+ }
+ }
+ Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
+ respond: { enumerable: true },
+ respondWithNewView: { enumerable: true },
+ view: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ReadableStreamBYOBRequest',
+ configurable: true
+ });
+ }
+ /**
+ * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
+ *
+ * @public
+ */
+ class ReadableByteStreamController {
+ constructor() {
+ throw new TypeError('Illegal constructor');
+ }
+ /**
+ * Returns the current BYOB pull request, or `null` if there isn't one.
+ */
+ get byobRequest() {
+ if (!IsReadableByteStreamController(this)) {
+ throw byteStreamControllerBrandCheckException('byobRequest');
+ }
+ return ReadableByteStreamControllerGetBYOBRequest(this);
+ }
+ /**
+ * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
+ * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
+ */
+ get desiredSize() {
+ if (!IsReadableByteStreamController(this)) {
+ throw byteStreamControllerBrandCheckException('desiredSize');
+ }
+ return ReadableByteStreamControllerGetDesiredSize(this);
+ }
+ /**
+ * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
+ * the stream, but once those are read, the stream will become closed.
+ */
+ close() {
+ if (!IsReadableByteStreamController(this)) {
+ throw byteStreamControllerBrandCheckException('close');
+ }
+ if (this._closeRequested) {
+ throw new TypeError('The stream has already been closed; do not close it again!');
+ }
+ const state = this._controlledReadableByteStream._state;
+ if (state !== 'readable') {
+ throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
+ }
+ ReadableByteStreamControllerClose(this);
+ }
+ enqueue(chunk) {
+ if (!IsReadableByteStreamController(this)) {
+ throw byteStreamControllerBrandCheckException('enqueue');
+ }
+ assertRequiredArgument(chunk, 1, 'enqueue');
+ if (!ArrayBuffer.isView(chunk)) {
+ throw new TypeError('chunk must be an array buffer view');
+ }
+ if (chunk.byteLength === 0) {
+ throw new TypeError('chunk must have non-zero byteLength');
+ }
+ if (chunk.buffer.byteLength === 0) {
+ throw new TypeError(`chunk's buffer must have non-zero byteLength`);
+ }
+ if (this._closeRequested) {
+ throw new TypeError('stream is closed or draining');
+ }
+ const state = this._controlledReadableByteStream._state;
+ if (state !== 'readable') {
+ throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
+ }
+ ReadableByteStreamControllerEnqueue(this, chunk);
+ }
+ /**
+ * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
+ */
+ error(e = undefined) {
+ if (!IsReadableByteStreamController(this)) {
+ throw byteStreamControllerBrandCheckException('error');
+ }
+ ReadableByteStreamControllerError(this, e);
+ }
+ /** @internal */
+ [CancelSteps](reason) {
+ ReadableByteStreamControllerClearPendingPullIntos(this);
+ ResetQueue(this);
+ const result = this._cancelAlgorithm(reason);
+ ReadableByteStreamControllerClearAlgorithms(this);
+ return result;
+ }
+ /** @internal */
+ [PullSteps](readRequest) {
+ const stream = this._controlledReadableByteStream;
+ if (this._queueTotalSize > 0) {
+ const entry = this._queue.shift();
+ this._queueTotalSize -= entry.byteLength;
+ ReadableByteStreamControllerHandleQueueDrain(this);
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
+ readRequest._chunkSteps(view);
+ return;
+ }
+ const autoAllocateChunkSize = this._autoAllocateChunkSize;
+ if (autoAllocateChunkSize !== undefined) {
+ let buffer;
+ try {
+ buffer = new ArrayBuffer(autoAllocateChunkSize);
+ }
+ catch (bufferE) {
+ readRequest._errorSteps(bufferE);
+ return;
+ }
+ const pullIntoDescriptor = {
+ buffer,
+ bufferByteLength: autoAllocateChunkSize,
+ byteOffset: 0,
+ byteLength: autoAllocateChunkSize,
+ bytesFilled: 0,
+ elementSize: 1,
+ viewConstructor: Uint8Array,
+ readerType: 'default'
+ };
+ this._pendingPullIntos.push(pullIntoDescriptor);
+ }
+ ReadableStreamAddReadRequest(stream, readRequest);
+ ReadableByteStreamControllerCallPullIfNeeded(this);
+ }
+ }
+ Object.defineProperties(ReadableByteStreamController.prototype, {
+ close: { enumerable: true },
+ enqueue: { enumerable: true },
+ error: { enumerable: true },
+ byobRequest: { enumerable: true },
+ desiredSize: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ReadableByteStreamController',
+ configurable: true
+ });
+ }
+ // Abstract operations for the ReadableByteStreamController.
+ function IsReadableByteStreamController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
+ return false;
+ }
+ return x instanceof ReadableByteStreamController;
+ }
+ function IsReadableStreamBYOBRequest(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
+ return false;
+ }
+ return x instanceof ReadableStreamBYOBRequest;
+ }
+ function ReadableByteStreamControllerCallPullIfNeeded(controller) {
+ const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
+ if (!shouldPull) {
+ return;
+ }
+ if (controller._pulling) {
+ controller._pullAgain = true;
+ return;
+ }
+ controller._pulling = true;
+ // TODO: Test controller argument
+ const pullPromise = controller._pullAlgorithm();
+ uponPromise(pullPromise, () => {
+ controller._pulling = false;
+ if (controller._pullAgain) {
+ controller._pullAgain = false;
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ }, e => {
+ ReadableByteStreamControllerError(controller, e);
+ });
+ }
+ function ReadableByteStreamControllerClearPendingPullIntos(controller) {
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
+ controller._pendingPullIntos = new SimpleQueue();
+ }
+ function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
+ let done = false;
+ if (stream._state === 'closed') {
+ done = true;
+ }
+ const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
+ if (pullIntoDescriptor.readerType === 'default') {
+ ReadableStreamFulfillReadRequest(stream, filledView, done);
+ }
+ else {
+ ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
+ }
+ }
+ function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
+ const bytesFilled = pullIntoDescriptor.bytesFilled;
+ const elementSize = pullIntoDescriptor.elementSize;
+ return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
+ }
+ function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
+ controller._queue.push({ buffer, byteOffset, byteLength });
+ controller._queueTotalSize += byteLength;
+ }
+ function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
+ const elementSize = pullIntoDescriptor.elementSize;
+ const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
+ const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
+ const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
+ const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
+ let totalBytesToCopyRemaining = maxBytesToCopy;
+ let ready = false;
+ if (maxAlignedBytes > currentAlignedBytes) {
+ totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
+ ready = true;
+ }
+ const queue = controller._queue;
+ while (totalBytesToCopyRemaining > 0) {
+ const headOfQueue = queue.peek();
+ const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
+ const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
+ CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
+ if (headOfQueue.byteLength === bytesToCopy) {
+ queue.shift();
+ }
+ else {
+ headOfQueue.byteOffset += bytesToCopy;
+ headOfQueue.byteLength -= bytesToCopy;
+ }
+ controller._queueTotalSize -= bytesToCopy;
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
+ totalBytesToCopyRemaining -= bytesToCopy;
+ }
+ return ready;
+ }
+ function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
+ pullIntoDescriptor.bytesFilled += size;
+ }
+ function ReadableByteStreamControllerHandleQueueDrain(controller) {
+ if (controller._queueTotalSize === 0 && controller._closeRequested) {
+ ReadableByteStreamControllerClearAlgorithms(controller);
+ ReadableStreamClose(controller._controlledReadableByteStream);
+ }
+ else {
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ }
+ function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
+ if (controller._byobRequest === null) {
+ return;
+ }
+ controller._byobRequest._associatedReadableByteStreamController = undefined;
+ controller._byobRequest._view = null;
+ controller._byobRequest = null;
+ }
+ function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
+ while (controller._pendingPullIntos.length > 0) {
+ if (controller._queueTotalSize === 0) {
+ return;
+ }
+ const pullIntoDescriptor = controller._pendingPullIntos.peek();
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
+ }
+ }
+ }
+ function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
+ const stream = controller._controlledReadableByteStream;
+ let elementSize = 1;
+ if (view.constructor !== DataView) {
+ elementSize = view.constructor.BYTES_PER_ELEMENT;
+ }
+ const ctor = view.constructor;
+ // try {
+ const buffer = TransferArrayBuffer(view.buffer);
+ // } catch (e) {
+ // readIntoRequest._errorSteps(e);
+ // return;
+ // }
+ const pullIntoDescriptor = {
+ buffer,
+ bufferByteLength: buffer.byteLength,
+ byteOffset: view.byteOffset,
+ byteLength: view.byteLength,
+ bytesFilled: 0,
+ elementSize,
+ viewConstructor: ctor,
+ readerType: 'byob'
+ };
+ if (controller._pendingPullIntos.length > 0) {
+ controller._pendingPullIntos.push(pullIntoDescriptor);
+ // No ReadableByteStreamControllerCallPullIfNeeded() call since:
+ // - No change happens on desiredSize
+ // - The source has already been notified of that there's at least 1 pending read(view)
+ ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
+ return;
+ }
+ if (stream._state === 'closed') {
+ const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
+ readIntoRequest._closeSteps(emptyView);
+ return;
+ }
+ if (controller._queueTotalSize > 0) {
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
+ const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
+ ReadableByteStreamControllerHandleQueueDrain(controller);
+ readIntoRequest._chunkSteps(filledView);
+ return;
+ }
+ if (controller._closeRequested) {
+ const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
+ ReadableByteStreamControllerError(controller, e);
+ readIntoRequest._errorSteps(e);
+ return;
+ }
+ }
+ controller._pendingPullIntos.push(pullIntoDescriptor);
+ ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
+ const stream = controller._controlledReadableByteStream;
+ if (ReadableStreamHasBYOBReader(stream)) {
+ while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
+ const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
+ ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
+ }
+ }
+ }
+ function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
+ return;
+ }
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
+ const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
+ if (remainderSize > 0) {
+ const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
+ const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
+ }
+ pullIntoDescriptor.bytesFilled -= remainderSize;
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
+ }
+ function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
+ const firstDescriptor = controller._pendingPullIntos.peek();
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
+ const state = controller._controlledReadableByteStream._state;
+ if (state === 'closed') {
+ ReadableByteStreamControllerRespondInClosedState(controller);
+ }
+ else {
+ ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
+ }
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ function ReadableByteStreamControllerShiftPendingPullInto(controller) {
+ const descriptor = controller._pendingPullIntos.shift();
+ return descriptor;
+ }
+ function ReadableByteStreamControllerShouldCallPull(controller) {
+ const stream = controller._controlledReadableByteStream;
+ if (stream._state !== 'readable') {
+ return false;
+ }
+ if (controller._closeRequested) {
+ return false;
+ }
+ if (!controller._started) {
+ return false;
+ }
+ if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
+ return true;
+ }
+ if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
+ return true;
+ }
+ const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
+ if (desiredSize > 0) {
+ return true;
+ }
+ return false;
+ }
+ function ReadableByteStreamControllerClearAlgorithms(controller) {
+ controller._pullAlgorithm = undefined;
+ controller._cancelAlgorithm = undefined;
+ }
+ // A client of ReadableByteStreamController may use these functions directly to bypass state check.
+ function ReadableByteStreamControllerClose(controller) {
+ const stream = controller._controlledReadableByteStream;
+ if (controller._closeRequested || stream._state !== 'readable') {
+ return;
+ }
+ if (controller._queueTotalSize > 0) {
+ controller._closeRequested = true;
+ return;
+ }
+ if (controller._pendingPullIntos.length > 0) {
+ const firstPendingPullInto = controller._pendingPullIntos.peek();
+ if (firstPendingPullInto.bytesFilled > 0) {
+ const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
+ ReadableByteStreamControllerError(controller, e);
+ throw e;
+ }
+ }
+ ReadableByteStreamControllerClearAlgorithms(controller);
+ ReadableStreamClose(stream);
+ }
+ function ReadableByteStreamControllerEnqueue(controller, chunk) {
+ const stream = controller._controlledReadableByteStream;
+ if (controller._closeRequested || stream._state !== 'readable') {
+ return;
+ }
+ const buffer = chunk.buffer;
+ const byteOffset = chunk.byteOffset;
+ const byteLength = chunk.byteLength;
+ const transferredBuffer = TransferArrayBuffer(buffer);
+ if (controller._pendingPullIntos.length > 0) {
+ const firstPendingPullInto = controller._pendingPullIntos.peek();
+ if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
+ firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
+ }
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
+ if (ReadableStreamHasDefaultReader(stream)) {
+ if (ReadableStreamGetNumReadRequests(stream) === 0) {
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
+ }
+ else {
+ if (controller._pendingPullIntos.length > 0) {
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
+ }
+ const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
+ ReadableStreamFulfillReadRequest(stream, transferredView, false);
+ }
+ }
+ else if (ReadableStreamHasBYOBReader(stream)) {
+ // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
+ }
+ else {
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
+ }
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }
+ function ReadableByteStreamControllerError(controller, e) {
+ const stream = controller._controlledReadableByteStream;
+ if (stream._state !== 'readable') {
+ return;
+ }
+ ReadableByteStreamControllerClearPendingPullIntos(controller);
+ ResetQueue(controller);
+ ReadableByteStreamControllerClearAlgorithms(controller);
+ ReadableStreamError(stream, e);
+ }
+ function ReadableByteStreamControllerGetBYOBRequest(controller) {
+ if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
+ const firstDescriptor = controller._pendingPullIntos.peek();
+ const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
+ const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
+ SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
+ controller._byobRequest = byobRequest;
+ }
+ return controller._byobRequest;
+ }
+ function ReadableByteStreamControllerGetDesiredSize(controller) {
+ const state = controller._controlledReadableByteStream._state;
+ if (state === 'errored') {
+ return null;
+ }
+ if (state === 'closed') {
+ return 0;
+ }
+ return controller._strategyHWM - controller._queueTotalSize;
+ }
+ function ReadableByteStreamControllerRespond(controller, bytesWritten) {
+ const firstDescriptor = controller._pendingPullIntos.peek();
+ const state = controller._controlledReadableByteStream._state;
+ if (state === 'closed') {
+ if (bytesWritten !== 0) {
+ throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
+ }
+ }
+ else {
+ if (bytesWritten === 0) {
+ throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');
+ }
+ if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
+ throw new RangeError('bytesWritten out of range');
+ }
+ }
+ firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
+ ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
+ }
+ function ReadableByteStreamControllerRespondWithNewView(controller, view) {
+ const firstDescriptor = controller._pendingPullIntos.peek();
+ const state = controller._controlledReadableByteStream._state;
+ if (state === 'closed') {
+ if (view.byteLength !== 0) {
+ throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream');
+ }
+ }
+ else {
+ if (view.byteLength === 0) {
+ throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream');
+ }
+ }
+ if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
+ throw new RangeError('The region specified by view does not match byobRequest');
+ }
+ if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
+ throw new RangeError('The buffer of view has different capacity than byobRequest');
+ }
+ if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
+ throw new RangeError('The region specified by view is larger than byobRequest');
+ }
+ const viewByteLength = view.byteLength;
+ firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
+ ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
+ }
+ function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
+ controller._controlledReadableByteStream = stream;
+ controller._pullAgain = false;
+ controller._pulling = false;
+ controller._byobRequest = null;
+ // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
+ controller._queue = controller._queueTotalSize = undefined;
+ ResetQueue(controller);
+ controller._closeRequested = false;
+ controller._started = false;
+ controller._strategyHWM = highWaterMark;
+ controller._pullAlgorithm = pullAlgorithm;
+ controller._cancelAlgorithm = cancelAlgorithm;
+ controller._autoAllocateChunkSize = autoAllocateChunkSize;
+ controller._pendingPullIntos = new SimpleQueue();
+ stream._readableStreamController = controller;
+ const startResult = startAlgorithm();
+ uponPromise(promiseResolvedWith(startResult), () => {
+ controller._started = true;
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
+ }, r => {
+ ReadableByteStreamControllerError(controller, r);
+ });
+ }
+ function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
+ const controller = Object.create(ReadableByteStreamController.prototype);
+ let startAlgorithm = () => undefined;
+ let pullAlgorithm = () => promiseResolvedWith(undefined);
+ let cancelAlgorithm = () => promiseResolvedWith(undefined);
+ if (underlyingByteSource.start !== undefined) {
+ startAlgorithm = () => underlyingByteSource.start(controller);
+ }
+ if (underlyingByteSource.pull !== undefined) {
+ pullAlgorithm = () => underlyingByteSource.pull(controller);
+ }
+ if (underlyingByteSource.cancel !== undefined) {
+ cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
+ }
+ const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
+ if (autoAllocateChunkSize === 0) {
+ throw new TypeError('autoAllocateChunkSize must be greater than 0');
+ }
+ SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
+ }
+ function SetUpReadableStreamBYOBRequest(request, controller, view) {
+ request._associatedReadableByteStreamController = controller;
+ request._view = view;
+ }
+ // Helper functions for the ReadableStreamBYOBRequest.
+ function byobRequestBrandCheckException(name) {
+ return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
+ }
+ // Helper functions for the ReadableByteStreamController.
+ function byteStreamControllerBrandCheckException(name) {
+ return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
+ }
+
+ // Abstract operations for the ReadableStream.
+ function AcquireReadableStreamBYOBReader(stream) {
+ return new ReadableStreamBYOBReader(stream);
+ }
+ // ReadableStream API exposed for controllers.
+ function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
+ stream._reader._readIntoRequests.push(readIntoRequest);
+ }
+ function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
+ const reader = stream._reader;
+ const readIntoRequest = reader._readIntoRequests.shift();
+ if (done) {
+ readIntoRequest._closeSteps(chunk);
+ }
+ else {
+ readIntoRequest._chunkSteps(chunk);
+ }
+ }
+ function ReadableStreamGetNumReadIntoRequests(stream) {
+ return stream._reader._readIntoRequests.length;
+ }
+ function ReadableStreamHasBYOBReader(stream) {
+ const reader = stream._reader;
+ if (reader === undefined) {
+ return false;
+ }
+ if (!IsReadableStreamBYOBReader(reader)) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * A BYOB reader vended by a {@link ReadableStream}.
+ *
+ * @public
+ */
+ class ReadableStreamBYOBReader {
+ constructor(stream) {
+ assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
+ assertReadableStream(stream, 'First parameter');
+ if (IsReadableStreamLocked(stream)) {
+ throw new TypeError('This stream has already been locked for exclusive reading by another reader');
+ }
+ if (!IsReadableByteStreamController(stream._readableStreamController)) {
+ throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
+ 'source');
+ }
+ ReadableStreamReaderGenericInitialize(this, stream);
+ this._readIntoRequests = new SimpleQueue();
+ }
+ /**
+ * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
+ * the reader's lock is released before the stream finishes closing.
+ */
+ get closed() {
+ if (!IsReadableStreamBYOBReader(this)) {
+ return promiseRejectedWith(byobReaderBrandCheckException('closed'));
+ }
+ return this._closedPromise;
+ }
+ /**
+ * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
+ */
+ cancel(reason = undefined) {
+ if (!IsReadableStreamBYOBReader(this)) {
+ return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
+ }
+ if (this._ownerReadableStream === undefined) {
+ return promiseRejectedWith(readerLockException('cancel'));
+ }
+ return ReadableStreamReaderGenericCancel(this, reason);
+ }
+ /**
+ * Attempts to reads bytes into view, and returns a promise resolved with the result.
+ *
+ * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
+ */
+ read(view) {
+ if (!IsReadableStreamBYOBReader(this)) {
+ return promiseRejectedWith(byobReaderBrandCheckException('read'));
+ }
+ if (!ArrayBuffer.isView(view)) {
+ return promiseRejectedWith(new TypeError('view must be an array buffer view'));
+ }
+ if (view.byteLength === 0) {
+ return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
+ }
+ if (view.buffer.byteLength === 0) {
+ return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
+ }
+ if (IsDetachedBuffer(view.buffer)) ;
+ if (this._ownerReadableStream === undefined) {
+ return promiseRejectedWith(readerLockException('read from'));
+ }
+ let resolvePromise;
+ let rejectPromise;
+ const promise = newPromise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ const readIntoRequest = {
+ _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
+ _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
+ _errorSteps: e => rejectPromise(e)
+ };
+ ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
+ return promise;
+ }
+ /**
+ * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
+ * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
+ * from now on; otherwise, the reader will appear closed.
+ *
+ * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
+ * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
+ * do so will throw a `TypeError` and leave the reader locked to the stream.
+ */
+ releaseLock() {
+ if (!IsReadableStreamBYOBReader(this)) {
+ throw byobReaderBrandCheckException('releaseLock');
+ }
+ if (this._ownerReadableStream === undefined) {
+ return;
+ }
+ if (this._readIntoRequests.length > 0) {
+ throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
+ }
+ ReadableStreamReaderGenericRelease(this);
+ }
+ }
+ Object.defineProperties(ReadableStreamBYOBReader.prototype, {
+ cancel: { enumerable: true },
+ read: { enumerable: true },
+ releaseLock: { enumerable: true },
+ closed: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ReadableStreamBYOBReader',
+ configurable: true
+ });
+ }
+ // Abstract operations for the readers.
+ function IsReadableStreamBYOBReader(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
+ return false;
+ }
+ return x instanceof ReadableStreamBYOBReader;
+ }
+ function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
+ const stream = reader._ownerReadableStream;
+ stream._disturbed = true;
+ if (stream._state === 'errored') {
+ readIntoRequest._errorSteps(stream._storedError);
+ }
+ else {
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
+ }
+ }
+ // Helper functions for the ReadableStreamBYOBReader.
+ function byobReaderBrandCheckException(name) {
+ return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
+ }
+
+ function ExtractHighWaterMark(strategy, defaultHWM) {
+ const { highWaterMark } = strategy;
+ if (highWaterMark === undefined) {
+ return defaultHWM;
+ }
+ if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
+ throw new RangeError('Invalid highWaterMark');
+ }
+ return highWaterMark;
+ }
+ function ExtractSizeAlgorithm(strategy) {
+ const { size } = strategy;
+ if (!size) {
+ return () => 1;
+ }
+ return size;
+ }
+
+ function convertQueuingStrategy(init, context) {
+ assertDictionary(init, context);
+ const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
+ const size = init === null || init === void 0 ? void 0 : init.size;
+ return {
+ highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
+ size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
+ };
+ }
+ function convertQueuingStrategySize(fn, context) {
+ assertFunction(fn, context);
+ return chunk => convertUnrestrictedDouble(fn(chunk));
+ }
+
+ function convertUnderlyingSink(original, context) {
+ assertDictionary(original, context);
+ const abort = original === null || original === void 0 ? void 0 : original.abort;
+ const close = original === null || original === void 0 ? void 0 : original.close;
+ const start = original === null || original === void 0 ? void 0 : original.start;
+ const type = original === null || original === void 0 ? void 0 : original.type;
+ const write = original === null || original === void 0 ? void 0 : original.write;
+ return {
+ abort: abort === undefined ?
+ undefined :
+ convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
+ close: close === undefined ?
+ undefined :
+ convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
+ start: start === undefined ?
+ undefined :
+ convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
+ write: write === undefined ?
+ undefined :
+ convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
+ type
+ };
+ }
+ function convertUnderlyingSinkAbortCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (reason) => promiseCall(fn, original, [reason]);
+ }
+ function convertUnderlyingSinkCloseCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return () => promiseCall(fn, original, []);
+ }
+ function convertUnderlyingSinkStartCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (controller) => reflectCall(fn, original, [controller]);
+ }
+ function convertUnderlyingSinkWriteCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
+ }
+
+ function assertWritableStream(x, context) {
+ if (!IsWritableStream(x)) {
+ throw new TypeError(`${context} is not a WritableStream.`);
+ }
+ }
+
+ function isAbortSignal(value) {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+ try {
+ return typeof value.aborted === 'boolean';
+ }
+ catch (_a) {
+ // AbortSignal.prototype.aborted throws if its brand check fails
+ return false;
+ }
+ }
+ const supportsAbortController = typeof AbortController === 'function';
+ /**
+ * Construct a new AbortController, if supported by the platform.
+ *
+ * @internal
+ */
+ function createAbortController() {
+ if (supportsAbortController) {
+ return new AbortController();
+ }
+ return undefined;
+ }
+
+ /**
+ * A writable stream represents a destination for data, into which you can write.
+ *
+ * @public
+ */
+ class WritableStream {
+ constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
+ if (rawUnderlyingSink === undefined) {
+ rawUnderlyingSink = null;
+ }
+ else {
+ assertObject(rawUnderlyingSink, 'First parameter');
+ }
+ const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
+ const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
+ InitializeWritableStream(this);
+ const type = underlyingSink.type;
+ if (type !== undefined) {
+ throw new RangeError('Invalid type is specified');
+ }
+ const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
+ const highWaterMark = ExtractHighWaterMark(strategy, 1);
+ SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
+ }
+ /**
+ * Returns whether or not the writable stream is locked to a writer.
+ */
+ get locked() {
+ if (!IsWritableStream(this)) {
+ throw streamBrandCheckException$2('locked');
+ }
+ return IsWritableStreamLocked(this);
+ }
+ /**
+ * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
+ * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
+ * mechanism of the underlying sink.
+ *
+ * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
+ * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
+ * the stream) if the stream is currently locked.
+ */
+ abort(reason = undefined) {
+ if (!IsWritableStream(this)) {
+ return promiseRejectedWith(streamBrandCheckException$2('abort'));
+ }
+ if (IsWritableStreamLocked(this)) {
+ return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
+ }
+ return WritableStreamAbort(this, reason);
+ }
+ /**
+ * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
+ * close behavior. During this time any further attempts to write will fail (without erroring the stream).
+ *
+ * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
+ * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
+ * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
+ */
+ close() {
+ if (!IsWritableStream(this)) {
+ return promiseRejectedWith(streamBrandCheckException$2('close'));
+ }
+ if (IsWritableStreamLocked(this)) {
+ return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
+ }
+ if (WritableStreamCloseQueuedOrInFlight(this)) {
+ return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
+ }
+ return WritableStreamClose(this);
+ }
+ /**
+ * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
+ * is locked, no other writer can be acquired until this one is released.
+ *
+ * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
+ * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
+ * the same time, which would cause the resulting written data to be unpredictable and probably useless.
+ */
+ getWriter() {
+ if (!IsWritableStream(this)) {
+ throw streamBrandCheckException$2('getWriter');
+ }
+ return AcquireWritableStreamDefaultWriter(this);
+ }
+ }
+ Object.defineProperties(WritableStream.prototype, {
+ abort: { enumerable: true },
+ close: { enumerable: true },
+ getWriter: { enumerable: true },
+ locked: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
+ value: 'WritableStream',
+ configurable: true
+ });
+ }
+ // Abstract operations for the WritableStream.
+ function AcquireWritableStreamDefaultWriter(stream) {
+ return new WritableStreamDefaultWriter(stream);
+ }
+ // Throws if and only if startAlgorithm throws.
+ function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
+ const stream = Object.create(WritableStream.prototype);
+ InitializeWritableStream(stream);
+ const controller = Object.create(WritableStreamDefaultController.prototype);
+ SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
+ return stream;
+ }
+ function InitializeWritableStream(stream) {
+ stream._state = 'writable';
+ // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
+ // 'erroring' or 'errored'. May be set to an undefined value.
+ stream._storedError = undefined;
+ stream._writer = undefined;
+ // Initialize to undefined first because the constructor of the controller checks this
+ // variable to validate the caller.
+ stream._writableStreamController = undefined;
+ // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
+ // producer without waiting for the queued writes to finish.
+ stream._writeRequests = new SimpleQueue();
+ // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
+ // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
+ stream._inFlightWriteRequest = undefined;
+ // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
+ // has been detached.
+ stream._closeRequest = undefined;
+ // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
+ // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
+ stream._inFlightCloseRequest = undefined;
+ // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
+ stream._pendingAbortRequest = undefined;
+ // The backpressure signal set by the controller.
+ stream._backpressure = false;
+ }
+ function IsWritableStream(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
+ return false;
+ }
+ return x instanceof WritableStream;
+ }
+ function IsWritableStreamLocked(stream) {
+ if (stream._writer === undefined) {
+ return false;
+ }
+ return true;
+ }
+ function WritableStreamAbort(stream, reason) {
+ var _a;
+ if (stream._state === 'closed' || stream._state === 'errored') {
+ return promiseResolvedWith(undefined);
+ }
+ stream._writableStreamController._abortReason = reason;
+ (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
+ // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
+ // but it doesn't know that signaling abort runs author code that might have changed the state.
+ // Widen the type again by casting to WritableStreamState.
+ const state = stream._state;
+ if (state === 'closed' || state === 'errored') {
+ return promiseResolvedWith(undefined);
+ }
+ if (stream._pendingAbortRequest !== undefined) {
+ return stream._pendingAbortRequest._promise;
+ }
+ let wasAlreadyErroring = false;
+ if (state === 'erroring') {
+ wasAlreadyErroring = true;
+ // reason will not be used, so don't keep a reference to it.
+ reason = undefined;
+ }
+ const promise = newPromise((resolve, reject) => {
+ stream._pendingAbortRequest = {
+ _promise: undefined,
+ _resolve: resolve,
+ _reject: reject,
+ _reason: reason,
+ _wasAlreadyErroring: wasAlreadyErroring
+ };
+ });
+ stream._pendingAbortRequest._promise = promise;
+ if (!wasAlreadyErroring) {
+ WritableStreamStartErroring(stream, reason);
+ }
+ return promise;
+ }
+ function WritableStreamClose(stream) {
+ const state = stream._state;
+ if (state === 'closed' || state === 'errored') {
+ return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
+ }
+ const promise = newPromise((resolve, reject) => {
+ const closeRequest = {
+ _resolve: resolve,
+ _reject: reject
+ };
+ stream._closeRequest = closeRequest;
+ });
+ const writer = stream._writer;
+ if (writer !== undefined && stream._backpressure && state === 'writable') {
+ defaultWriterReadyPromiseResolve(writer);
+ }
+ WritableStreamDefaultControllerClose(stream._writableStreamController);
+ return promise;
+ }
+ // WritableStream API exposed for controllers.
+ function WritableStreamAddWriteRequest(stream) {
+ const promise = newPromise((resolve, reject) => {
+ const writeRequest = {
+ _resolve: resolve,
+ _reject: reject
+ };
+ stream._writeRequests.push(writeRequest);
+ });
+ return promise;
+ }
+ function WritableStreamDealWithRejection(stream, error) {
+ const state = stream._state;
+ if (state === 'writable') {
+ WritableStreamStartErroring(stream, error);
+ return;
+ }
+ WritableStreamFinishErroring(stream);
+ }
+ function WritableStreamStartErroring(stream, reason) {
+ const controller = stream._writableStreamController;
+ stream._state = 'erroring';
+ stream._storedError = reason;
+ const writer = stream._writer;
+ if (writer !== undefined) {
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
+ }
+ if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
+ WritableStreamFinishErroring(stream);
+ }
+ }
+ function WritableStreamFinishErroring(stream) {
+ stream._state = 'errored';
+ stream._writableStreamController[ErrorSteps]();
+ const storedError = stream._storedError;
+ stream._writeRequests.forEach(writeRequest => {
+ writeRequest._reject(storedError);
+ });
+ stream._writeRequests = new SimpleQueue();
+ if (stream._pendingAbortRequest === undefined) {
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ return;
+ }
+ const abortRequest = stream._pendingAbortRequest;
+ stream._pendingAbortRequest = undefined;
+ if (abortRequest._wasAlreadyErroring) {
+ abortRequest._reject(storedError);
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ return;
+ }
+ const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
+ uponPromise(promise, () => {
+ abortRequest._resolve();
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ }, (reason) => {
+ abortRequest._reject(reason);
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
+ });
+ }
+ function WritableStreamFinishInFlightWrite(stream) {
+ stream._inFlightWriteRequest._resolve(undefined);
+ stream._inFlightWriteRequest = undefined;
+ }
+ function WritableStreamFinishInFlightWriteWithError(stream, error) {
+ stream._inFlightWriteRequest._reject(error);
+ stream._inFlightWriteRequest = undefined;
+ WritableStreamDealWithRejection(stream, error);
+ }
+ function WritableStreamFinishInFlightClose(stream) {
+ stream._inFlightCloseRequest._resolve(undefined);
+ stream._inFlightCloseRequest = undefined;
+ const state = stream._state;
+ if (state === 'erroring') {
+ // The error was too late to do anything, so it is ignored.
+ stream._storedError = undefined;
+ if (stream._pendingAbortRequest !== undefined) {
+ stream._pendingAbortRequest._resolve();
+ stream._pendingAbortRequest = undefined;
+ }
+ }
+ stream._state = 'closed';
+ const writer = stream._writer;
+ if (writer !== undefined) {
+ defaultWriterClosedPromiseResolve(writer);
+ }
+ }
+ function WritableStreamFinishInFlightCloseWithError(stream, error) {
+ stream._inFlightCloseRequest._reject(error);
+ stream._inFlightCloseRequest = undefined;
+ // Never execute sink abort() after sink close().
+ if (stream._pendingAbortRequest !== undefined) {
+ stream._pendingAbortRequest._reject(error);
+ stream._pendingAbortRequest = undefined;
+ }
+ WritableStreamDealWithRejection(stream, error);
+ }
+ // TODO(ricea): Fix alphabetical order.
+ function WritableStreamCloseQueuedOrInFlight(stream) {
+ if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
+ return false;
+ }
+ return true;
+ }
+ function WritableStreamHasOperationMarkedInFlight(stream) {
+ if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
+ return false;
+ }
+ return true;
+ }
+ function WritableStreamMarkCloseRequestInFlight(stream) {
+ stream._inFlightCloseRequest = stream._closeRequest;
+ stream._closeRequest = undefined;
+ }
+ function WritableStreamMarkFirstWriteRequestInFlight(stream) {
+ stream._inFlightWriteRequest = stream._writeRequests.shift();
+ }
+ function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
+ if (stream._closeRequest !== undefined) {
+ stream._closeRequest._reject(stream._storedError);
+ stream._closeRequest = undefined;
+ }
+ const writer = stream._writer;
+ if (writer !== undefined) {
+ defaultWriterClosedPromiseReject(writer, stream._storedError);
+ }
+ }
+ function WritableStreamUpdateBackpressure(stream, backpressure) {
+ const writer = stream._writer;
+ if (writer !== undefined && backpressure !== stream._backpressure) {
+ if (backpressure) {
+ defaultWriterReadyPromiseReset(writer);
+ }
+ else {
+ defaultWriterReadyPromiseResolve(writer);
+ }
+ }
+ stream._backpressure = backpressure;
+ }
+ /**
+ * A default writer vended by a {@link WritableStream}.
+ *
+ * @public
+ */
+ class WritableStreamDefaultWriter {
+ constructor(stream) {
+ assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
+ assertWritableStream(stream, 'First parameter');
+ if (IsWritableStreamLocked(stream)) {
+ throw new TypeError('This stream has already been locked for exclusive writing by another writer');
+ }
+ this._ownerWritableStream = stream;
+ stream._writer = this;
+ const state = stream._state;
+ if (state === 'writable') {
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
+ defaultWriterReadyPromiseInitialize(this);
+ }
+ else {
+ defaultWriterReadyPromiseInitializeAsResolved(this);
+ }
+ defaultWriterClosedPromiseInitialize(this);
+ }
+ else if (state === 'erroring') {
+ defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
+ defaultWriterClosedPromiseInitialize(this);
+ }
+ else if (state === 'closed') {
+ defaultWriterReadyPromiseInitializeAsResolved(this);
+ defaultWriterClosedPromiseInitializeAsResolved(this);
+ }
+ else {
+ const storedError = stream._storedError;
+ defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
+ defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
+ }
+ }
+ /**
+ * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
+ * the writer’s lock is released before the stream finishes closing.
+ */
+ get closed() {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
+ }
+ return this._closedPromise;
+ }
+ /**
+ * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
+ * A producer can use this information to determine the right amount of data to write.
+ *
+ * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
+ * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
+ * the writer’s lock is released.
+ */
+ get desiredSize() {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ throw defaultWriterBrandCheckException('desiredSize');
+ }
+ if (this._ownerWritableStream === undefined) {
+ throw defaultWriterLockException('desiredSize');
+ }
+ return WritableStreamDefaultWriterGetDesiredSize(this);
+ }
+ /**
+ * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
+ * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
+ * back to zero or below, the getter will return a new promise that stays pending until the next transition.
+ *
+ * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
+ * rejected.
+ */
+ get ready() {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
+ }
+ return this._readyPromise;
+ }
+ /**
+ * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
+ */
+ abort(reason = undefined) {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
+ }
+ if (this._ownerWritableStream === undefined) {
+ return promiseRejectedWith(defaultWriterLockException('abort'));
+ }
+ return WritableStreamDefaultWriterAbort(this, reason);
+ }
+ /**
+ * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
+ */
+ close() {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ return promiseRejectedWith(defaultWriterBrandCheckException('close'));
+ }
+ const stream = this._ownerWritableStream;
+ if (stream === undefined) {
+ return promiseRejectedWith(defaultWriterLockException('close'));
+ }
+ if (WritableStreamCloseQueuedOrInFlight(stream)) {
+ return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
+ }
+ return WritableStreamDefaultWriterClose(this);
+ }
+ /**
+ * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
+ * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
+ * now on; otherwise, the writer will appear closed.
+ *
+ * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
+ * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
+ * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
+ * other producers from writing in an interleaved manner.
+ */
+ releaseLock() {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ throw defaultWriterBrandCheckException('releaseLock');
+ }
+ const stream = this._ownerWritableStream;
+ if (stream === undefined) {
+ return;
+ }
+ WritableStreamDefaultWriterRelease(this);
+ }
+ write(chunk = undefined) {
+ if (!IsWritableStreamDefaultWriter(this)) {
+ return promiseRejectedWith(defaultWriterBrandCheckException('write'));
+ }
+ if (this._ownerWritableStream === undefined) {
+ return promiseRejectedWith(defaultWriterLockException('write to'));
+ }
+ return WritableStreamDefaultWriterWrite(this, chunk);
+ }
+ }
+ Object.defineProperties(WritableStreamDefaultWriter.prototype, {
+ abort: { enumerable: true },
+ close: { enumerable: true },
+ releaseLock: { enumerable: true },
+ write: { enumerable: true },
+ closed: { enumerable: true },
+ desiredSize: { enumerable: true },
+ ready: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
+ value: 'WritableStreamDefaultWriter',
+ configurable: true
+ });
+ }
+ // Abstract operations for the WritableStreamDefaultWriter.
+ function IsWritableStreamDefaultWriter(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
+ return false;
+ }
+ return x instanceof WritableStreamDefaultWriter;
+ }
+ // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
+ function WritableStreamDefaultWriterAbort(writer, reason) {
+ const stream = writer._ownerWritableStream;
+ return WritableStreamAbort(stream, reason);
+ }
+ function WritableStreamDefaultWriterClose(writer) {
+ const stream = writer._ownerWritableStream;
+ return WritableStreamClose(stream);
+ }
+ function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
+ const stream = writer._ownerWritableStream;
+ const state = stream._state;
+ if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
+ return promiseResolvedWith(undefined);
+ }
+ if (state === 'errored') {
+ return promiseRejectedWith(stream._storedError);
+ }
+ return WritableStreamDefaultWriterClose(writer);
+ }
+ function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
+ if (writer._closedPromiseState === 'pending') {
+ defaultWriterClosedPromiseReject(writer, error);
+ }
+ else {
+ defaultWriterClosedPromiseResetToRejected(writer, error);
+ }
+ }
+ function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
+ if (writer._readyPromiseState === 'pending') {
+ defaultWriterReadyPromiseReject(writer, error);
+ }
+ else {
+ defaultWriterReadyPromiseResetToRejected(writer, error);
+ }
+ }
+ function WritableStreamDefaultWriterGetDesiredSize(writer) {
+ const stream = writer._ownerWritableStream;
+ const state = stream._state;
+ if (state === 'errored' || state === 'erroring') {
+ return null;
+ }
+ if (state === 'closed') {
+ return 0;
+ }
+ return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
+ }
+ function WritableStreamDefaultWriterRelease(writer) {
+ const stream = writer._ownerWritableStream;
+ const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
+ // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
+ // rejected until afterwards. This means that simply testing state will not work.
+ WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
+ stream._writer = undefined;
+ writer._ownerWritableStream = undefined;
+ }
+ function WritableStreamDefaultWriterWrite(writer, chunk) {
+ const stream = writer._ownerWritableStream;
+ const controller = stream._writableStreamController;
+ const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
+ if (stream !== writer._ownerWritableStream) {
+ return promiseRejectedWith(defaultWriterLockException('write to'));
+ }
+ const state = stream._state;
+ if (state === 'errored') {
+ return promiseRejectedWith(stream._storedError);
+ }
+ if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
+ return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
+ }
+ if (state === 'erroring') {
+ return promiseRejectedWith(stream._storedError);
+ }
+ const promise = WritableStreamAddWriteRequest(stream);
+ WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
+ return promise;
+ }
+ const closeSentinel = {};
+ /**
+ * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
+ *
+ * @public
+ */
+ class WritableStreamDefaultController {
+ constructor() {
+ throw new TypeError('Illegal constructor');
+ }
+ /**
+ * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
+ *
+ * @deprecated
+ * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
+ * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
+ */
+ get abortReason() {
+ if (!IsWritableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$2('abortReason');
+ }
+ return this._abortReason;
+ }
+ /**
+ * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
+ */
+ get signal() {
+ if (!IsWritableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$2('signal');
+ }
+ if (this._abortController === undefined) {
+ // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.
+ // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,
+ // so instead we only implement support for `signal` if we find a global `AbortController` constructor.
+ throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');
+ }
+ return this._abortController.signal;
+ }
+ /**
+ * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
+ *
+ * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
+ * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
+ * normal lifecycle of interactions with the underlying sink.
+ */
+ error(e = undefined) {
+ if (!IsWritableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$2('error');
+ }
+ const state = this._controlledWritableStream._state;
+ if (state !== 'writable') {
+ // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
+ // just treat it as a no-op.
+ return;
+ }
+ WritableStreamDefaultControllerError(this, e);
+ }
+ /** @internal */
+ [AbortSteps](reason) {
+ const result = this._abortAlgorithm(reason);
+ WritableStreamDefaultControllerClearAlgorithms(this);
+ return result;
+ }
+ /** @internal */
+ [ErrorSteps]() {
+ ResetQueue(this);
+ }
+ }
+ Object.defineProperties(WritableStreamDefaultController.prototype, {
+ abortReason: { enumerable: true },
+ signal: { enumerable: true },
+ error: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
+ value: 'WritableStreamDefaultController',
+ configurable: true
+ });
+ }
+ // Abstract operations implementing interface required by the WritableStream.
+ function IsWritableStreamDefaultController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
+ return false;
+ }
+ return x instanceof WritableStreamDefaultController;
+ }
+ function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
+ controller._controlledWritableStream = stream;
+ stream._writableStreamController = controller;
+ // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
+ controller._queue = undefined;
+ controller._queueTotalSize = undefined;
+ ResetQueue(controller);
+ controller._abortReason = undefined;
+ controller._abortController = createAbortController();
+ controller._started = false;
+ controller._strategySizeAlgorithm = sizeAlgorithm;
+ controller._strategyHWM = highWaterMark;
+ controller._writeAlgorithm = writeAlgorithm;
+ controller._closeAlgorithm = closeAlgorithm;
+ controller._abortAlgorithm = abortAlgorithm;
+ const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
+ WritableStreamUpdateBackpressure(stream, backpressure);
+ const startResult = startAlgorithm();
+ const startPromise = promiseResolvedWith(startResult);
+ uponPromise(startPromise, () => {
+ controller._started = true;
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }, r => {
+ controller._started = true;
+ WritableStreamDealWithRejection(stream, r);
+ });
+ }
+ function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
+ const controller = Object.create(WritableStreamDefaultController.prototype);
+ let startAlgorithm = () => undefined;
+ let writeAlgorithm = () => promiseResolvedWith(undefined);
+ let closeAlgorithm = () => promiseResolvedWith(undefined);
+ let abortAlgorithm = () => promiseResolvedWith(undefined);
+ if (underlyingSink.start !== undefined) {
+ startAlgorithm = () => underlyingSink.start(controller);
+ }
+ if (underlyingSink.write !== undefined) {
+ writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
+ }
+ if (underlyingSink.close !== undefined) {
+ closeAlgorithm = () => underlyingSink.close();
+ }
+ if (underlyingSink.abort !== undefined) {
+ abortAlgorithm = reason => underlyingSink.abort(reason);
+ }
+ SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
+ }
+ // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
+ function WritableStreamDefaultControllerClearAlgorithms(controller) {
+ controller._writeAlgorithm = undefined;
+ controller._closeAlgorithm = undefined;
+ controller._abortAlgorithm = undefined;
+ controller._strategySizeAlgorithm = undefined;
+ }
+ function WritableStreamDefaultControllerClose(controller) {
+ EnqueueValueWithSize(controller, closeSentinel, 0);
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }
+ function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
+ try {
+ return controller._strategySizeAlgorithm(chunk);
+ }
+ catch (chunkSizeE) {
+ WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
+ return 1;
+ }
+ }
+ function WritableStreamDefaultControllerGetDesiredSize(controller) {
+ return controller._strategyHWM - controller._queueTotalSize;
+ }
+ function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
+ try {
+ EnqueueValueWithSize(controller, chunk, chunkSize);
+ }
+ catch (enqueueE) {
+ WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
+ return;
+ }
+ const stream = controller._controlledWritableStream;
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
+ const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
+ WritableStreamUpdateBackpressure(stream, backpressure);
+ }
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }
+ // Abstract operations for the WritableStreamDefaultController.
+ function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
+ const stream = controller._controlledWritableStream;
+ if (!controller._started) {
+ return;
+ }
+ if (stream._inFlightWriteRequest !== undefined) {
+ return;
+ }
+ const state = stream._state;
+ if (state === 'erroring') {
+ WritableStreamFinishErroring(stream);
+ return;
+ }
+ if (controller._queue.length === 0) {
+ return;
+ }
+ const value = PeekQueueValue(controller);
+ if (value === closeSentinel) {
+ WritableStreamDefaultControllerProcessClose(controller);
+ }
+ else {
+ WritableStreamDefaultControllerProcessWrite(controller, value);
+ }
+ }
+ function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
+ if (controller._controlledWritableStream._state === 'writable') {
+ WritableStreamDefaultControllerError(controller, error);
+ }
+ }
+ function WritableStreamDefaultControllerProcessClose(controller) {
+ const stream = controller._controlledWritableStream;
+ WritableStreamMarkCloseRequestInFlight(stream);
+ DequeueValue(controller);
+ const sinkClosePromise = controller._closeAlgorithm();
+ WritableStreamDefaultControllerClearAlgorithms(controller);
+ uponPromise(sinkClosePromise, () => {
+ WritableStreamFinishInFlightClose(stream);
+ }, reason => {
+ WritableStreamFinishInFlightCloseWithError(stream, reason);
+ });
+ }
+ function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
+ const stream = controller._controlledWritableStream;
+ WritableStreamMarkFirstWriteRequestInFlight(stream);
+ const sinkWritePromise = controller._writeAlgorithm(chunk);
+ uponPromise(sinkWritePromise, () => {
+ WritableStreamFinishInFlightWrite(stream);
+ const state = stream._state;
+ DequeueValue(controller);
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
+ const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
+ WritableStreamUpdateBackpressure(stream, backpressure);
+ }
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
+ }, reason => {
+ if (stream._state === 'writable') {
+ WritableStreamDefaultControllerClearAlgorithms(controller);
+ }
+ WritableStreamFinishInFlightWriteWithError(stream, reason);
+ });
+ }
+ function WritableStreamDefaultControllerGetBackpressure(controller) {
+ const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
+ return desiredSize <= 0;
+ }
+ // A client of WritableStreamDefaultController may use these functions directly to bypass state check.
+ function WritableStreamDefaultControllerError(controller, error) {
+ const stream = controller._controlledWritableStream;
+ WritableStreamDefaultControllerClearAlgorithms(controller);
+ WritableStreamStartErroring(stream, error);
+ }
+ // Helper functions for the WritableStream.
+ function streamBrandCheckException$2(name) {
+ return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
+ }
+ // Helper functions for the WritableStreamDefaultController.
+ function defaultControllerBrandCheckException$2(name) {
+ return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
+ }
+ // Helper functions for the WritableStreamDefaultWriter.
+ function defaultWriterBrandCheckException(name) {
+ return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
+ }
+ function defaultWriterLockException(name) {
+ return new TypeError('Cannot ' + name + ' a stream using a released writer');
+ }
+ function defaultWriterClosedPromiseInitialize(writer) {
+ writer._closedPromise = newPromise((resolve, reject) => {
+ writer._closedPromise_resolve = resolve;
+ writer._closedPromise_reject = reject;
+ writer._closedPromiseState = 'pending';
+ });
+ }
+ function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
+ defaultWriterClosedPromiseInitialize(writer);
+ defaultWriterClosedPromiseReject(writer, reason);
+ }
+ function defaultWriterClosedPromiseInitializeAsResolved(writer) {
+ defaultWriterClosedPromiseInitialize(writer);
+ defaultWriterClosedPromiseResolve(writer);
+ }
+ function defaultWriterClosedPromiseReject(writer, reason) {
+ if (writer._closedPromise_reject === undefined) {
+ return;
+ }
+ setPromiseIsHandledToTrue(writer._closedPromise);
+ writer._closedPromise_reject(reason);
+ writer._closedPromise_resolve = undefined;
+ writer._closedPromise_reject = undefined;
+ writer._closedPromiseState = 'rejected';
+ }
+ function defaultWriterClosedPromiseResetToRejected(writer, reason) {
+ defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
+ }
+ function defaultWriterClosedPromiseResolve(writer) {
+ if (writer._closedPromise_resolve === undefined) {
+ return;
+ }
+ writer._closedPromise_resolve(undefined);
+ writer._closedPromise_resolve = undefined;
+ writer._closedPromise_reject = undefined;
+ writer._closedPromiseState = 'resolved';
+ }
+ function defaultWriterReadyPromiseInitialize(writer) {
+ writer._readyPromise = newPromise((resolve, reject) => {
+ writer._readyPromise_resolve = resolve;
+ writer._readyPromise_reject = reject;
+ });
+ writer._readyPromiseState = 'pending';
+ }
+ function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
+ defaultWriterReadyPromiseInitialize(writer);
+ defaultWriterReadyPromiseReject(writer, reason);
+ }
+ function defaultWriterReadyPromiseInitializeAsResolved(writer) {
+ defaultWriterReadyPromiseInitialize(writer);
+ defaultWriterReadyPromiseResolve(writer);
+ }
+ function defaultWriterReadyPromiseReject(writer, reason) {
+ if (writer._readyPromise_reject === undefined) {
+ return;
+ }
+ setPromiseIsHandledToTrue(writer._readyPromise);
+ writer._readyPromise_reject(reason);
+ writer._readyPromise_resolve = undefined;
+ writer._readyPromise_reject = undefined;
+ writer._readyPromiseState = 'rejected';
+ }
+ function defaultWriterReadyPromiseReset(writer) {
+ defaultWriterReadyPromiseInitialize(writer);
+ }
+ function defaultWriterReadyPromiseResetToRejected(writer, reason) {
+ defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
+ }
+ function defaultWriterReadyPromiseResolve(writer) {
+ if (writer._readyPromise_resolve === undefined) {
+ return;
+ }
+ writer._readyPromise_resolve(undefined);
+ writer._readyPromise_resolve = undefined;
+ writer._readyPromise_reject = undefined;
+ writer._readyPromiseState = 'fulfilled';
+ }
+
+ ///
+ const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
+
+ ///
+ function isDOMExceptionConstructor(ctor) {
+ if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
+ return false;
+ }
+ try {
+ new ctor();
+ return true;
+ }
+ catch (_a) {
+ return false;
+ }
+ }
+ function createDOMExceptionPolyfill() {
+ // eslint-disable-next-line no-shadow
+ const ctor = function DOMException(message, name) {
+ this.message = message || '';
+ this.name = name || 'Error';
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+ };
+ ctor.prototype = Object.create(Error.prototype);
+ Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
+ return ctor;
+ }
+ // eslint-disable-next-line no-redeclare
+ const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
+
+ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
+ const reader = AcquireReadableStreamDefaultReader(source);
+ const writer = AcquireWritableStreamDefaultWriter(dest);
+ source._disturbed = true;
+ let shuttingDown = false;
+ // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
+ let currentWrite = promiseResolvedWith(undefined);
+ return newPromise((resolve, reject) => {
+ let abortAlgorithm;
+ if (signal !== undefined) {
+ abortAlgorithm = () => {
+ const error = new DOMException$1('Aborted', 'AbortError');
+ const actions = [];
+ if (!preventAbort) {
+ actions.push(() => {
+ if (dest._state === 'writable') {
+ return WritableStreamAbort(dest, error);
+ }
+ return promiseResolvedWith(undefined);
+ });
+ }
+ if (!preventCancel) {
+ actions.push(() => {
+ if (source._state === 'readable') {
+ return ReadableStreamCancel(source, error);
+ }
+ return promiseResolvedWith(undefined);
+ });
+ }
+ shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
+ };
+ if (signal.aborted) {
+ abortAlgorithm();
+ return;
+ }
+ signal.addEventListener('abort', abortAlgorithm);
+ }
+ // Using reader and writer, read all chunks from this and write them to dest
+ // - Backpressure must be enforced
+ // - Shutdown must stop all activity
+ function pipeLoop() {
+ return newPromise((resolveLoop, rejectLoop) => {
+ function next(done) {
+ if (done) {
+ resolveLoop();
+ }
+ else {
+ // Use `PerformPromiseThen` instead of `uponPromise` to avoid
+ // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
+ PerformPromiseThen(pipeStep(), next, rejectLoop);
+ }
+ }
+ next(false);
+ });
+ }
+ function pipeStep() {
+ if (shuttingDown) {
+ return promiseResolvedWith(true);
+ }
+ return PerformPromiseThen(writer._readyPromise, () => {
+ return newPromise((resolveRead, rejectRead) => {
+ ReadableStreamDefaultReaderRead(reader, {
+ _chunkSteps: chunk => {
+ currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
+ resolveRead(false);
+ },
+ _closeSteps: () => resolveRead(true),
+ _errorSteps: rejectRead
+ });
+ });
+ });
+ }
+ // Errors must be propagated forward
+ isOrBecomesErrored(source, reader._closedPromise, storedError => {
+ if (!preventAbort) {
+ shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
+ }
+ else {
+ shutdown(true, storedError);
+ }
+ });
+ // Errors must be propagated backward
+ isOrBecomesErrored(dest, writer._closedPromise, storedError => {
+ if (!preventCancel) {
+ shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
+ }
+ else {
+ shutdown(true, storedError);
+ }
+ });
+ // Closing must be propagated forward
+ isOrBecomesClosed(source, reader._closedPromise, () => {
+ if (!preventClose) {
+ shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
+ }
+ else {
+ shutdown();
+ }
+ });
+ // Closing must be propagated backward
+ if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
+ const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
+ if (!preventCancel) {
+ shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
+ }
+ else {
+ shutdown(true, destClosed);
+ }
+ }
+ setPromiseIsHandledToTrue(pipeLoop());
+ function waitForWritesToFinish() {
+ // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
+ // for that too.
+ const oldCurrentWrite = currentWrite;
+ return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
+ }
+ function isOrBecomesErrored(stream, promise, action) {
+ if (stream._state === 'errored') {
+ action(stream._storedError);
+ }
+ else {
+ uponRejection(promise, action);
+ }
+ }
+ function isOrBecomesClosed(stream, promise, action) {
+ if (stream._state === 'closed') {
+ action();
+ }
+ else {
+ uponFulfillment(promise, action);
+ }
+ }
+ function shutdownWithAction(action, originalIsError, originalError) {
+ if (shuttingDown) {
+ return;
+ }
+ shuttingDown = true;
+ if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
+ uponFulfillment(waitForWritesToFinish(), doTheRest);
+ }
+ else {
+ doTheRest();
+ }
+ function doTheRest() {
+ uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
+ }
+ }
+ function shutdown(isError, error) {
+ if (shuttingDown) {
+ return;
+ }
+ shuttingDown = true;
+ if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
+ uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
+ }
+ else {
+ finalize(isError, error);
+ }
+ }
+ function finalize(isError, error) {
+ WritableStreamDefaultWriterRelease(writer);
+ ReadableStreamReaderGenericRelease(reader);
+ if (signal !== undefined) {
+ signal.removeEventListener('abort', abortAlgorithm);
+ }
+ if (isError) {
+ reject(error);
+ }
+ else {
+ resolve(undefined);
+ }
+ }
+ });
+ }
+
+ /**
+ * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
+ *
+ * @public
+ */
+ class ReadableStreamDefaultController {
+ constructor() {
+ throw new TypeError('Illegal constructor');
+ }
+ /**
+ * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
+ * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
+ */
+ get desiredSize() {
+ if (!IsReadableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$1('desiredSize');
+ }
+ return ReadableStreamDefaultControllerGetDesiredSize(this);
+ }
+ /**
+ * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
+ * the stream, but once those are read, the stream will become closed.
+ */
+ close() {
+ if (!IsReadableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$1('close');
+ }
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
+ throw new TypeError('The stream is not in a state that permits close');
+ }
+ ReadableStreamDefaultControllerClose(this);
+ }
+ enqueue(chunk = undefined) {
+ if (!IsReadableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$1('enqueue');
+ }
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
+ throw new TypeError('The stream is not in a state that permits enqueue');
+ }
+ return ReadableStreamDefaultControllerEnqueue(this, chunk);
+ }
+ /**
+ * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
+ */
+ error(e = undefined) {
+ if (!IsReadableStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException$1('error');
+ }
+ ReadableStreamDefaultControllerError(this, e);
+ }
+ /** @internal */
+ [CancelSteps](reason) {
+ ResetQueue(this);
+ const result = this._cancelAlgorithm(reason);
+ ReadableStreamDefaultControllerClearAlgorithms(this);
+ return result;
+ }
+ /** @internal */
+ [PullSteps](readRequest) {
+ const stream = this._controlledReadableStream;
+ if (this._queue.length > 0) {
+ const chunk = DequeueValue(this);
+ if (this._closeRequested && this._queue.length === 0) {
+ ReadableStreamDefaultControllerClearAlgorithms(this);
+ ReadableStreamClose(stream);
+ }
+ else {
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
+ }
+ readRequest._chunkSteps(chunk);
+ }
+ else {
+ ReadableStreamAddReadRequest(stream, readRequest);
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
+ }
+ }
+ }
+ Object.defineProperties(ReadableStreamDefaultController.prototype, {
+ close: { enumerable: true },
+ enqueue: { enumerable: true },
+ error: { enumerable: true },
+ desiredSize: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ReadableStreamDefaultController',
+ configurable: true
+ });
+ }
+ // Abstract operations for the ReadableStreamDefaultController.
+ function IsReadableStreamDefaultController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
+ return false;
+ }
+ return x instanceof ReadableStreamDefaultController;
+ }
+ function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
+ const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
+ if (!shouldPull) {
+ return;
+ }
+ if (controller._pulling) {
+ controller._pullAgain = true;
+ return;
+ }
+ controller._pulling = true;
+ const pullPromise = controller._pullAlgorithm();
+ uponPromise(pullPromise, () => {
+ controller._pulling = false;
+ if (controller._pullAgain) {
+ controller._pullAgain = false;
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
+ }
+ }, e => {
+ ReadableStreamDefaultControllerError(controller, e);
+ });
+ }
+ function ReadableStreamDefaultControllerShouldCallPull(controller) {
+ const stream = controller._controlledReadableStream;
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
+ return false;
+ }
+ if (!controller._started) {
+ return false;
+ }
+ if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
+ return true;
+ }
+ const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
+ if (desiredSize > 0) {
+ return true;
+ }
+ return false;
+ }
+ function ReadableStreamDefaultControllerClearAlgorithms(controller) {
+ controller._pullAlgorithm = undefined;
+ controller._cancelAlgorithm = undefined;
+ controller._strategySizeAlgorithm = undefined;
+ }
+ // A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
+ function ReadableStreamDefaultControllerClose(controller) {
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
+ return;
+ }
+ const stream = controller._controlledReadableStream;
+ controller._closeRequested = true;
+ if (controller._queue.length === 0) {
+ ReadableStreamDefaultControllerClearAlgorithms(controller);
+ ReadableStreamClose(stream);
+ }
+ }
+ function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
+ return;
+ }
+ const stream = controller._controlledReadableStream;
+ if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
+ ReadableStreamFulfillReadRequest(stream, chunk, false);
+ }
+ else {
+ let chunkSize;
+ try {
+ chunkSize = controller._strategySizeAlgorithm(chunk);
+ }
+ catch (chunkSizeE) {
+ ReadableStreamDefaultControllerError(controller, chunkSizeE);
+ throw chunkSizeE;
+ }
+ try {
+ EnqueueValueWithSize(controller, chunk, chunkSize);
+ }
+ catch (enqueueE) {
+ ReadableStreamDefaultControllerError(controller, enqueueE);
+ throw enqueueE;
+ }
+ }
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
+ }
+ function ReadableStreamDefaultControllerError(controller, e) {
+ const stream = controller._controlledReadableStream;
+ if (stream._state !== 'readable') {
+ return;
+ }
+ ResetQueue(controller);
+ ReadableStreamDefaultControllerClearAlgorithms(controller);
+ ReadableStreamError(stream, e);
+ }
+ function ReadableStreamDefaultControllerGetDesiredSize(controller) {
+ const state = controller._controlledReadableStream._state;
+ if (state === 'errored') {
+ return null;
+ }
+ if (state === 'closed') {
+ return 0;
+ }
+ return controller._strategyHWM - controller._queueTotalSize;
+ }
+ // This is used in the implementation of TransformStream.
+ function ReadableStreamDefaultControllerHasBackpressure(controller) {
+ if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
+ return false;
+ }
+ return true;
+ }
+ function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
+ const state = controller._controlledReadableStream._state;
+ if (!controller._closeRequested && state === 'readable') {
+ return true;
+ }
+ return false;
+ }
+ function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
+ controller._controlledReadableStream = stream;
+ controller._queue = undefined;
+ controller._queueTotalSize = undefined;
+ ResetQueue(controller);
+ controller._started = false;
+ controller._closeRequested = false;
+ controller._pullAgain = false;
+ controller._pulling = false;
+ controller._strategySizeAlgorithm = sizeAlgorithm;
+ controller._strategyHWM = highWaterMark;
+ controller._pullAlgorithm = pullAlgorithm;
+ controller._cancelAlgorithm = cancelAlgorithm;
+ stream._readableStreamController = controller;
+ const startResult = startAlgorithm();
+ uponPromise(promiseResolvedWith(startResult), () => {
+ controller._started = true;
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
+ }, r => {
+ ReadableStreamDefaultControllerError(controller, r);
+ });
+ }
+ function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
+ const controller = Object.create(ReadableStreamDefaultController.prototype);
+ let startAlgorithm = () => undefined;
+ let pullAlgorithm = () => promiseResolvedWith(undefined);
+ let cancelAlgorithm = () => promiseResolvedWith(undefined);
+ if (underlyingSource.start !== undefined) {
+ startAlgorithm = () => underlyingSource.start(controller);
+ }
+ if (underlyingSource.pull !== undefined) {
+ pullAlgorithm = () => underlyingSource.pull(controller);
+ }
+ if (underlyingSource.cancel !== undefined) {
+ cancelAlgorithm = reason => underlyingSource.cancel(reason);
+ }
+ SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
+ }
+ // Helper functions for the ReadableStreamDefaultController.
+ function defaultControllerBrandCheckException$1(name) {
+ return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
+ }
+
+ function ReadableStreamTee(stream, cloneForBranch2) {
+ if (IsReadableByteStreamController(stream._readableStreamController)) {
+ return ReadableByteStreamTee(stream);
+ }
+ return ReadableStreamDefaultTee(stream);
+ }
+ function ReadableStreamDefaultTee(stream, cloneForBranch2) {
+ const reader = AcquireReadableStreamDefaultReader(stream);
+ let reading = false;
+ let readAgain = false;
+ let canceled1 = false;
+ let canceled2 = false;
+ let reason1;
+ let reason2;
+ let branch1;
+ let branch2;
+ let resolveCancelPromise;
+ const cancelPromise = newPromise(resolve => {
+ resolveCancelPromise = resolve;
+ });
+ function pullAlgorithm() {
+ if (reading) {
+ readAgain = true;
+ return promiseResolvedWith(undefined);
+ }
+ reading = true;
+ const readRequest = {
+ _chunkSteps: chunk => {
+ // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
+ // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
+ // successful synchronously-available reads get ahead of asynchronously-available errors.
+ queueMicrotask(() => {
+ readAgain = false;
+ const chunk1 = chunk;
+ const chunk2 = chunk;
+ // There is no way to access the cloning code right now in the reference implementation.
+ // If we add one then we'll need an implementation for serializable objects.
+ // if (!canceled2 && cloneForBranch2) {
+ // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));
+ // }
+ if (!canceled1) {
+ ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
+ }
+ if (!canceled2) {
+ ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
+ }
+ reading = false;
+ if (readAgain) {
+ pullAlgorithm();
+ }
+ });
+ },
+ _closeSteps: () => {
+ reading = false;
+ if (!canceled1) {
+ ReadableStreamDefaultControllerClose(branch1._readableStreamController);
+ }
+ if (!canceled2) {
+ ReadableStreamDefaultControllerClose(branch2._readableStreamController);
+ }
+ if (!canceled1 || !canceled2) {
+ resolveCancelPromise(undefined);
+ }
+ },
+ _errorSteps: () => {
+ reading = false;
+ }
+ };
+ ReadableStreamDefaultReaderRead(reader, readRequest);
+ return promiseResolvedWith(undefined);
+ }
+ function cancel1Algorithm(reason) {
+ canceled1 = true;
+ reason1 = reason;
+ if (canceled2) {
+ const compositeReason = CreateArrayFromList([reason1, reason2]);
+ const cancelResult = ReadableStreamCancel(stream, compositeReason);
+ resolveCancelPromise(cancelResult);
+ }
+ return cancelPromise;
+ }
+ function cancel2Algorithm(reason) {
+ canceled2 = true;
+ reason2 = reason;
+ if (canceled1) {
+ const compositeReason = CreateArrayFromList([reason1, reason2]);
+ const cancelResult = ReadableStreamCancel(stream, compositeReason);
+ resolveCancelPromise(cancelResult);
+ }
+ return cancelPromise;
+ }
+ function startAlgorithm() {
+ // do nothing
+ }
+ branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
+ branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
+ uponRejection(reader._closedPromise, (r) => {
+ ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
+ ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
+ if (!canceled1 || !canceled2) {
+ resolveCancelPromise(undefined);
+ }
+ });
+ return [branch1, branch2];
+ }
+ function ReadableByteStreamTee(stream) {
+ let reader = AcquireReadableStreamDefaultReader(stream);
+ let reading = false;
+ let readAgainForBranch1 = false;
+ let readAgainForBranch2 = false;
+ let canceled1 = false;
+ let canceled2 = false;
+ let reason1;
+ let reason2;
+ let branch1;
+ let branch2;
+ let resolveCancelPromise;
+ const cancelPromise = newPromise(resolve => {
+ resolveCancelPromise = resolve;
+ });
+ function forwardReaderError(thisReader) {
+ uponRejection(thisReader._closedPromise, r => {
+ if (thisReader !== reader) {
+ return;
+ }
+ ReadableByteStreamControllerError(branch1._readableStreamController, r);
+ ReadableByteStreamControllerError(branch2._readableStreamController, r);
+ if (!canceled1 || !canceled2) {
+ resolveCancelPromise(undefined);
+ }
+ });
+ }
+ function pullWithDefaultReader() {
+ if (IsReadableStreamBYOBReader(reader)) {
+ ReadableStreamReaderGenericRelease(reader);
+ reader = AcquireReadableStreamDefaultReader(stream);
+ forwardReaderError(reader);
+ }
+ const readRequest = {
+ _chunkSteps: chunk => {
+ // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
+ // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
+ // successful synchronously-available reads get ahead of asynchronously-available errors.
+ queueMicrotask(() => {
+ readAgainForBranch1 = false;
+ readAgainForBranch2 = false;
+ const chunk1 = chunk;
+ let chunk2 = chunk;
+ if (!canceled1 && !canceled2) {
+ try {
+ chunk2 = CloneAsUint8Array(chunk);
+ }
+ catch (cloneE) {
+ ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
+ ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
+ resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
+ return;
+ }
+ }
+ if (!canceled1) {
+ ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
+ }
+ if (!canceled2) {
+ ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
+ }
+ reading = false;
+ if (readAgainForBranch1) {
+ pull1Algorithm();
+ }
+ else if (readAgainForBranch2) {
+ pull2Algorithm();
+ }
+ });
+ },
+ _closeSteps: () => {
+ reading = false;
+ if (!canceled1) {
+ ReadableByteStreamControllerClose(branch1._readableStreamController);
+ }
+ if (!canceled2) {
+ ReadableByteStreamControllerClose(branch2._readableStreamController);
+ }
+ if (branch1._readableStreamController._pendingPullIntos.length > 0) {
+ ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
+ }
+ if (branch2._readableStreamController._pendingPullIntos.length > 0) {
+ ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
+ }
+ if (!canceled1 || !canceled2) {
+ resolveCancelPromise(undefined);
+ }
+ },
+ _errorSteps: () => {
+ reading = false;
+ }
+ };
+ ReadableStreamDefaultReaderRead(reader, readRequest);
+ }
+ function pullWithBYOBReader(view, forBranch2) {
+ if (IsReadableStreamDefaultReader(reader)) {
+ ReadableStreamReaderGenericRelease(reader);
+ reader = AcquireReadableStreamBYOBReader(stream);
+ forwardReaderError(reader);
+ }
+ const byobBranch = forBranch2 ? branch2 : branch1;
+ const otherBranch = forBranch2 ? branch1 : branch2;
+ const readIntoRequest = {
+ _chunkSteps: chunk => {
+ // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
+ // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
+ // successful synchronously-available reads get ahead of asynchronously-available errors.
+ queueMicrotask(() => {
+ readAgainForBranch1 = false;
+ readAgainForBranch2 = false;
+ const byobCanceled = forBranch2 ? canceled2 : canceled1;
+ const otherCanceled = forBranch2 ? canceled1 : canceled2;
+ if (!otherCanceled) {
+ let clonedChunk;
+ try {
+ clonedChunk = CloneAsUint8Array(chunk);
+ }
+ catch (cloneE) {
+ ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
+ ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
+ resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
+ return;
+ }
+ if (!byobCanceled) {
+ ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
+ }
+ ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
+ }
+ else if (!byobCanceled) {
+ ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
+ }
+ reading = false;
+ if (readAgainForBranch1) {
+ pull1Algorithm();
+ }
+ else if (readAgainForBranch2) {
+ pull2Algorithm();
+ }
+ });
+ },
+ _closeSteps: chunk => {
+ reading = false;
+ const byobCanceled = forBranch2 ? canceled2 : canceled1;
+ const otherCanceled = forBranch2 ? canceled1 : canceled2;
+ if (!byobCanceled) {
+ ReadableByteStreamControllerClose(byobBranch._readableStreamController);
+ }
+ if (!otherCanceled) {
+ ReadableByteStreamControllerClose(otherBranch._readableStreamController);
+ }
+ if (chunk !== undefined) {
+ if (!byobCanceled) {
+ ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
+ }
+ if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
+ ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
+ }
+ }
+ if (!byobCanceled || !otherCanceled) {
+ resolveCancelPromise(undefined);
+ }
+ },
+ _errorSteps: () => {
+ reading = false;
+ }
+ };
+ ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
+ }
+ function pull1Algorithm() {
+ if (reading) {
+ readAgainForBranch1 = true;
+ return promiseResolvedWith(undefined);
+ }
+ reading = true;
+ const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
+ if (byobRequest === null) {
+ pullWithDefaultReader();
+ }
+ else {
+ pullWithBYOBReader(byobRequest._view, false);
+ }
+ return promiseResolvedWith(undefined);
+ }
+ function pull2Algorithm() {
+ if (reading) {
+ readAgainForBranch2 = true;
+ return promiseResolvedWith(undefined);
+ }
+ reading = true;
+ const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
+ if (byobRequest === null) {
+ pullWithDefaultReader();
+ }
+ else {
+ pullWithBYOBReader(byobRequest._view, true);
+ }
+ return promiseResolvedWith(undefined);
+ }
+ function cancel1Algorithm(reason) {
+ canceled1 = true;
+ reason1 = reason;
+ if (canceled2) {
+ const compositeReason = CreateArrayFromList([reason1, reason2]);
+ const cancelResult = ReadableStreamCancel(stream, compositeReason);
+ resolveCancelPromise(cancelResult);
+ }
+ return cancelPromise;
+ }
+ function cancel2Algorithm(reason) {
+ canceled2 = true;
+ reason2 = reason;
+ if (canceled1) {
+ const compositeReason = CreateArrayFromList([reason1, reason2]);
+ const cancelResult = ReadableStreamCancel(stream, compositeReason);
+ resolveCancelPromise(cancelResult);
+ }
+ return cancelPromise;
+ }
+ function startAlgorithm() {
+ return;
+ }
+ branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
+ branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
+ forwardReaderError(reader);
+ return [branch1, branch2];
+ }
+
+ function convertUnderlyingDefaultOrByteSource(source, context) {
+ assertDictionary(source, context);
+ const original = source;
+ const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
+ const pull = original === null || original === void 0 ? void 0 : original.pull;
+ const start = original === null || original === void 0 ? void 0 : original.start;
+ const type = original === null || original === void 0 ? void 0 : original.type;
+ return {
+ autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
+ undefined :
+ convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
+ cancel: cancel === undefined ?
+ undefined :
+ convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
+ pull: pull === undefined ?
+ undefined :
+ convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
+ start: start === undefined ?
+ undefined :
+ convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
+ type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
+ };
+ }
+ function convertUnderlyingSourceCancelCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (reason) => promiseCall(fn, original, [reason]);
+ }
+ function convertUnderlyingSourcePullCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (controller) => promiseCall(fn, original, [controller]);
+ }
+ function convertUnderlyingSourceStartCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (controller) => reflectCall(fn, original, [controller]);
+ }
+ function convertReadableStreamType(type, context) {
+ type = `${type}`;
+ if (type !== 'bytes') {
+ throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
+ }
+ return type;
+ }
+
+ function convertReaderOptions(options, context) {
+ assertDictionary(options, context);
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
+ return {
+ mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
+ };
+ }
+ function convertReadableStreamReaderMode(mode, context) {
+ mode = `${mode}`;
+ if (mode !== 'byob') {
+ throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
+ }
+ return mode;
+ }
+
+ function convertIteratorOptions(options, context) {
+ assertDictionary(options, context);
+ const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
+ return { preventCancel: Boolean(preventCancel) };
+ }
+
+ function convertPipeOptions(options, context) {
+ assertDictionary(options, context);
+ const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
+ const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
+ const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
+ if (signal !== undefined) {
+ assertAbortSignal(signal, `${context} has member 'signal' that`);
+ }
+ return {
+ preventAbort: Boolean(preventAbort),
+ preventCancel: Boolean(preventCancel),
+ preventClose: Boolean(preventClose),
+ signal
+ };
+ }
+ function assertAbortSignal(signal, context) {
+ if (!isAbortSignal(signal)) {
+ throw new TypeError(`${context} is not an AbortSignal.`);
+ }
+ }
+
+ function convertReadableWritablePair(pair, context) {
+ assertDictionary(pair, context);
+ const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
+ assertRequiredField(readable, 'readable', 'ReadableWritablePair');
+ assertReadableStream(readable, `${context} has member 'readable' that`);
+ const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
+ assertRequiredField(writable, 'writable', 'ReadableWritablePair');
+ assertWritableStream(writable, `${context} has member 'writable' that`);
+ return { readable, writable };
+ }
+
+ /**
+ * A readable stream represents a source of data, from which you can read.
+ *
+ * @public
+ */
+ class ReadableStream {
+ constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
+ if (rawUnderlyingSource === undefined) {
+ rawUnderlyingSource = null;
+ }
+ else {
+ assertObject(rawUnderlyingSource, 'First parameter');
+ }
+ const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
+ const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
+ InitializeReadableStream(this);
+ if (underlyingSource.type === 'bytes') {
+ if (strategy.size !== undefined) {
+ throw new RangeError('The strategy for a byte stream cannot have a size function');
+ }
+ const highWaterMark = ExtractHighWaterMark(strategy, 0);
+ SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
+ }
+ else {
+ const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
+ const highWaterMark = ExtractHighWaterMark(strategy, 1);
+ SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
+ }
+ }
+ /**
+ * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
+ */
+ get locked() {
+ if (!IsReadableStream(this)) {
+ throw streamBrandCheckException$1('locked');
+ }
+ return IsReadableStreamLocked(this);
+ }
+ /**
+ * Cancels the stream, signaling a loss of interest in the stream by a consumer.
+ *
+ * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
+ * method, which might or might not use it.
+ */
+ cancel(reason = undefined) {
+ if (!IsReadableStream(this)) {
+ return promiseRejectedWith(streamBrandCheckException$1('cancel'));
+ }
+ if (IsReadableStreamLocked(this)) {
+ return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
+ }
+ return ReadableStreamCancel(this, reason);
+ }
+ getReader(rawOptions = undefined) {
+ if (!IsReadableStream(this)) {
+ throw streamBrandCheckException$1('getReader');
+ }
+ const options = convertReaderOptions(rawOptions, 'First parameter');
+ if (options.mode === undefined) {
+ return AcquireReadableStreamDefaultReader(this);
+ }
+ return AcquireReadableStreamBYOBReader(this);
+ }
+ pipeThrough(rawTransform, rawOptions = {}) {
+ if (!IsReadableStream(this)) {
+ throw streamBrandCheckException$1('pipeThrough');
+ }
+ assertRequiredArgument(rawTransform, 1, 'pipeThrough');
+ const transform = convertReadableWritablePair(rawTransform, 'First parameter');
+ const options = convertPipeOptions(rawOptions, 'Second parameter');
+ if (IsReadableStreamLocked(this)) {
+ throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
+ }
+ if (IsWritableStreamLocked(transform.writable)) {
+ throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
+ }
+ const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
+ setPromiseIsHandledToTrue(promise);
+ return transform.readable;
+ }
+ pipeTo(destination, rawOptions = {}) {
+ if (!IsReadableStream(this)) {
+ return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
+ }
+ if (destination === undefined) {
+ return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
+ }
+ if (!IsWritableStream(destination)) {
+ return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
+ }
+ let options;
+ try {
+ options = convertPipeOptions(rawOptions, 'Second parameter');
+ }
+ catch (e) {
+ return promiseRejectedWith(e);
+ }
+ if (IsReadableStreamLocked(this)) {
+ return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
+ }
+ if (IsWritableStreamLocked(destination)) {
+ return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
+ }
+ return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
+ }
+ /**
+ * Tees this readable stream, returning a two-element array containing the two resulting branches as
+ * new {@link ReadableStream} instances.
+ *
+ * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
+ * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
+ * propagated to the stream's underlying source.
+ *
+ * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
+ * this could allow interference between the two branches.
+ */
+ tee() {
+ if (!IsReadableStream(this)) {
+ throw streamBrandCheckException$1('tee');
+ }
+ const branches = ReadableStreamTee(this);
+ return CreateArrayFromList(branches);
+ }
+ values(rawOptions = undefined) {
+ if (!IsReadableStream(this)) {
+ throw streamBrandCheckException$1('values');
+ }
+ const options = convertIteratorOptions(rawOptions, 'First parameter');
+ return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
+ }
+ }
+ Object.defineProperties(ReadableStream.prototype, {
+ cancel: { enumerable: true },
+ getReader: { enumerable: true },
+ pipeThrough: { enumerable: true },
+ pipeTo: { enumerable: true },
+ tee: { enumerable: true },
+ values: { enumerable: true },
+ locked: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ReadableStream',
+ configurable: true
+ });
+ }
+ if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
+ Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
+ value: ReadableStream.prototype.values,
+ writable: true,
+ configurable: true
+ });
+ }
+ // Abstract operations for the ReadableStream.
+ // Throws if and only if startAlgorithm throws.
+ function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
+ const stream = Object.create(ReadableStream.prototype);
+ InitializeReadableStream(stream);
+ const controller = Object.create(ReadableStreamDefaultController.prototype);
+ SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
+ return stream;
+ }
+ // Throws if and only if startAlgorithm throws.
+ function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
+ const stream = Object.create(ReadableStream.prototype);
+ InitializeReadableStream(stream);
+ const controller = Object.create(ReadableByteStreamController.prototype);
+ SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);
+ return stream;
+ }
+ function InitializeReadableStream(stream) {
+ stream._state = 'readable';
+ stream._reader = undefined;
+ stream._storedError = undefined;
+ stream._disturbed = false;
+ }
+ function IsReadableStream(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
+ return false;
+ }
+ return x instanceof ReadableStream;
+ }
+ function IsReadableStreamLocked(stream) {
+ if (stream._reader === undefined) {
+ return false;
+ }
+ return true;
+ }
+ // ReadableStream API exposed for controllers.
+ function ReadableStreamCancel(stream, reason) {
+ stream._disturbed = true;
+ if (stream._state === 'closed') {
+ return promiseResolvedWith(undefined);
+ }
+ if (stream._state === 'errored') {
+ return promiseRejectedWith(stream._storedError);
+ }
+ ReadableStreamClose(stream);
+ const reader = stream._reader;
+ if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
+ reader._readIntoRequests.forEach(readIntoRequest => {
+ readIntoRequest._closeSteps(undefined);
+ });
+ reader._readIntoRequests = new SimpleQueue();
+ }
+ const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
+ return transformPromiseWith(sourceCancelPromise, noop);
+ }
+ function ReadableStreamClose(stream) {
+ stream._state = 'closed';
+ const reader = stream._reader;
+ if (reader === undefined) {
+ return;
+ }
+ defaultReaderClosedPromiseResolve(reader);
+ if (IsReadableStreamDefaultReader(reader)) {
+ reader._readRequests.forEach(readRequest => {
+ readRequest._closeSteps();
+ });
+ reader._readRequests = new SimpleQueue();
+ }
+ }
+ function ReadableStreamError(stream, e) {
+ stream._state = 'errored';
+ stream._storedError = e;
+ const reader = stream._reader;
+ if (reader === undefined) {
+ return;
+ }
+ defaultReaderClosedPromiseReject(reader, e);
+ if (IsReadableStreamDefaultReader(reader)) {
+ reader._readRequests.forEach(readRequest => {
+ readRequest._errorSteps(e);
+ });
+ reader._readRequests = new SimpleQueue();
+ }
+ else {
+ reader._readIntoRequests.forEach(readIntoRequest => {
+ readIntoRequest._errorSteps(e);
+ });
+ reader._readIntoRequests = new SimpleQueue();
+ }
+ }
+ // Helper functions for the ReadableStream.
+ function streamBrandCheckException$1(name) {
+ return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
+ }
+
+ function convertQueuingStrategyInit(init, context) {
+ assertDictionary(init, context);
+ const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
+ assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
+ return {
+ highWaterMark: convertUnrestrictedDouble(highWaterMark)
+ };
+ }
+
+ // The size function must not have a prototype property nor be a constructor
+ const byteLengthSizeFunction = (chunk) => {
+ return chunk.byteLength;
+ };
+ try {
+ Object.defineProperty(byteLengthSizeFunction, 'name', {
+ value: 'size',
+ configurable: true
+ });
+ }
+ catch (_a) {
+ // This property is non-configurable in older browsers, so ignore if this throws.
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
+ }
+ /**
+ * A queuing strategy that counts the number of bytes in each chunk.
+ *
+ * @public
+ */
+ class ByteLengthQueuingStrategy {
+ constructor(options) {
+ assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
+ options = convertQueuingStrategyInit(options, 'First parameter');
+ this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
+ }
+ /**
+ * Returns the high water mark provided to the constructor.
+ */
+ get highWaterMark() {
+ if (!IsByteLengthQueuingStrategy(this)) {
+ throw byteLengthBrandCheckException('highWaterMark');
+ }
+ return this._byteLengthQueuingStrategyHighWaterMark;
+ }
+ /**
+ * Measures the size of `chunk` by returning the value of its `byteLength` property.
+ */
+ get size() {
+ if (!IsByteLengthQueuingStrategy(this)) {
+ throw byteLengthBrandCheckException('size');
+ }
+ return byteLengthSizeFunction;
+ }
+ }
+ Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
+ highWaterMark: { enumerable: true },
+ size: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
+ value: 'ByteLengthQueuingStrategy',
+ configurable: true
+ });
+ }
+ // Helper functions for the ByteLengthQueuingStrategy.
+ function byteLengthBrandCheckException(name) {
+ return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
+ }
+ function IsByteLengthQueuingStrategy(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
+ return false;
+ }
+ return x instanceof ByteLengthQueuingStrategy;
+ }
+
+ // The size function must not have a prototype property nor be a constructor
+ const countSizeFunction = () => {
+ return 1;
+ };
+ try {
+ Object.defineProperty(countSizeFunction, 'name', {
+ value: 'size',
+ configurable: true
+ });
+ }
+ catch (_a) {
+ // This property is non-configurable in older browsers, so ignore if this throws.
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
+ }
+ /**
+ * A queuing strategy that counts the number of chunks.
+ *
+ * @public
+ */
+ class CountQueuingStrategy {
+ constructor(options) {
+ assertRequiredArgument(options, 1, 'CountQueuingStrategy');
+ options = convertQueuingStrategyInit(options, 'First parameter');
+ this._countQueuingStrategyHighWaterMark = options.highWaterMark;
+ }
+ /**
+ * Returns the high water mark provided to the constructor.
+ */
+ get highWaterMark() {
+ if (!IsCountQueuingStrategy(this)) {
+ throw countBrandCheckException('highWaterMark');
+ }
+ return this._countQueuingStrategyHighWaterMark;
+ }
+ /**
+ * Measures the size of `chunk` by always returning 1.
+ * This ensures that the total queue size is a count of the number of chunks in the queue.
+ */
+ get size() {
+ if (!IsCountQueuingStrategy(this)) {
+ throw countBrandCheckException('size');
+ }
+ return countSizeFunction;
+ }
+ }
+ Object.defineProperties(CountQueuingStrategy.prototype, {
+ highWaterMark: { enumerable: true },
+ size: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
+ value: 'CountQueuingStrategy',
+ configurable: true
+ });
+ }
+ // Helper functions for the CountQueuingStrategy.
+ function countBrandCheckException(name) {
+ return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
+ }
+ function IsCountQueuingStrategy(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
+ return false;
+ }
+ return x instanceof CountQueuingStrategy;
+ }
+
+ function convertTransformer(original, context) {
+ assertDictionary(original, context);
+ const flush = original === null || original === void 0 ? void 0 : original.flush;
+ const readableType = original === null || original === void 0 ? void 0 : original.readableType;
+ const start = original === null || original === void 0 ? void 0 : original.start;
+ const transform = original === null || original === void 0 ? void 0 : original.transform;
+ const writableType = original === null || original === void 0 ? void 0 : original.writableType;
+ return {
+ flush: flush === undefined ?
+ undefined :
+ convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
+ readableType,
+ start: start === undefined ?
+ undefined :
+ convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
+ transform: transform === undefined ?
+ undefined :
+ convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
+ writableType
+ };
+ }
+ function convertTransformerFlushCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (controller) => promiseCall(fn, original, [controller]);
+ }
+ function convertTransformerStartCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (controller) => reflectCall(fn, original, [controller]);
+ }
+ function convertTransformerTransformCallback(fn, original, context) {
+ assertFunction(fn, context);
+ return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
+ }
+
+ // Class TransformStream
+ /**
+ * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
+ * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
+ * In a manner specific to the transform stream in question, writes to the writable side result in new data being
+ * made available for reading from the readable side.
+ *
+ * @public
+ */
+ class TransformStream {
+ constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
+ if (rawTransformer === undefined) {
+ rawTransformer = null;
+ }
+ const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
+ const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
+ const transformer = convertTransformer(rawTransformer, 'First parameter');
+ if (transformer.readableType !== undefined) {
+ throw new RangeError('Invalid readableType specified');
+ }
+ if (transformer.writableType !== undefined) {
+ throw new RangeError('Invalid writableType specified');
+ }
+ const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
+ const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
+ const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
+ const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
+ let startPromise_resolve;
+ const startPromise = newPromise(resolve => {
+ startPromise_resolve = resolve;
+ });
+ InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
+ SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
+ if (transformer.start !== undefined) {
+ startPromise_resolve(transformer.start(this._transformStreamController));
+ }
+ else {
+ startPromise_resolve(undefined);
+ }
+ }
+ /**
+ * The readable side of the transform stream.
+ */
+ get readable() {
+ if (!IsTransformStream(this)) {
+ throw streamBrandCheckException('readable');
+ }
+ return this._readable;
+ }
+ /**
+ * The writable side of the transform stream.
+ */
+ get writable() {
+ if (!IsTransformStream(this)) {
+ throw streamBrandCheckException('writable');
+ }
+ return this._writable;
+ }
+ }
+ Object.defineProperties(TransformStream.prototype, {
+ readable: { enumerable: true },
+ writable: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {
+ value: 'TransformStream',
+ configurable: true
+ });
+ }
+ function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
+ function startAlgorithm() {
+ return startPromise;
+ }
+ function writeAlgorithm(chunk) {
+ return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
+ }
+ function abortAlgorithm(reason) {
+ return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
+ }
+ function closeAlgorithm() {
+ return TransformStreamDefaultSinkCloseAlgorithm(stream);
+ }
+ stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
+ function pullAlgorithm() {
+ return TransformStreamDefaultSourcePullAlgorithm(stream);
+ }
+ function cancelAlgorithm(reason) {
+ TransformStreamErrorWritableAndUnblockWrite(stream, reason);
+ return promiseResolvedWith(undefined);
+ }
+ stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
+ // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
+ stream._backpressure = undefined;
+ stream._backpressureChangePromise = undefined;
+ stream._backpressureChangePromise_resolve = undefined;
+ TransformStreamSetBackpressure(stream, true);
+ stream._transformStreamController = undefined;
+ }
+ function IsTransformStream(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
+ return false;
+ }
+ return x instanceof TransformStream;
+ }
+ // This is a no-op if both sides are already errored.
+ function TransformStreamError(stream, e) {
+ ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
+ TransformStreamErrorWritableAndUnblockWrite(stream, e);
+ }
+ function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
+ TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
+ WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
+ if (stream._backpressure) {
+ // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
+ // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
+ // _backpressure is set.
+ TransformStreamSetBackpressure(stream, false);
+ }
+ }
+ function TransformStreamSetBackpressure(stream, backpressure) {
+ // Passes also when called during construction.
+ if (stream._backpressureChangePromise !== undefined) {
+ stream._backpressureChangePromise_resolve();
+ }
+ stream._backpressureChangePromise = newPromise(resolve => {
+ stream._backpressureChangePromise_resolve = resolve;
+ });
+ stream._backpressure = backpressure;
+ }
+ // Class TransformStreamDefaultController
+ /**
+ * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
+ *
+ * @public
+ */
+ class TransformStreamDefaultController {
+ constructor() {
+ throw new TypeError('Illegal constructor');
+ }
+ /**
+ * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
+ */
+ get desiredSize() {
+ if (!IsTransformStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException('desiredSize');
+ }
+ const readableController = this._controlledTransformStream._readable._readableStreamController;
+ return ReadableStreamDefaultControllerGetDesiredSize(readableController);
+ }
+ enqueue(chunk = undefined) {
+ if (!IsTransformStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException('enqueue');
+ }
+ TransformStreamDefaultControllerEnqueue(this, chunk);
+ }
+ /**
+ * Errors both the readable side and the writable side of the controlled transform stream, making all future
+ * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
+ */
+ error(reason = undefined) {
+ if (!IsTransformStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException('error');
+ }
+ TransformStreamDefaultControllerError(this, reason);
+ }
+ /**
+ * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
+ * transformer only needs to consume a portion of the chunks written to the writable side.
+ */
+ terminate() {
+ if (!IsTransformStreamDefaultController(this)) {
+ throw defaultControllerBrandCheckException('terminate');
+ }
+ TransformStreamDefaultControllerTerminate(this);
+ }
+ }
+ Object.defineProperties(TransformStreamDefaultController.prototype, {
+ enqueue: { enumerable: true },
+ error: { enumerable: true },
+ terminate: { enumerable: true },
+ desiredSize: { enumerable: true }
+ });
+ if (typeof SymbolPolyfill.toStringTag === 'symbol') {
+ Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
+ value: 'TransformStreamDefaultController',
+ configurable: true
+ });
+ }
+ // Transform Stream Default Controller Abstract Operations
+ function IsTransformStreamDefaultController(x) {
+ if (!typeIsObject(x)) {
+ return false;
+ }
+ if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
+ return false;
+ }
+ return x instanceof TransformStreamDefaultController;
+ }
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
+ controller._controlledTransformStream = stream;
+ stream._transformStreamController = controller;
+ controller._transformAlgorithm = transformAlgorithm;
+ controller._flushAlgorithm = flushAlgorithm;
+ }
+ function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
+ const controller = Object.create(TransformStreamDefaultController.prototype);
+ let transformAlgorithm = (chunk) => {
+ try {
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
+ return promiseResolvedWith(undefined);
+ }
+ catch (transformResultE) {
+ return promiseRejectedWith(transformResultE);
+ }
+ };
+ let flushAlgorithm = () => promiseResolvedWith(undefined);
+ if (transformer.transform !== undefined) {
+ transformAlgorithm = chunk => transformer.transform(chunk, controller);
+ }
+ if (transformer.flush !== undefined) {
+ flushAlgorithm = () => transformer.flush(controller);
+ }
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
+ }
+ function TransformStreamDefaultControllerClearAlgorithms(controller) {
+ controller._transformAlgorithm = undefined;
+ controller._flushAlgorithm = undefined;
+ }
+ function TransformStreamDefaultControllerEnqueue(controller, chunk) {
+ const stream = controller._controlledTransformStream;
+ const readableController = stream._readable._readableStreamController;
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
+ throw new TypeError('Readable side is not in a state that permits enqueue');
+ }
+ // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
+ // accept TransformStreamDefaultControllerEnqueue() calls.
+ try {
+ ReadableStreamDefaultControllerEnqueue(readableController, chunk);
+ }
+ catch (e) {
+ // This happens when readableStrategy.size() throws.
+ TransformStreamErrorWritableAndUnblockWrite(stream, e);
+ throw stream._readable._storedError;
+ }
+ const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
+ if (backpressure !== stream._backpressure) {
+ TransformStreamSetBackpressure(stream, true);
+ }
+ }
+ function TransformStreamDefaultControllerError(controller, e) {
+ TransformStreamError(controller._controlledTransformStream, e);
+ }
+ function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
+ const transformPromise = controller._transformAlgorithm(chunk);
+ return transformPromiseWith(transformPromise, undefined, r => {
+ TransformStreamError(controller._controlledTransformStream, r);
+ throw r;
+ });
+ }
+ function TransformStreamDefaultControllerTerminate(controller) {
+ const stream = controller._controlledTransformStream;
+ const readableController = stream._readable._readableStreamController;
+ ReadableStreamDefaultControllerClose(readableController);
+ const error = new TypeError('TransformStream terminated');
+ TransformStreamErrorWritableAndUnblockWrite(stream, error);
+ }
+ // TransformStreamDefaultSink Algorithms
+ function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
+ const controller = stream._transformStreamController;
+ if (stream._backpressure) {
+ const backpressureChangePromise = stream._backpressureChangePromise;
+ return transformPromiseWith(backpressureChangePromise, () => {
+ const writable = stream._writable;
+ const state = writable._state;
+ if (state === 'erroring') {
+ throw writable._storedError;
+ }
+ return TransformStreamDefaultControllerPerformTransform(controller, chunk);
+ });
+ }
+ return TransformStreamDefaultControllerPerformTransform(controller, chunk);
+ }
+ function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
+ // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
+ // errored.
+ TransformStreamError(stream, reason);
+ return promiseResolvedWith(undefined);
+ }
+ function TransformStreamDefaultSinkCloseAlgorithm(stream) {
+ // stream._readable cannot change after construction, so caching it across a call to user code is safe.
+ const readable = stream._readable;
+ const controller = stream._transformStreamController;
+ const flushPromise = controller._flushAlgorithm();
+ TransformStreamDefaultControllerClearAlgorithms(controller);
+ // Return a promise that is fulfilled with undefined on success.
+ return transformPromiseWith(flushPromise, () => {
+ if (readable._state === 'errored') {
+ throw readable._storedError;
+ }
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
+ }, r => {
+ TransformStreamError(stream, r);
+ throw readable._storedError;
+ });
+ }
+ // TransformStreamDefaultSource Algorithms
+ function TransformStreamDefaultSourcePullAlgorithm(stream) {
+ // Invariant. Enforced by the promises returned by start() and pull().
+ TransformStreamSetBackpressure(stream, false);
+ // Prevent the next pull() call until there is backpressure.
+ return stream._backpressureChangePromise;
+ }
+ // Helper functions for the TransformStreamDefaultController.
+ function defaultControllerBrandCheckException(name) {
+ return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
+ }
+ // Helper functions for the TransformStream.
+ function streamBrandCheckException(name) {
+ return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
+ }
+
+ exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
+ exports.CountQueuingStrategy = CountQueuingStrategy;
+ exports.ReadableByteStreamController = ReadableByteStreamController;
+ exports.ReadableStream = ReadableStream;
+ exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
+ exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
+ exports.ReadableStreamDefaultController = ReadableStreamDefaultController;
+ exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
+ exports.TransformStream = TransformStream;
+ exports.TransformStreamDefaultController = TransformStreamDefaultController;
+ exports.WritableStream = WritableStream;
+ exports.WritableStreamDefaultController = WritableStreamDefaultController;
+ exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
+
+ Object.defineProperty(exports, '__esModule', { value: true });
+
+ })));
+
+} (ponyfill_es2018, ponyfill_es2018Exports));
+ return ponyfill_es2018Exports;
+}
+
+/* c8 ignore start */
+
+// 64 KiB (same size chrome slice theirs blob into Uint8array's)
+const POOL_SIZE$1 = 65536;
+
+if (!globalThis.ReadableStream) {
+ // `node:stream/web` got introduced in v16.5.0 as experimental
+ // and it's preferred over the polyfilled version. So we also
+ // suppress the warning that gets emitted by NodeJS for using it.
+ try {
+ const process = require('node:process');
+ const { emitWarning } = process;
+ try {
+ process.emitWarning = () => {};
+ Object.assign(globalThis, require('node:stream/web'));
+ process.emitWarning = emitWarning;
+ } catch (error) {
+ process.emitWarning = emitWarning;
+ throw error
+ }
+ } catch (error) {
+ // fallback to polyfill implementation
+ Object.assign(globalThis, requirePonyfill_es2018());
+ }
+}
+
+try {
+ // Don't use node: prefix for this, require+node: is not supported until node v14.14
+ // Only `import()` can use prefix in 12.20 and later
+ const { Blob } = require('buffer');
+ if (Blob && !Blob.prototype.stream) {
+ Blob.prototype.stream = function name (params) {
+ let position = 0;
+ const blob = this;
+
+ return new ReadableStream({
+ type: 'bytes',
+ async pull (ctrl) {
+ const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE$1));
+ const buffer = await chunk.arrayBuffer();
+ position += buffer.byteLength;
+ ctrl.enqueue(new Uint8Array(buffer));
+
+ if (position === blob.size) {
+ ctrl.close();
+ }
+ }
+ })
+ };
+ }
+} catch (error) {}
+
+/*! fetch-blob. MIT License. Jimmy Wärting */
+
+// 64 KiB (same size chrome slice theirs blob into Uint8array's)
+const POOL_SIZE = 65536;
+
+/** @param {(Blob | Uint8Array)[]} parts */
+async function * toIterator (parts, clone = true) {
+ for (const part of parts) {
+ if ('stream' in part) {
+ yield * (/** @type {AsyncIterableIterator} */ (part.stream()));
+ } else if (ArrayBuffer.isView(part)) {
+ if (clone) {
+ let position = part.byteOffset;
+ const end = part.byteOffset + part.byteLength;
+ while (position !== end) {
+ const size = Math.min(end - position, POOL_SIZE);
+ const chunk = part.buffer.slice(position, position + size);
+ position += chunk.byteLength;
+ yield new Uint8Array(chunk);
+ }
+ } else {
+ yield part;
+ }
+ /* c8 ignore next 10 */
+ } else {
+ // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob)
+ let position = 0, b = (/** @type {Blob} */ (part));
+ while (position !== b.size) {
+ const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE));
+ const buffer = await chunk.arrayBuffer();
+ position += buffer.byteLength;
+ yield new Uint8Array(buffer);
+ }
+ }
+ }
+}
+
+const _Blob = class Blob {
+ /** @type {Array.<(Blob|Uint8Array)>} */
+ #parts = []
+ #type = ''
+ #size = 0
+ #endings = 'transparent'
+
+ /**
+ * The Blob() constructor returns a new Blob object. The content
+ * of the blob consists of the concatenation of the values given
+ * in the parameter array.
+ *
+ * @param {*} blobParts
+ * @param {{ type?: string, endings?: string }} [options]
+ */
+ constructor (blobParts = [], options = {}) {
+ if (typeof blobParts !== 'object' || blobParts === null) {
+ throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.')
+ }
+
+ if (typeof blobParts[Symbol.iterator] !== 'function') {
+ throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.')
+ }
+
+ if (typeof options !== 'object' && typeof options !== 'function') {
+ throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.')
+ }
+
+ if (options === null) options = {};
+
+ const encoder = new TextEncoder();
+ for (const element of blobParts) {
+ let part;
+ if (ArrayBuffer.isView(element)) {
+ part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
+ } else if (element instanceof ArrayBuffer) {
+ part = new Uint8Array(element.slice(0));
+ } else if (element instanceof Blob) {
+ part = element;
+ } else {
+ part = encoder.encode(`${element}`);
+ }
+
+ this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
+ this.#parts.push(part);
+ }
+
+ this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}`;
+ const type = options.type === undefined ? '' : String(options.type);
+ this.#type = /^[\x20-\x7E]*$/.test(type) ? type : '';
+ }
+
+ /**
+ * The Blob interface's size property returns the
+ * size of the Blob in bytes.
+ */
+ get size () {
+ return this.#size
+ }
+
+ /**
+ * The type property of a Blob object returns the MIME type of the file.
+ */
+ get type () {
+ return this.#type
+ }
+
+ /**
+ * The text() method in the Blob interface returns a Promise
+ * that resolves with a string containing the contents of
+ * the blob, interpreted as UTF-8.
+ *
+ * @return {Promise}
+ */
+ async text () {
+ // More optimized than using this.arrayBuffer()
+ // that requires twice as much ram
+ const decoder = new TextDecoder();
+ let str = '';
+ for await (const part of toIterator(this.#parts, false)) {
+ str += decoder.decode(part, { stream: true });
+ }
+ // Remaining
+ str += decoder.decode();
+ return str
+ }
+
+ /**
+ * The arrayBuffer() method in the Blob interface returns a
+ * Promise that resolves with the contents of the blob as
+ * binary data contained in an ArrayBuffer.
+ *
+ * @return {Promise}
+ */
+ async arrayBuffer () {
+ // Easier way... Just a unnecessary overhead
+ // const view = new Uint8Array(this.size);
+ // await this.stream().getReader({mode: 'byob'}).read(view);
+ // return view.buffer;
+
+ const data = new Uint8Array(this.size);
+ let offset = 0;
+ for await (const chunk of toIterator(this.#parts, false)) {
+ data.set(chunk, offset);
+ offset += chunk.length;
+ }
+
+ return data.buffer
+ }
+
+ stream () {
+ const it = toIterator(this.#parts, true);
+
+ return new globalThis.ReadableStream({
+ // @ts-ignore
+ type: 'bytes',
+ async pull (ctrl) {
+ const chunk = await it.next();
+ chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
+ },
+
+ async cancel () {
+ await it.return();
+ }
+ })
+ }
+
+ /**
+ * The Blob interface's slice() method creates and returns a
+ * new Blob object which contains data from a subset of the
+ * blob on which it's called.
+ *
+ * @param {number} [start]
+ * @param {number} [end]
+ * @param {string} [type]
+ */
+ slice (start = 0, end = this.size, type = '') {
+ const { size } = this;
+
+ let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
+ let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
+
+ const span = Math.max(relativeEnd - relativeStart, 0);
+ const parts = this.#parts;
+ const blobParts = [];
+ let added = 0;
+
+ for (const part of parts) {
+ // don't add the overflow to new blobParts
+ if (added >= span) {
+ break
+ }
+
+ const size = ArrayBuffer.isView(part) ? part.byteLength : part.size;
+ if (relativeStart && size <= relativeStart) {
+ // Skip the beginning and change the relative
+ // start & end position as we skip the unwanted parts
+ relativeStart -= size;
+ relativeEnd -= size;
+ } else {
+ let chunk;
+ if (ArrayBuffer.isView(part)) {
+ chunk = part.subarray(relativeStart, Math.min(size, relativeEnd));
+ added += chunk.byteLength;
+ } else {
+ chunk = part.slice(relativeStart, Math.min(size, relativeEnd));
+ added += chunk.size;
+ }
+ relativeEnd -= size;
+ blobParts.push(chunk);
+ relativeStart = 0; // All next sequential parts should start at 0
+ }
+ }
+
+ const blob = new Blob([], { type: String(type).toLowerCase() });
+ blob.#size = span;
+ blob.#parts = blobParts;
+
+ return blob
+ }
+
+ get [Symbol.toStringTag] () {
+ return 'Blob'
+ }
+
+ static [Symbol.hasInstance] (object) {
+ return (
+ object &&
+ typeof object === 'object' &&
+ typeof object.constructor === 'function' &&
+ (
+ typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function'
+ ) &&
+ /^(Blob|File)$/.test(object[Symbol.toStringTag])
+ )
+ }
+};
+
+Object.defineProperties(_Blob.prototype, {
+ size: { enumerable: true },
+ type: { enumerable: true },
+ slice: { enumerable: true }
+});
+
+/** @type {typeof globalThis.Blob} */
+const Blob = _Blob;
+var Blob$1 = Blob;
+
+const _File = class File extends Blob$1 {
+ #lastModified = 0
+ #name = ''
+
+ /**
+ * @param {*[]} fileBits
+ * @param {string} fileName
+ * @param {{lastModified?: number, type?: string}} options
+ */// @ts-ignore
+ constructor (fileBits, fileName, options = {}) {
+ if (arguments.length < 2) {
+ throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`)
+ }
+ super(fileBits, options);
+
+ if (options === null) options = {};
+
+ // Simulate WebIDL type casting for NaN value in lastModified option.
+ const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified);
+ if (!Number.isNaN(lastModified)) {
+ this.#lastModified = lastModified;
+ }
+
+ this.#name = String(fileName);
+ }
+
+ get name () {
+ return this.#name
+ }
+
+ get lastModified () {
+ return this.#lastModified
+ }
+
+ get [Symbol.toStringTag] () {
+ return 'File'
+ }
+
+ static [Symbol.hasInstance] (object) {
+ return !!object && object instanceof Blob$1 &&
+ /^(File)$/.test(object[Symbol.toStringTag])
+ }
+};
+
+/** @type {typeof globalThis.File} */// @ts-ignore
+const File = _File;
+
+/*! formdata-polyfill. MIT License. Jimmy Wärting */
+
+var {toStringTag:t,iterator:i,hasInstance:h}=Symbol,
+r=Math.random,
+m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','),
+f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new File([b],c,b):b]:[a,b+'']),
+e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'),
+x=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')}
+append(...a){x('append',arguments,2);this.#d.push(f(...a));}
+delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a);}
+get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b}
+has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)}
+forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this);}
+set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d);});c&&b.push(a);this.#d=b;}
+*entries(){yield*this.#d;}
+*keys(){for(var[a]of this)yield a;}
+*values(){for(var[,a]of this)yield a;}};
+
+/** @param {FormData} F */
+function formDataToBlob (F,B=Blob$1){
+var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="`;
+F.forEach((v,n)=>typeof v=='string'
+?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(? {
+ return (
+ typeof object === 'object' &&
+ typeof object.append === 'function' &&
+ typeof object.delete === 'function' &&
+ typeof object.get === 'function' &&
+ typeof object.getAll === 'function' &&
+ typeof object.has === 'function' &&
+ typeof object.set === 'function' &&
+ typeof object.sort === 'function' &&
+ object[NAME] === 'URLSearchParams'
+ );
+};
+
+/**
+ * Check if `object` is a W3C `Blob` object (which `File` inherits from)
+ * @param {*} object - Object to check for
+ * @return {boolean}
+ */
+const isBlob = object => {
+ return (
+ object &&
+ typeof object === 'object' &&
+ typeof object.arrayBuffer === 'function' &&
+ typeof object.type === 'string' &&
+ typeof object.stream === 'function' &&
+ typeof object.constructor === 'function' &&
+ /^(Blob|File)$/.test(object[NAME])
+ );
+};
+
+/**
+ * Check if `obj` is an instance of AbortSignal.
+ * @param {*} object - Object to check for
+ * @return {boolean}
+ */
+const isAbortSignal = object => {
+ return (
+ typeof object === 'object' && (
+ object[NAME] === 'AbortSignal' ||
+ object[NAME] === 'EventTarget'
+ )
+ );
+};
+
+/**
+ * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of
+ * the parent domain.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isDomainOrSubdomain = (destination, original) => {
+ const orig = new URL(original).hostname;
+ const dest = new URL(destination).hostname;
+
+ return orig === dest || orig.endsWith(`.${dest}`);
+};
+
+/**
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isSameProtocol = (destination, original) => {
+ const orig = new URL(original).protocol;
+ const dest = new URL(destination).protocol;
+
+ return orig === dest;
+};
+
+const pipeline = node_util.promisify(Stream$3.pipeline);
+const INTERNALS$2 = Symbol('Body internals');
+
+/**
+ * Body mixin
+ *
+ * Ref: https://fetch.spec.whatwg.org/#body
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+class Body {
+ constructor(body, {
+ size = 0
+ } = {}) {
+ let boundary = null;
+
+ if (body === null) {
+ // Body is undefined or null
+ body = null;
+ } else if (isURLSearchParameters(body)) {
+ // Body is a URLSearchParams
+ body = node_buffer.Buffer.from(body.toString());
+ } else if (isBlob(body)) ; else if (node_buffer.Buffer.isBuffer(body)) ; else if (node_util.types.isAnyArrayBuffer(body)) {
+ // Body is ArrayBuffer
+ body = node_buffer.Buffer.from(body);
+ } else if (ArrayBuffer.isView(body)) {
+ // Body is ArrayBufferView
+ body = node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength);
+ } else if (body instanceof Stream$3) ; else if (body instanceof FormData) {
+ // Body is FormData
+ body = formDataToBlob(body);
+ boundary = body.type.split('=')[1];
+ } else {
+ // None of the above
+ // coerce to string then buffer
+ body = node_buffer.Buffer.from(String(body));
+ }
+
+ let stream = body;
+
+ if (node_buffer.Buffer.isBuffer(body)) {
+ stream = Stream$3.Readable.from(body);
+ } else if (isBlob(body)) {
+ stream = Stream$3.Readable.from(body.stream());
+ }
+
+ this[INTERNALS$2] = {
+ body,
+ stream,
+ boundary,
+ disturbed: false,
+ error: null
+ };
+ this.size = size;
+
+ if (body instanceof Stream$3) {
+ body.on('error', error_ => {
+ const error = error_ instanceof FetchBaseError ?
+ error_ :
+ new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_);
+ this[INTERNALS$2].error = error;
+ });
+ }
+ }
+
+ get body() {
+ return this[INTERNALS$2].stream;
+ }
+
+ get bodyUsed() {
+ return this[INTERNALS$2].disturbed;
+ }
+
+ /**
+ * Decode response as ArrayBuffer
+ *
+ * @return Promise
+ */
+ async arrayBuffer() {
+ const {buffer, byteOffset, byteLength} = await consumeBody(this);
+ return buffer.slice(byteOffset, byteOffset + byteLength);
+ }
+
+ async formData() {
+ const ct = this.headers.get('content-type');
+
+ if (ct.startsWith('application/x-www-form-urlencoded')) {
+ const formData = new FormData();
+ const parameters = new URLSearchParams(await this.text());
+
+ for (const [name, value] of parameters) {
+ formData.append(name, value);
+ }
+
+ return formData;
+ }
+
+ const {toFormData} = await Promise.resolve().then(function () { return require('./multipart-parser-d1d13d05.js'); });
+ return toFormData(this.body, ct);
+ }
+
+ /**
+ * Return raw response as Blob
+ *
+ * @return Promise
+ */
+ async blob() {
+ const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS$2].body && this[INTERNALS$2].body.type) || '';
+ const buf = await this.arrayBuffer();
+
+ return new Blob$1([buf], {
+ type: ct
+ });
+ }
+
+ /**
+ * Decode response as json
+ *
+ * @return Promise
+ */
+ async json() {
+ const text = await this.text();
+ return JSON.parse(text);
+ }
+
+ /**
+ * Decode response as text
+ *
+ * @return Promise
+ */
+ async text() {
+ const buffer = await consumeBody(this);
+ return new TextDecoder().decode(buffer);
+ }
+
+ /**
+ * Decode response as buffer (non-spec api)
+ *
+ * @return Promise
+ */
+ buffer() {
+ return consumeBody(this);
+ }
+}
+
+Body.prototype.buffer = node_util.deprecate(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer');
+
+// In browsers, all properties are enumerable.
+Object.defineProperties(Body.prototype, {
+ body: {enumerable: true},
+ bodyUsed: {enumerable: true},
+ arrayBuffer: {enumerable: true},
+ blob: {enumerable: true},
+ json: {enumerable: true},
+ text: {enumerable: true},
+ data: {get: node_util.deprecate(() => {},
+ 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead',
+ 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')}
+});
+
+/**
+ * Consume and convert an entire Body to a Buffer.
+ *
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
+ *
+ * @return Promise
+ */
+async function consumeBody(data) {
+ if (data[INTERNALS$2].disturbed) {
+ throw new TypeError(`body used already for: ${data.url}`);
+ }
+
+ data[INTERNALS$2].disturbed = true;
+
+ if (data[INTERNALS$2].error) {
+ throw data[INTERNALS$2].error;
+ }
+
+ const {body} = data;
+
+ // Body is null
+ if (body === null) {
+ return node_buffer.Buffer.alloc(0);
+ }
+
+ /* c8 ignore next 3 */
+ if (!(body instanceof Stream$3)) {
+ return node_buffer.Buffer.alloc(0);
+ }
+
+ // Body is stream
+ // get ready to actually consume the body
+ const accum = [];
+ let accumBytes = 0;
+
+ try {
+ for await (const chunk of body) {
+ if (data.size > 0 && accumBytes + chunk.length > data.size) {
+ const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');
+ body.destroy(error);
+ throw error;
+ }
+
+ accumBytes += chunk.length;
+ accum.push(chunk);
+ }
+ } catch (error) {
+ const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);
+ throw error_;
+ }
+
+ if (body.readableEnded === true || body._readableState.ended === true) {
+ try {
+ if (accum.every(c => typeof c === 'string')) {
+ return node_buffer.Buffer.from(accum.join(''));
+ }
+
+ return node_buffer.Buffer.concat(accum, accumBytes);
+ } catch (error) {
+ throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);
+ }
+ } else {
+ throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
+ }
+}
+
+/**
+ * Clone body given Res/Req instance
+ *
+ * @param Mixed instance Response or Request instance
+ * @param String highWaterMark highWaterMark for both PassThrough body streams
+ * @return Mixed
+ */
+const clone = (instance, highWaterMark) => {
+ let p1;
+ let p2;
+ let {body} = instance[INTERNALS$2];
+
+ // Don't allow cloning a used body
+ if (instance.bodyUsed) {
+ throw new Error('cannot clone body after it is used');
+ }
+
+ // Check that body is a stream and not form-data object
+ // note: we can't clone the form-data object without having it as a dependency
+ if ((body instanceof Stream$3) && (typeof body.getBoundary !== 'function')) {
+ // Tee instance body
+ p1 = new Stream$3.PassThrough({highWaterMark});
+ p2 = new Stream$3.PassThrough({highWaterMark});
+ body.pipe(p1);
+ body.pipe(p2);
+ // Set instance body to teed body and return the other teed body
+ instance[INTERNALS$2].stream = p1;
+ body = p2;
+ }
+
+ return body;
+};
+
+const getNonSpecFormDataBoundary = node_util.deprecate(
+ body => body.getBoundary(),
+ 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package',
+ 'https://github.com/node-fetch/node-fetch/issues/1167'
+);
+
+/**
+ * Performs the operation "extract a `Content-Type` value from |object|" as
+ * specified in the specification:
+ * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+ *
+ * This function assumes that instance.body is present.
+ *
+ * @param {any} body Any options.body input
+ * @returns {string | null}
+ */
+const extractContentType = (body, request) => {
+ // Body is null or undefined
+ if (body === null) {
+ return null;
+ }
+
+ // Body is string
+ if (typeof body === 'string') {
+ return 'text/plain;charset=UTF-8';
+ }
+
+ // Body is a URLSearchParams
+ if (isURLSearchParameters(body)) {
+ return 'application/x-www-form-urlencoded;charset=UTF-8';
+ }
+
+ // Body is blob
+ if (isBlob(body)) {
+ return body.type || null;
+ }
+
+ // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView)
+ if (node_buffer.Buffer.isBuffer(body) || node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
+ return null;
+ }
+
+ if (body instanceof FormData) {
+ return `multipart/form-data; boundary=${request[INTERNALS$2].boundary}`;
+ }
+
+ // Detect form data input from form-data module
+ if (body && typeof body.getBoundary === 'function') {
+ return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
+ }
+
+ // Body is stream - can't really do much about this
+ if (body instanceof Stream$3) {
+ return null;
+ }
+
+ // Body constructor defaults other things to string
+ return 'text/plain;charset=UTF-8';
+};
+
+/**
+ * The Fetch Standard treats this as if "total bytes" is a property on the body.
+ * For us, we have to explicitly get it with a function.
+ *
+ * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
+ *
+ * @param {any} obj.body Body object from the Body instance.
+ * @returns {number | null}
+ */
+const getTotalBytes = request => {
+ const {body} = request[INTERNALS$2];
+
+ // Body is null or undefined
+ if (body === null) {
+ return 0;
+ }
+
+ // Body is Blob
+ if (isBlob(body)) {
+ return body.size;
+ }
+
+ // Body is Buffer
+ if (node_buffer.Buffer.isBuffer(body)) {
+ return body.length;
+ }
+
+ // Detect form data input from form-data module
+ if (body && typeof body.getLengthSync === 'function') {
+ return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
+ }
+
+ // Body is stream
+ return null;
+};
+
+/**
+ * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
+ *
+ * @param {Stream.Writable} dest The stream to write to.
+ * @param obj.body Body object from the Body instance.
+ * @returns {Promise}
+ */
+const writeToStream = async (dest, {body}) => {
+ if (body === null) {
+ // Body is null
+ dest.end();
+ } else {
+ // Body is stream
+ await pipeline(body, dest);
+ }
+};
+
+/**
+ * Headers.js
+ *
+ * Headers class offers convenient helpers
+ */
+
+/* c8 ignore next 9 */
+const validateHeaderName = typeof http$7.validateHeaderName === 'function' ?
+ http$7.validateHeaderName :
+ name => {
+ if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
+ const error = new TypeError(`Header name must be a valid HTTP token [${name}]`);
+ Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'});
+ throw error;
+ }
+ };
+
+/* c8 ignore next 9 */
+const validateHeaderValue = typeof http$7.validateHeaderValue === 'function' ?
+ http$7.validateHeaderValue :
+ (name, value) => {
+ if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
+ const error = new TypeError(`Invalid character in header content ["${name}"]`);
+ Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'});
+ throw error;
+ }
+ };
+
+/**
+ * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit
+ */
+
+/**
+ * This Fetch API interface allows you to perform various actions on HTTP request and response headers.
+ * These actions include retrieving, setting, adding to, and removing.
+ * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.
+ * You can add to this using methods like append() (see Examples.)
+ * In all methods of this interface, header names are matched by case-insensitive byte sequence.
+ *
+ */
+class Headers extends URLSearchParams {
+ /**
+ * Headers class
+ *
+ * @constructor
+ * @param {HeadersInit} [init] - Response headers
+ */
+ constructor(init) {
+ // Validate and normalize init object in [name, value(s)][]
+ /** @type {string[][]} */
+ let result = [];
+ if (init instanceof Headers) {
+ const raw = init.raw();
+ for (const [name, values] of Object.entries(raw)) {
+ result.push(...values.map(value => [name, value]));
+ }
+ } else if (init == null) ; else if (typeof init === 'object' && !node_util.types.isBoxedPrimitive(init)) {
+ const method = init[Symbol.iterator];
+ // eslint-disable-next-line no-eq-null, eqeqeq
+ if (method == null) {
+ // Record
+ result.push(...Object.entries(init));
+ } else {
+ if (typeof method !== 'function') {
+ throw new TypeError('Header pairs must be iterable');
+ }
+
+ // Sequence>
+ // Note: per spec we have to first exhaust the lists then process them
+ result = [...init]
+ .map(pair => {
+ if (
+ typeof pair !== 'object' || node_util.types.isBoxedPrimitive(pair)
+ ) {
+ throw new TypeError('Each header pair must be an iterable object');
+ }
+
+ return [...pair];
+ }).map(pair => {
+ if (pair.length !== 2) {
+ throw new TypeError('Each header pair must be a name/value tuple');
+ }
+
+ return [...pair];
+ });
+ }
+ } else {
+ throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence> or record)');
+ }
+
+ // Validate and lowercase
+ result =
+ result.length > 0 ?
+ result.map(([name, value]) => {
+ validateHeaderName(name);
+ validateHeaderValue(name, String(value));
+ return [String(name).toLowerCase(), String(value)];
+ }) :
+ undefined;
+
+ super(result);
+
+ // Returning a Proxy that will lowercase key names, validate parameters and sort keys
+ // eslint-disable-next-line no-constructor-return
+ return new Proxy(this, {
+ get(target, p, receiver) {
+ switch (p) {
+ case 'append':
+ case 'set':
+ return (name, value) => {
+ validateHeaderName(name);
+ validateHeaderValue(name, String(value));
+ return URLSearchParams.prototype[p].call(
+ target,
+ String(name).toLowerCase(),
+ String(value)
+ );
+ };
+
+ case 'delete':
+ case 'has':
+ case 'getAll':
+ return name => {
+ validateHeaderName(name);
+ return URLSearchParams.prototype[p].call(
+ target,
+ String(name).toLowerCase()
+ );
+ };
+
+ case 'keys':
+ return () => {
+ target.sort();
+ return new Set(URLSearchParams.prototype.keys.call(target)).keys();
+ };
+
+ default:
+ return Reflect.get(target, p, receiver);
+ }
+ }
+ });
+ /* c8 ignore next */
+ }
+
+ get [Symbol.toStringTag]() {
+ return this.constructor.name;
+ }
+
+ toString() {
+ return Object.prototype.toString.call(this);
+ }
+
+ get(name) {
+ const values = this.getAll(name);
+ if (values.length === 0) {
+ return null;
+ }
+
+ let value = values.join(', ');
+ if (/^content-encoding$/i.test(name)) {
+ value = value.toLowerCase();
+ }
+
+ return value;
+ }
+
+ forEach(callback, thisArg = undefined) {
+ for (const name of this.keys()) {
+ Reflect.apply(callback, thisArg, [this.get(name), name, this]);
+ }
+ }
+
+ * values() {
+ for (const name of this.keys()) {
+ yield this.get(name);
+ }
+ }
+
+ /**
+ * @type {() => IterableIterator<[string, string]>}
+ */
+ * entries() {
+ for (const name of this.keys()) {
+ yield [name, this.get(name)];
+ }
+ }
+
+ [Symbol.iterator]() {
+ return this.entries();
+ }
+
+ /**
+ * Node-fetch non-spec method
+ * returning all headers and their values as array
+ * @returns {Record}
+ */
+ raw() {
+ return [...this.keys()].reduce((result, key) => {
+ result[key] = this.getAll(key);
+ return result;
+ }, {});
+ }
+
+ /**
+ * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
+ */
+ [Symbol.for('nodejs.util.inspect.custom')]() {
+ return [...this.keys()].reduce((result, key) => {
+ const values = this.getAll(key);
+ // Http.request() only supports string as Host header.
+ // This hack makes specifying custom Host header possible.
+ if (key === 'host') {
+ result[key] = values[0];
+ } else {
+ result[key] = values.length > 1 ? values : values[0];
+ }
+
+ return result;
+ }, {});
+ }
+}
+
+/**
+ * Re-shaping object for Web IDL tests
+ * Only need to do it for overridden methods
+ */
+Object.defineProperties(
+ Headers.prototype,
+ ['get', 'entries', 'forEach', 'values'].reduce((result, property) => {
+ result[property] = {enumerable: true};
+ return result;
+ }, {})
+);
+
+/**
+ * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do
+ * not conform to HTTP grammar productions.
+ * @param {import('http').IncomingMessage['rawHeaders']} headers
+ */
+function fromRawHeaders(headers = []) {
+ return new Headers(
+ headers
+ // Split into pairs
+ .reduce((result, value, index, array) => {
+ if (index % 2 === 0) {
+ result.push(array.slice(index, index + 2));
+ }
+
+ return result;
+ }, [])
+ .filter(([name, value]) => {
+ try {
+ validateHeaderName(name);
+ validateHeaderValue(name, String(value));
+ return true;
+ } catch {
+ return false;
+ }
+ })
+
+ );
+}
+
+const redirectStatus = new Set([301, 302, 303, 307, 308]);
+
+/**
+ * Redirect code matching
+ *
+ * @param {number} code - Status code
+ * @return {boolean}
+ */
+const isRedirect = code => {
+ return redirectStatus.has(code);
+};
+
+/**
+ * Response.js
+ *
+ * Response class provides content decoding
+ */
+
+const INTERNALS$1 = Symbol('Response internals');
+
+/**
+ * Response class
+ *
+ * Ref: https://fetch.spec.whatwg.org/#response-class
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+class Response extends Body {
+ constructor(body = null, options = {}) {
+ super(body, options);
+
+ // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition
+ const status = options.status != null ? options.status : 200;
+
+ const headers = new Headers(options.headers);
+
+ if (body !== null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(body, this);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ this[INTERNALS$1] = {
+ type: 'default',
+ url: options.url,
+ status,
+ statusText: options.statusText || '',
+ headers,
+ counter: options.counter,
+ highWaterMark: options.highWaterMark
+ };
+ }
+
+ get type() {
+ return this[INTERNALS$1].type;
+ }
+
+ get url() {
+ return this[INTERNALS$1].url || '';
+ }
+
+ get status() {
+ return this[INTERNALS$1].status;
+ }
+
+ /**
+ * Convenience property representing if the request ended normally
+ */
+ get ok() {
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
+ }
+
+ get redirected() {
+ return this[INTERNALS$1].counter > 0;
+ }
+
+ get statusText() {
+ return this[INTERNALS$1].statusText;
+ }
+
+ get headers() {
+ return this[INTERNALS$1].headers;
+ }
+
+ get highWaterMark() {
+ return this[INTERNALS$1].highWaterMark;
+ }
+
+ /**
+ * Clone this response
+ *
+ * @return Response
+ */
+ clone() {
+ return new Response(clone(this, this.highWaterMark), {
+ type: this.type,
+ url: this.url,
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ ok: this.ok,
+ redirected: this.redirected,
+ size: this.size,
+ highWaterMark: this.highWaterMark
+ });
+ }
+
+ /**
+ * @param {string} url The URL that the new response is to originate from.
+ * @param {number} status An optional status code for the response (e.g., 302.)
+ * @returns {Response} A Response object.
+ */
+ static redirect(url, status = 302) {
+ if (!isRedirect(status)) {
+ throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
+ }
+
+ return new Response(null, {
+ headers: {
+ location: new URL(url).toString()
+ },
+ status
+ });
+ }
+
+ static error() {
+ const response = new Response(null, {status: 0, statusText: ''});
+ response[INTERNALS$1].type = 'error';
+ return response;
+ }
+
+ static json(data = undefined, init = {}) {
+ const body = JSON.stringify(data);
+
+ if (body === undefined) {
+ throw new TypeError('data is not JSON serializable');
+ }
+
+ const headers = new Headers(init && init.headers);
+
+ if (!headers.has('content-type')) {
+ headers.set('content-type', 'application/json');
+ }
+
+ return new Response(body, {
+ ...init,
+ headers
+ });
+ }
+
+ get [Symbol.toStringTag]() {
+ return 'Response';
+ }
+}
+
+Object.defineProperties(Response.prototype, {
+ type: {enumerable: true},
+ url: {enumerable: true},
+ status: {enumerable: true},
+ ok: {enumerable: true},
+ redirected: {enumerable: true},
+ statusText: {enumerable: true},
+ headers: {enumerable: true},
+ clone: {enumerable: true}
+});
+
+const getSearch = parsedURL => {
+ if (parsedURL.search) {
+ return parsedURL.search;
+ }
+
+ const lastOffset = parsedURL.href.length - 1;
+ const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : '');
+ return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : '';
+};
+
+/**
+ * @external URL
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL}
+ */
+
+/**
+ * @module utils/referrer
+ * @private
+ */
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer}
+ * @param {string} URL
+ * @param {boolean} [originOnly=false]
+ */
+function stripURLForUseAsAReferrer(url, originOnly = false) {
+ // 1. If url is null, return no referrer.
+ if (url == null) { // eslint-disable-line no-eq-null, eqeqeq
+ return 'no-referrer';
+ }
+
+ url = new URL(url);
+
+ // 2. If url's scheme is a local scheme, then return no referrer.
+ if (/^(about|blob|data):$/.test(url.protocol)) {
+ return 'no-referrer';
+ }
+
+ // 3. Set url's username to the empty string.
+ url.username = '';
+
+ // 4. Set url's password to null.
+ // Note: `null` appears to be a mistake as this actually results in the password being `"null"`.
+ url.password = '';
+
+ // 5. Set url's fragment to null.
+ // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`.
+ url.hash = '';
+
+ // 6. If the origin-only flag is true, then:
+ if (originOnly) {
+ // 6.1. Set url's path to null.
+ // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`.
+ url.pathname = '';
+
+ // 6.2. Set url's query to null.
+ // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`.
+ url.search = '';
+ }
+
+ // 7. Return url.
+ return url;
+}
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy}
+ */
+const ReferrerPolicy = new Set([
+ '',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'same-origin',
+ 'origin',
+ 'strict-origin',
+ 'origin-when-cross-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url'
+]);
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy}
+ */
+const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin';
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies}
+ * @param {string} referrerPolicy
+ * @returns {string} referrerPolicy
+ */
+function validateReferrerPolicy(referrerPolicy) {
+ if (!ReferrerPolicy.has(referrerPolicy)) {
+ throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
+ }
+
+ return referrerPolicy;
+}
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?}
+ * @param {external:URL} url
+ * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
+ */
+function isOriginPotentiallyTrustworthy(url) {
+ // 1. If origin is an opaque origin, return "Not Trustworthy".
+ // Not applicable
+
+ // 2. Assert: origin is a tuple origin.
+ // Not for implementations
+
+ // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy".
+ if (/^(http|ws)s:$/.test(url.protocol)) {
+ return true;
+ }
+
+ // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
+ const hostIp = url.host.replace(/(^\[)|(]$)/g, '');
+ const hostIPVersion = node_net.isIP(hostIp);
+
+ if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
+ return true;
+ }
+
+ if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
+ return true;
+ }
+
+ // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy".
+ // We are returning FALSE here because we cannot ensure conformance to
+ // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)
+ if (url.host === 'localhost' || url.host.endsWith('.localhost')) {
+ return false;
+ }
+
+ // 6. If origin's scheme component is file, return "Potentially Trustworthy".
+ if (url.protocol === 'file:') {
+ return true;
+ }
+
+ // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy".
+ // Not supported
+
+ // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy".
+ // Not supported
+
+ // 9. Return "Not Trustworthy".
+ return false;
+}
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?}
+ * @param {external:URL} url
+ * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy"
+ */
+function isUrlPotentiallyTrustworthy(url) {
+ // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy".
+ if (/^about:(blank|srcdoc)$/.test(url)) {
+ return true;
+ }
+
+ // 2. If url's scheme is "data", return "Potentially Trustworthy".
+ if (url.protocol === 'data:') {
+ return true;
+ }
+
+ // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were
+ // created. Therefore, blobs created in a trustworthy origin will themselves be potentially
+ // trustworthy.
+ if (/^(blob|filesystem):$/.test(url.protocol)) {
+ return true;
+ }
+
+ // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin.
+ return isOriginPotentiallyTrustworthy(url);
+}
+
+/**
+ * Modifies the referrerURL to enforce any extra security policy considerations.
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7
+ * @callback module:utils/referrer~referrerURLCallback
+ * @param {external:URL} referrerURL
+ * @returns {external:URL} modified referrerURL
+ */
+
+/**
+ * Modifies the referrerOrigin to enforce any extra security policy considerations.
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7
+ * @callback module:utils/referrer~referrerOriginCallback
+ * @param {external:URL} referrerOrigin
+ * @returns {external:URL} modified referrerOrigin
+ */
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}
+ * @param {Request} request
+ * @param {object} o
+ * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback
+ * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback
+ * @returns {external:URL} Request's referrer
+ */
+function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) {
+ // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for
+ // these cases:
+ // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm.
+ // > Note: If request's referrer policy is the empty string, Fetch will not call into this
+ // > algorithm.
+ if (request.referrer === 'no-referrer' || request.referrerPolicy === '') {
+ return null;
+ }
+
+ // 1. Let policy be request's associated referrer policy.
+ const policy = request.referrerPolicy;
+
+ // 2. Let environment be request's client.
+ // not applicable to node.js
+
+ // 3. Switch on request's referrer:
+ if (request.referrer === 'about:client') {
+ return 'no-referrer';
+ }
+
+ // "a URL": Let referrerSource be request's referrer.
+ const referrerSource = request.referrer;
+
+ // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer.
+ let referrerURL = stripURLForUseAsAReferrer(referrerSource);
+
+ // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the
+ // origin-only flag set to true.
+ let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
+
+ // 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set
+ // referrerURL to referrerOrigin.
+ if (referrerURL.toString().length > 4096) {
+ referrerURL = referrerOrigin;
+ }
+
+ // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary
+ // policy considerations in the interests of minimizing data leakage. For example, the user
+ // agent could strip the URL down to an origin, modify its host, replace it with an empty
+ // string, etc.
+ if (referrerURLCallback) {
+ referrerURL = referrerURLCallback(referrerURL);
+ }
+
+ if (referrerOriginCallback) {
+ referrerOrigin = referrerOriginCallback(referrerOrigin);
+ }
+
+ // 8.Execute the statements corresponding to the value of policy:
+ const currentURL = new URL(request.url);
+
+ switch (policy) {
+ case 'no-referrer':
+ return 'no-referrer';
+
+ case 'origin':
+ return referrerOrigin;
+
+ case 'unsafe-url':
+ return referrerURL;
+
+ case 'strict-origin':
+ // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a
+ // potentially trustworthy URL, then return no referrer.
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer';
+ }
+
+ // 2. Return referrerOrigin.
+ return referrerOrigin.toString();
+
+ case 'strict-origin-when-cross-origin':
+ // 1. If the origin of referrerURL and the origin of request's current URL are the same, then
+ // return referrerURL.
+ if (referrerURL.origin === currentURL.origin) {
+ return referrerURL;
+ }
+
+ // 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a
+ // potentially trustworthy URL, then return no referrer.
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer';
+ }
+
+ // 3. Return referrerOrigin.
+ return referrerOrigin;
+
+ case 'same-origin':
+ // 1. If the origin of referrerURL and the origin of request's current URL are the same, then
+ // return referrerURL.
+ if (referrerURL.origin === currentURL.origin) {
+ return referrerURL;
+ }
+
+ // 2. Return no referrer.
+ return 'no-referrer';
+
+ case 'origin-when-cross-origin':
+ // 1. If the origin of referrerURL and the origin of request's current URL are the same, then
+ // return referrerURL.
+ if (referrerURL.origin === currentURL.origin) {
+ return referrerURL;
+ }
+
+ // Return referrerOrigin.
+ return referrerOrigin;
+
+ case 'no-referrer-when-downgrade':
+ // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a
+ // potentially trustworthy URL, then return no referrer.
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer';
+ }
+
+ // 2. Return referrerURL.
+ return referrerURL;
+
+ default:
+ throw new TypeError(`Invalid referrerPolicy: ${policy}`);
+ }
+}
+
+/**
+ * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header}
+ * @param {Headers} headers Response headers
+ * @returns {string} policy
+ */
+function parseReferrerPolicyFromHeader(headers) {
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy`
+ // and response’s header list.
+ const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/);
+
+ // 2. Let policy be the empty string.
+ let policy = '';
+
+ // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty
+ // string, then set policy to token.
+ // Note: This algorithm loops over multiple policy values to allow deployment of new policy
+ // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values.
+ for (const token of policyTokens) {
+ if (token && ReferrerPolicy.has(token)) {
+ policy = token;
+ }
+ }
+
+ // 4. Return policy.
+ return policy;
+}
+
+/**
+ * Request.js
+ *
+ * Request class contains server only options
+ *
+ * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
+ */
+
+const INTERNALS = Symbol('Request internals');
+
+/**
+ * Check if `obj` is an instance of Request.
+ *
+ * @param {*} object
+ * @return {boolean}
+ */
+const isRequest = object => {
+ return (
+ typeof object === 'object' &&
+ typeof object[INTERNALS] === 'object'
+ );
+};
+
+const doBadDataWarn = node_util.deprecate(() => {},
+ '.data is not a valid RequestInit property, use .body instead',
+ 'https://github.com/node-fetch/node-fetch/issues/1000 (request)');
+
+/**
+ * Request class
+ *
+ * Ref: https://fetch.spec.whatwg.org/#request-class
+ *
+ * @param Mixed input Url or Request instance
+ * @param Object init Custom options
+ * @return Void
+ */
+class Request extends Body {
+ constructor(input, init = {}) {
+ let parsedURL;
+
+ // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245)
+ if (isRequest(input)) {
+ parsedURL = new URL(input.url);
+ } else {
+ parsedURL = new URL(input);
+ input = {};
+ }
+
+ if (parsedURL.username !== '' || parsedURL.password !== '') {
+ throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
+ }
+
+ let method = init.method || input.method || 'GET';
+ if (/^(delete|get|head|options|post|put)$/i.test(method)) {
+ method = method.toUpperCase();
+ }
+
+ if (!isRequest(init) && 'data' in init) {
+ doBadDataWarn();
+ }
+
+ // eslint-disable-next-line no-eq-null, eqeqeq
+ if ((init.body != null || (isRequest(input) && input.body !== null)) &&
+ (method === 'GET' || method === 'HEAD')) {
+ throw new TypeError('Request with GET/HEAD method cannot have body');
+ }
+
+ const inputBody = init.body ?
+ init.body :
+ (isRequest(input) && input.body !== null ?
+ clone(input) :
+ null);
+
+ super(inputBody, {
+ size: init.size || input.size || 0
+ });
+
+ const headers = new Headers(init.headers || input.headers || {});
+
+ if (inputBody !== null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(inputBody, this);
+ if (contentType) {
+ headers.set('Content-Type', contentType);
+ }
+ }
+
+ let signal = isRequest(input) ?
+ input.signal :
+ null;
+ if ('signal' in init) {
+ signal = init.signal;
+ }
+
+ // eslint-disable-next-line no-eq-null, eqeqeq
+ if (signal != null && !isAbortSignal(signal)) {
+ throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');
+ }
+
+ // §5.4, Request constructor steps, step 15.1
+ // eslint-disable-next-line no-eq-null, eqeqeq
+ let referrer = init.referrer == null ? input.referrer : init.referrer;
+ if (referrer === '') {
+ // §5.4, Request constructor steps, step 15.2
+ referrer = 'no-referrer';
+ } else if (referrer) {
+ // §5.4, Request constructor steps, step 15.3.1, 15.3.2
+ const parsedReferrer = new URL(referrer);
+ // §5.4, Request constructor steps, step 15.3.3, 15.3.4
+ referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer;
+ } else {
+ referrer = undefined;
+ }
+
+ this[INTERNALS] = {
+ method,
+ redirect: init.redirect || input.redirect || 'follow',
+ headers,
+ parsedURL,
+ signal,
+ referrer
+ };
+
+ // Node-fetch-only options
+ this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow;
+ this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress;
+ this.counter = init.counter || input.counter || 0;
+ this.agent = init.agent || input.agent;
+ this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
+ this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
+
+ // §5.4, Request constructor steps, step 16.
+ // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy
+ this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || '';
+ }
+
+ /** @returns {string} */
+ get method() {
+ return this[INTERNALS].method;
+ }
+
+ /** @returns {string} */
+ get url() {
+ return node_url.format(this[INTERNALS].parsedURL);
+ }
+
+ /** @returns {Headers} */
+ get headers() {
+ return this[INTERNALS].headers;
+ }
+
+ get redirect() {
+ return this[INTERNALS].redirect;
+ }
+
+ /** @returns {AbortSignal} */
+ get signal() {
+ return this[INTERNALS].signal;
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-request-referrer
+ get referrer() {
+ if (this[INTERNALS].referrer === 'no-referrer') {
+ return '';
+ }
+
+ if (this[INTERNALS].referrer === 'client') {
+ return 'about:client';
+ }
+
+ if (this[INTERNALS].referrer) {
+ return this[INTERNALS].referrer.toString();
+ }
+
+ return undefined;
+ }
+
+ get referrerPolicy() {
+ return this[INTERNALS].referrerPolicy;
+ }
+
+ set referrerPolicy(referrerPolicy) {
+ this[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy);
+ }
+
+ /**
+ * Clone this request
+ *
+ * @return Request
+ */
+ clone() {
+ return new Request(this);
+ }
+
+ get [Symbol.toStringTag]() {
+ return 'Request';
+ }
+}
+
+Object.defineProperties(Request.prototype, {
+ method: {enumerable: true},
+ url: {enumerable: true},
+ headers: {enumerable: true},
+ redirect: {enumerable: true},
+ clone: {enumerable: true},
+ signal: {enumerable: true},
+ referrer: {enumerable: true},
+ referrerPolicy: {enumerable: true}
+});
+
+/**
+ * Convert a Request to Node.js http request options.
+ *
+ * @param {Request} request - A Request instance
+ * @return The options object to be passed to http.request
+ */
+const getNodeRequestOptions = request => {
+ const {parsedURL} = request[INTERNALS];
+ const headers = new Headers(request[INTERNALS].headers);
+
+ // Fetch step 1.3
+ if (!headers.has('Accept')) {
+ headers.set('Accept', '*/*');
+ }
+
+ // HTTP-network-or-cache fetch steps 2.4-2.7
+ let contentLengthValue = null;
+ if (request.body === null && /^(post|put)$/i.test(request.method)) {
+ contentLengthValue = '0';
+ }
+
+ if (request.body !== null) {
+ const totalBytes = getTotalBytes(request);
+ // Set Content-Length if totalBytes is a number (that is not NaN)
+ if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) {
+ contentLengthValue = String(totalBytes);
+ }
+ }
+
+ if (contentLengthValue) {
+ headers.set('Content-Length', contentLengthValue);
+ }
+
+ // 4.1. Main fetch, step 2.6
+ // > If request's referrer policy is the empty string, then set request's referrer policy to the
+ // > default referrer policy.
+ if (request.referrerPolicy === '') {
+ request.referrerPolicy = DEFAULT_REFERRER_POLICY;
+ }
+
+ // 4.1. Main fetch, step 2.7
+ // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking
+ // > determine request's referrer.
+ if (request.referrer && request.referrer !== 'no-referrer') {
+ request[INTERNALS].referrer = determineRequestsReferrer(request);
+ } else {
+ request[INTERNALS].referrer = 'no-referrer';
+ }
+
+ // 4.5. HTTP-network-or-cache fetch, step 6.9
+ // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized
+ // > and isomorphic encoded, to httpRequest's header list.
+ if (request[INTERNALS].referrer instanceof URL) {
+ headers.set('Referer', request.referrer);
+ }
+
+ // HTTP-network-or-cache fetch step 2.11
+ if (!headers.has('User-Agent')) {
+ headers.set('User-Agent', 'node-fetch');
+ }
+
+ // HTTP-network-or-cache fetch step 2.15
+ if (request.compress && !headers.has('Accept-Encoding')) {
+ headers.set('Accept-Encoding', 'gzip, deflate, br');
+ }
+
+ let {agent} = request;
+ if (typeof agent === 'function') {
+ agent = agent(parsedURL);
+ }
+
+ if (!headers.has('Connection') && !agent) {
+ headers.set('Connection', 'close');
+ }
+
+ // HTTP-network fetch step 4.2
+ // chunked encoding is handled by Node.js
+
+ const search = getSearch(parsedURL);
+
+ // Pass the full URL directly to request(), but overwrite the following
+ // options:
+ const options = {
+ // Overwrite search to retain trailing ? (issue #776)
+ path: parsedURL.pathname + search,
+ // The following options are not expressed in the URL
+ method: request.method,
+ headers: headers[Symbol.for('nodejs.util.inspect.custom')](),
+ insecureHTTPParser: request.insecureHTTPParser,
+ agent
+ };
+
+ return {
+ /** @type {URL} */
+ parsedURL,
+ options
+ };
+};
+
+/**
+ * AbortError interface for cancelled requests
+ */
+let AbortError$1 = class AbortError extends FetchBaseError {
+ constructor(message, type = 'aborted') {
+ super(message, type);
+ }
+};
+
+/*! node-domexception. MIT License. Jimmy Wärting */
+
+if (!globalThis.DOMException) {
+ try {
+ const { MessageChannel } = require('worker_threads'),
+ port = new MessageChannel().port1,
+ ab = new ArrayBuffer();
+ port.postMessage(ab, [ab, ab]);
+ } catch (err) {
+ err.constructor.name === 'DOMException' && (
+ globalThis.DOMException = err.constructor
+ );
+ }
+}
+
+/**
+ * Index.js
+ *
+ * a request API compatible with window.fetch
+ *
+ * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.
+ */
+
+const supportedSchemas = new Set(['data:', 'http:', 'https:']);
+
+/**
+ * Fetch function
+ *
+ * @param {string | URL | import('./request').default} url - Absolute url or Request instance
+ * @param {*} [options_] - Fetch options
+ * @return {Promise}
+ */
+async function fetch$1(url, options_) {
+ return new Promise((resolve, reject) => {
+ // Build request object
+ const request = new Request(url, options_);
+ const {parsedURL, options} = getNodeRequestOptions(request);
+ if (!supportedSchemas.has(parsedURL.protocol)) {
+ throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`);
+ }
+
+ if (parsedURL.protocol === 'data:') {
+ const data = dataUriToBuffer(request.url);
+ const response = new Response(data, {headers: {'Content-Type': data.typeFull}});
+ resolve(response);
+ return;
+ }
+
+ // Wrap http.request into fetch
+ const send = (parsedURL.protocol === 'https:' ? https$4 : http$7).request;
+ const {signal} = request;
+ let response = null;
+
+ const abort = () => {
+ const error = new AbortError$1('The operation was aborted.');
+ reject(error);
+ if (request.body && request.body instanceof Stream$3.Readable) {
+ request.body.destroy(error);
+ }
+
+ if (!response || !response.body) {
+ return;
+ }
+
+ response.body.emit('error', error);
+ };
+
+ if (signal && signal.aborted) {
+ abort();
+ return;
+ }
+
+ const abortAndFinalize = () => {
+ abort();
+ finalize();
+ };
+
+ // Send request
+ const request_ = send(parsedURL.toString(), options);
+
+ if (signal) {
+ signal.addEventListener('abort', abortAndFinalize);
+ }
+
+ const finalize = () => {
+ request_.abort();
+ if (signal) {
+ signal.removeEventListener('abort', abortAndFinalize);
+ }
+ };
+
+ request_.on('error', error => {
+ reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));
+ finalize();
+ });
+
+ fixResponseChunkedTransferBadEnding(request_, error => {
+ if (response && response.body) {
+ response.body.destroy(error);
+ }
+ });
+
+ /* c8 ignore next 18 */
+ if (process.version < 'v14') {
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
+ // properly handle when the socket close/end events are out of order.
+ request_.on('socket', s => {
+ let endedWithEventsCount;
+ s.prependListener('end', () => {
+ endedWithEventsCount = s._eventsCount;
+ });
+ s.prependListener('close', hadError => {
+ // if end happened before close but the socket didn't emit an error, do it now
+ if (response && endedWithEventsCount < s._eventsCount && !hadError) {
+ const error = new Error('Premature close');
+ error.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ response.body.emit('error', error);
+ }
+ });
+ });
+ }
+
+ request_.on('response', response_ => {
+ request_.setTimeout(0);
+ const headers = fromRawHeaders(response_.rawHeaders);
+
+ // HTTP fetch step 5
+ if (isRedirect(response_.statusCode)) {
+ // HTTP fetch step 5.2
+ const location = headers.get('Location');
+
+ // HTTP fetch step 5.3
+ let locationURL = null;
+ try {
+ locationURL = location === null ? null : new URL(location, request.url);
+ } catch {
+ // error here can only be invalid URL in Location: header
+ // do not throw when options.redirect == manual
+ // let the user extract the errorneous redirect URL
+ if (request.redirect !== 'manual') {
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
+ finalize();
+ return;
+ }
+ }
+
+ // HTTP fetch step 5.5
+ switch (request.redirect) {
+ case 'error':
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
+ finalize();
+ return;
+ case 'manual':
+ // Nothing to do
+ break;
+ case 'follow': {
+ // HTTP-redirect fetch step 2
+ if (locationURL === null) {
+ break;
+ }
+
+ // HTTP-redirect fetch step 5
+ if (request.counter >= request.follow) {
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 6 (counter increment)
+ // Create a new Request object.
+ const requestOptions = {
+ headers: new Headers(request.headers),
+ follow: request.follow,
+ counter: request.counter + 1,
+ agent: request.agent,
+ compress: request.compress,
+ method: request.method,
+ body: clone(request),
+ signal: request.signal,
+ size: request.size,
+ referrer: request.referrer,
+ referrerPolicy: request.referrerPolicy
+ };
+
+ // when forwarding sensitive headers like "Authorization",
+ // "WWW-Authenticate", and "Cookie" to untrusted targets,
+ // headers will be ignored when following a redirect to a domain
+ // that is not a subdomain match or exact match of the initial domain.
+ // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
+ // will forward the sensitive headers, but a redirect to "bar.com" will not.
+ // headers will also be ignored when following a redirect to a domain using
+ // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com"
+ // will not forward the sensitive headers
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
+ requestOptions.headers.delete(name);
+ }
+ }
+
+ // HTTP-redirect fetch step 9
+ if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream$3.Readable) {
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 11
+ if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) {
+ requestOptions.method = 'GET';
+ requestOptions.body = undefined;
+ requestOptions.headers.delete('content-length');
+ }
+
+ // HTTP-redirect fetch step 14
+ const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
+ if (responseReferrerPolicy) {
+ requestOptions.referrerPolicy = responseReferrerPolicy;
+ }
+
+ // HTTP-redirect fetch step 15
+ resolve(fetch$1(new Request(locationURL, requestOptions)));
+ finalize();
+ return;
+ }
+
+ default:
+ return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
+ }
+ }
+
+ // Prepare response
+ if (signal) {
+ response_.once('end', () => {
+ signal.removeEventListener('abort', abortAndFinalize);
+ });
+ }
+
+ let body = Stream$3.pipeline(response_, new Stream$3.PassThrough(), error => {
+ if (error) {
+ reject(error);
+ }
+ });
+ // see https://github.com/nodejs/node/pull/29376
+ /* c8 ignore next 3 */
+ if (process.version < 'v12.10') {
+ response_.on('aborted', abortAndFinalize);
+ }
+
+ const responseOptions = {
+ url: request.url,
+ status: response_.statusCode,
+ statusText: response_.statusMessage,
+ headers,
+ size: request.size,
+ counter: request.counter,
+ highWaterMark: request.highWaterMark
+ };
+
+ // HTTP-network fetch step 12.1.1.3
+ const codings = headers.get('Content-Encoding');
+
+ // HTTP-network fetch step 12.1.1.4: handle content codings
+
+ // in following scenarios we ignore compression support
+ // 1. compression support is disabled
+ // 2. HEAD request
+ // 3. no Content-Encoding header
+ // 4. no content response (204)
+ // 5. content not modified response (304)
+ if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
+ response = new Response(body, responseOptions);
+ resolve(response);
+ return;
+ }
+
+ // For Node v6+
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ const zlibOptions = {
+ flush: zlib$3.Z_SYNC_FLUSH,
+ finishFlush: zlib$3.Z_SYNC_FLUSH
+ };
+
+ // For gzip
+ if (codings === 'gzip' || codings === 'x-gzip') {
+ body = Stream$3.pipeline(body, zlib$3.createGunzip(zlibOptions), error => {
+ if (error) {
+ reject(error);
+ }
+ });
+ response = new Response(body, responseOptions);
+ resolve(response);
+ return;
+ }
+
+ // For deflate
+ if (codings === 'deflate' || codings === 'x-deflate') {
+ // Handle the infamous raw deflate response from old servers
+ // a hack for old IIS and Apache servers
+ const raw = Stream$3.pipeline(response_, new Stream$3.PassThrough(), error => {
+ if (error) {
+ reject(error);
+ }
+ });
+ raw.once('data', chunk => {
+ // See http://stackoverflow.com/questions/37519828
+ if ((chunk[0] & 0x0F) === 0x08) {
+ body = Stream$3.pipeline(body, zlib$3.createInflate(), error => {
+ if (error) {
+ reject(error);
+ }
+ });
+ } else {
+ body = Stream$3.pipeline(body, zlib$3.createInflateRaw(), error => {
+ if (error) {
+ reject(error);
+ }
+ });
+ }
+
+ response = new Response(body, responseOptions);
+ resolve(response);
+ });
+ raw.once('end', () => {
+ // Some old IIS servers return zero-length OK deflate responses, so
+ // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903
+ if (!response) {
+ response = new Response(body, responseOptions);
+ resolve(response);
+ }
+ });
+ return;
+ }
+
+ // For br
+ if (codings === 'br') {
+ body = Stream$3.pipeline(body, zlib$3.createBrotliDecompress(), error => {
+ if (error) {
+ reject(error);
+ }
+ });
+ response = new Response(body, responseOptions);
+ resolve(response);
+ return;
+ }
+
+ // Otherwise, use response as-is
+ response = new Response(body, responseOptions);
+ resolve(response);
+ });
+
+ // eslint-disable-next-line promise/prefer-await-to-then
+ writeToStream(request_, request).catch(reject);
+ });
+}
+
+function fixResponseChunkedTransferBadEnding(request, errorCallback) {
+ const LAST_CHUNK = node_buffer.Buffer.from('0\r\n\r\n');
+
+ let isChunkedTransfer = false;
+ let properLastChunkReceived = false;
+ let previousChunk;
+
+ request.on('response', response => {
+ const {headers} = response;
+ isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length'];
+ });
+
+ request.on('socket', socket => {
+ const onSocketClose = () => {
+ if (isChunkedTransfer && !properLastChunkReceived) {
+ const error = new Error('Premature close');
+ error.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ errorCallback(error);
+ }
+ };
+
+ const onData = buf => {
+ properLastChunkReceived = node_buffer.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;
+
+ // Sometimes final 0-length chunk and end of message code are in separate packets
+ if (!properLastChunkReceived && previousChunk) {
+ properLastChunkReceived = (
+ node_buffer.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 &&
+ node_buffer.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0
+ );
+ }
+
+ previousChunk = buf;
+ };
+
+ socket.prependListener('close', onSocketClose);
+ socket.on('data', onData);
+
+ request.on('close', () => {
+ socket.removeListener('close', onSocketClose);
+ socket.removeListener('data', onData);
+ });
+ });
+}
+
+if (!globalThis.fetch) {
+ globalThis.fetch = fetch$1;
+ globalThis.Headers = Headers;
+ globalThis.Request = Request;
+ globalThis.Response = Response;
+}
+
+// This file includes code which was modified from https://github.com/openai/gpt-2
+const fs = require$$0$e;
+const path = require$$0$c;
+
+const encoder = JSON.parse(fs.readFileSync(path.join(__dirname, './encoder.json')));
+const bpe_file = fs.readFileSync(path.join(__dirname, './vocab.bpe'), 'utf-8');
+
+const range = (x, y) => {
+ const res = Array.from(Array(y).keys()).slice(x);
+ return res
+};
+
+const ord = x => {
+ return x.charCodeAt(0)
+};
+
+const chr = x => {
+ return String.fromCharCode(x)
+};
+
+const textEncoder = new TextEncoder("utf-8");
+const encodeStr = str => {
+ return Array.from(textEncoder.encode(str)).map(x => x.toString())
+};
+
+const textDecoder = new TextDecoder("utf-8");
+const decodeStr = arr => {
+ return textDecoder.decode(new Uint8Array(arr));
+};
+
+const dictZip = (x, y) => {
+ const result = {};
+ x.map((_, i) => { result[x[i]] = y[i]; });
+ return result
+};
+
+function bytes_to_unicode() {
+ const bs = range(ord('!'), ord('~') + 1).concat(range(ord('¡'), ord('¬') + 1), range(ord('®'), ord('ÿ') + 1));
+
+ let cs = bs.slice();
+ let n = 0;
+ for (let b = 0; b < 2 ** 8; b++) {
+ if (!bs.includes(b)) {
+ bs.push(b);
+ cs.push(2 ** 8 + n);
+ n = n + 1;
+ }
+ }
+
+ cs = cs.map(x => chr(x));
+
+ const result = {};
+ bs.map((_, i) => { result[bs[i]] = cs[i]; });
+ return result
+}
+
+function get_pairs(word) {
+ const pairs = new Set();
+ let prev_char = word[0];
+ for (let i = 1; i < word.length; i++) {
+ const char = word[i];
+ pairs.add([prev_char, char]);
+ prev_char = char;
+ }
+ return pairs
+}
+
+const pat = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
+
+const decoder = {};
+Object.keys(encoder).map(x => { decoder[encoder[x]] = x; });
+
+const lines = bpe_file.split('\n');
+
+// bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split("\n")[1:-1]]
+const bpe_merges = lines.slice(1, lines.length - 1).map(x => {
+ return x.split(/(\s+)/).filter(function(e) { return e.trim().length > 0 })
+});
+
+const byte_encoder = bytes_to_unicode();
+const byte_decoder = {};
+Object.keys(byte_encoder).map(x => { byte_decoder[byte_encoder[x]] = x; });
+
+const bpe_ranks = dictZip(bpe_merges, range(0, bpe_merges.length));
+const cache = new Map;
+
+function bpe(token) {
+ if (cache.has(token)) {
+ return cache.get(token)
+ }
+ let word = token.split('');
+
+ let pairs = get_pairs(word);
+
+ if (!pairs) {
+ return token
+ }
+
+ while (true) {
+ const minPairs = {};
+ Array.from(pairs).map(pair => {
+ const rank = bpe_ranks[pair];
+ minPairs[(isNaN(rank) ? 10e10 : rank)] = pair;
+ });
+
+
+
+ const bigram = minPairs[Math.min(...Object.keys(minPairs).map(x => {
+ return parseInt(x)
+ }
+ ))];
+
+ if (!(bigram in bpe_ranks)) {
+ break
+ }
+
+ const first = bigram[0];
+ const second = bigram[1];
+ let new_word = [];
+ let i = 0;
+
+ while (i < word.length) {
+ const j = word.indexOf(first, i);
+ if (j === -1) {
+ new_word = new_word.concat(word.slice(i));
+ break
+ }
+ new_word = new_word.concat(word.slice(i, j));
+ i = j;
+
+ if (word[i] === first && i < word.length - 1 && word[i + 1] === second) {
+ new_word.push(first + second);
+ i = i + 2;
+ } else {
+ new_word.push(word[i]);
+ i = i + 1;
+ }
+ }
+
+ word = new_word;
+ if (word.length === 1) {
+ break
+ } else {
+ pairs = get_pairs(word);
+ }
+ }
+
+ word = word.join(' ');
+ cache.set(token, word);
+
+ return word
+}
+
+function encode$1(text) {
+ let bpe_tokens = [];
+ const matches = Array.from(text.matchAll(pat)).map(x => x[0]);
+ for (let token of matches) {
+ token = encodeStr(token).map(x => {
+ return byte_encoder[x]
+ }).join('');
+
+ const new_tokens = bpe(token).split(' ').map(x => encoder[x]);
+ bpe_tokens = bpe_tokens.concat(new_tokens);
+ }
+ return bpe_tokens
+}
+
+function decode$1(tokens) {
+ let text = tokens.map(x => decoder[x]).join('');
+ text = decodeStr(text.split('').map(x => byte_decoder[x]));
+ return text
+}
+
+var Encoder = {
+ encode: encode$1,
+ decode: decode$1
+};
+
+const { encode, decode } = Encoder;
+
+var gpt3Encoder = {
+ encode,
+ decode,
+};
+
+var jsonBuffer = {};
+
+//TODO: handle reviver/dehydrate function like normal
+//and handle indentation, like normal.
+//if anyone needs this... please send pull request.
+
+jsonBuffer.stringify = function stringify (o) {
+ if('undefined' == typeof o) return o
+
+ if(o && Buffer.isBuffer(o))
+ return JSON.stringify(':base64:' + o.toString('base64'))
+
+ if(o && o.toJSON)
+ o = o.toJSON();
+
+ if(o && 'object' === typeof o) {
+ var s = '';
+ var array = Array.isArray(o);
+ s = array ? '[' : '{';
+ var first = true;
+
+ for(var k in o) {
+ var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]);
+ if(Object.hasOwnProperty.call(o, k) && !ignore) {
+ if(!first)
+ s += ',';
+ first = false;
+ if (array) {
+ if(o[k] == undefined)
+ s += 'null';
+ else
+ s += stringify(o[k]);
+ } else if (o[k] !== void(0)) {
+ s += stringify(k) + ':' + stringify(o[k]);
+ }
+ }
+ }
+
+ s += array ? ']' : '}';
+
+ return s
+ } else if ('string' === typeof o) {
+ return JSON.stringify(/^:/.test(o) ? ':' + o : o)
+ } else if ('undefined' === typeof o) {
+ return 'null';
+ } else
+ return JSON.stringify(o)
+};
+
+jsonBuffer.parse = function (s) {
+ return JSON.parse(s, function (key, value) {
+ if('string' === typeof value) {
+ if(/^:base64:/.test(value))
+ return Buffer.from(value.substring(8), 'base64')
+ else
+ return /^:/.test(value) ? value.substring(1) : value
+ }
+ return value
+ })
+};
+
+const EventEmitter = require$$0$f;
+const JSONB = jsonBuffer;
+
+const loadStore = options => {
+ const adapters = {
+ redis: '@keyv/redis',
+ rediss: '@keyv/redis',
+ mongodb: '@keyv/mongo',
+ mongo: '@keyv/mongo',
+ sqlite: '@keyv/sqlite',
+ postgresql: '@keyv/postgres',
+ postgres: '@keyv/postgres',
+ mysql: '@keyv/mysql',
+ etcd: '@keyv/etcd',
+ offline: '@keyv/offline',
+ tiered: '@keyv/tiered',
+ };
+ if (options.adapter || options.uri) {
+ const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0];
+ return new (commonjsRequire(adapters[adapter]))(options);
+ }
+
+ return new Map();
+};
+
+const iterableAdapters = [
+ 'sqlite',
+ 'postgres',
+ 'mysql',
+ 'mongo',
+ 'redis',
+ 'tiered',
+];
+
+class Keyv extends EventEmitter {
+ constructor(uri, {emitErrors = true, ...options} = {}) {
+ super();
+ this.opts = {
+ namespace: 'keyv',
+ serialize: JSONB.stringify,
+ deserialize: JSONB.parse,
+ ...((typeof uri === 'string') ? {uri} : uri),
+ ...options,
+ };
+
+ if (!this.opts.store) {
+ const adapterOptions = {...this.opts};
+ this.opts.store = loadStore(adapterOptions);
+ }
+
+ if (this.opts.compression) {
+ const compression = this.opts.compression;
+ this.opts.serialize = compression.serialize.bind(compression);
+ this.opts.deserialize = compression.deserialize.bind(compression);
+ }
+
+ if (typeof this.opts.store.on === 'function' && emitErrors) {
+ this.opts.store.on('error', error => this.emit('error', error));
+ }
+
+ this.opts.store.namespace = this.opts.namespace;
+
+ const generateIterator = iterator => async function * () {
+ for await (const [key, raw] of typeof iterator === 'function'
+ ? iterator(this.opts.store.namespace)
+ : iterator) {
+ const data = this.opts.deserialize(raw);
+ if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) {
+ continue;
+ }
+
+ if (typeof data.expires === 'number' && Date.now() > data.expires) {
+ this.delete(key);
+ continue;
+ }
+
+ yield [this._getKeyUnprefix(key), data.value];
+ }
+ };
+
+ // Attach iterators
+ if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) {
+ this.iterator = generateIterator(this.opts.store);
+ } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts
+ && this._checkIterableAdaptar()) {
+ this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store));
+ }
+ }
+
+ _checkIterableAdaptar() {
+ return iterableAdapters.includes(this.opts.store.opts.dialect)
+ || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0;
+ }
+
+ _getKeyPrefix(key) {
+ return `${this.opts.namespace}:${key}`;
+ }
+
+ _getKeyPrefixArray(keys) {
+ return keys.map(key => `${this.opts.namespace}:${key}`);
+ }
+
+ _getKeyUnprefix(key) {
+ return key
+ .split(':')
+ .splice(1)
+ .join(':');
+ }
+
+ get(key, options) {
+ const {store} = this.opts;
+ const isArray = Array.isArray(key);
+ const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);
+ if (isArray && store.getMany === undefined) {
+ const promises = [];
+ for (const key of keyPrefixed) {
+ promises.push(Promise.resolve()
+ .then(() => store.get(key))
+ .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data))
+ .then(data => {
+ if (data === undefined || data === null) {
+ return undefined;
+ }
+
+ if (typeof data.expires === 'number' && Date.now() > data.expires) {
+ return this.delete(key).then(() => undefined);
+ }
+
+ return (options && options.raw) ? data : data.value;
+ }),
+ );
+ }
+
+ return Promise.allSettled(promises)
+ .then(values => {
+ const data = [];
+ for (const value of values) {
+ data.push(value.value);
+ }
+
+ return data;
+ });
+ }
+
+ return Promise.resolve()
+ .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed))
+ .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data))
+ .then(data => {
+ if (data === undefined || data === null) {
+ return undefined;
+ }
+
+ if (isArray) {
+ const result = [];
+
+ for (let row of data) {
+ if ((typeof row === 'string')) {
+ row = this.opts.deserialize(row);
+ }
+
+ if (row === undefined || row === null) {
+ result.push(undefined);
+ continue;
+ }
+
+ if (typeof row.expires === 'number' && Date.now() > row.expires) {
+ this.delete(key).then(() => undefined);
+ result.push(undefined);
+ } else {
+ result.push((options && options.raw) ? row : row.value);
+ }
+ }
+
+ return result;
+ }
+
+ if (typeof data.expires === 'number' && Date.now() > data.expires) {
+ return this.delete(key).then(() => undefined);
+ }
+
+ return (options && options.raw) ? data : data.value;
+ });
+ }
+
+ set(key, value, ttl) {
+ const keyPrefixed = this._getKeyPrefix(key);
+ if (typeof ttl === 'undefined') {
+ ttl = this.opts.ttl;
+ }
+
+ if (ttl === 0) {
+ ttl = undefined;
+ }
+
+ const {store} = this.opts;
+
+ return Promise.resolve()
+ .then(() => {
+ const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null;
+ if (typeof value === 'symbol') {
+ this.emit('error', 'symbol cannot be serialized');
+ }
+
+ value = {value, expires};
+ return this.opts.serialize(value);
+ })
+ .then(value => store.set(keyPrefixed, value, ttl))
+ .then(() => true);
+ }
+
+ delete(key) {
+ const {store} = this.opts;
+ if (Array.isArray(key)) {
+ const keyPrefixed = this._getKeyPrefixArray(key);
+ if (store.deleteMany === undefined) {
+ const promises = [];
+ for (const key of keyPrefixed) {
+ promises.push(store.delete(key));
+ }
+
+ return Promise.allSettled(promises)
+ .then(values => values.every(x => x.value === true));
+ }
+
+ return Promise.resolve()
+ .then(() => store.deleteMany(keyPrefixed));
+ }
+
+ const keyPrefixed = this._getKeyPrefix(key);
+ return Promise.resolve()
+ .then(() => store.delete(keyPrefixed));
+ }
+
+ clear() {
+ const {store} = this.opts;
+ return Promise.resolve()
+ .then(() => store.clear());
+ }
+
+ has(key) {
+ const keyPrefixed = this._getKeyPrefix(key);
+ const {store} = this.opts;
+ return Promise.resolve()
+ .then(async () => {
+ if (typeof store.has === 'function') {
+ return store.has(keyPrefixed);
+ }
+
+ const value = await store.get(keyPrefixed);
+ return value !== undefined;
+ });
+ }
+
+ disconnect() {
+ const {store} = this.opts;
+ if (typeof store.disconnect === 'function') {
+ return store.disconnect();
+ }
+ }
+}
+
+var src = Keyv;
+
+class TimeoutError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = 'TimeoutError';
+ }
+}
+
+/**
+An error to be thrown when the request is aborted by AbortController.
+DOMException is thrown instead of this Error when DOMException is available.
+*/
+class AbortError extends Error {
+ constructor(message) {
+ super();
+ this.name = 'AbortError';
+ this.message = message;
+ }
+}
+
+/**
+TODO: Remove AbortError and just throw DOMException when targeting Node 18.
+*/
+const getDOMException = errorMessage => globalThis.DOMException === undefined
+ ? new AbortError(errorMessage)
+ : new DOMException(errorMessage);
+
+/**
+TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
+*/
+const getAbortedReason = signal => {
+ const reason = signal.reason === undefined
+ ? getDOMException('This operation was aborted.')
+ : signal.reason;
+
+ return reason instanceof Error ? reason : getDOMException(reason);
+};
+
+function pTimeout(promise, options) {
+ const {
+ milliseconds,
+ fallback,
+ message,
+ customTimers = {setTimeout, clearTimeout},
+ } = options;
+
+ let timer;
+
+ const cancelablePromise = new Promise((resolve, reject) => {
+ if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
+ throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
+ }
+
+ if (milliseconds === Number.POSITIVE_INFINITY) {
+ resolve(promise);
+ return;
+ }
+
+ if (options.signal) {
+ const {signal} = options;
+ if (signal.aborted) {
+ reject(getAbortedReason(signal));
+ }
+
+ signal.addEventListener('abort', () => {
+ reject(getAbortedReason(signal));
+ });
+ }
+
+ timer = customTimers.setTimeout.call(undefined, () => {
+ if (fallback) {
+ try {
+ resolve(fallback());
+ } catch (error) {
+ reject(error);
+ }
+
+ return;
+ }
+
+ if (typeof promise.cancel === 'function') {
+ promise.cancel();
+ }
+
+ if (message === false) {
+ resolve();
+ } else if (message instanceof Error) {
+ reject(message);
+ } else {
+ const errorMessage = message ?? `Promise timed out after ${milliseconds} milliseconds`;
+ reject(new TimeoutError(errorMessage));
+ }
+ }, milliseconds);
+
+ (async () => {
+ try {
+ resolve(await promise);
+ } catch (error) {
+ reject(error);
+ } finally {
+ customTimers.clearTimeout.call(undefined, timer);
+ }
+ })();
+ });
+
+ cancelablePromise.clear = () => {
+ customTimers.clearTimeout.call(undefined, timer);
+ timer = undefined;
+ };
+
+ return cancelablePromise;
+}
+
+class QuickLRU extends Map {
+ constructor(options = {}) {
+ super();
+
+ if (!(options.maxSize && options.maxSize > 0)) {
+ throw new TypeError('`maxSize` must be a number greater than 0');
+ }
+
+ if (typeof options.maxAge === 'number' && options.maxAge === 0) {
+ throw new TypeError('`maxAge` must be a number greater than 0');
+ }
+
+ // TODO: Use private class fields when ESLint supports them.
+ this.maxSize = options.maxSize;
+ this.maxAge = options.maxAge || Number.POSITIVE_INFINITY;
+ this.onEviction = options.onEviction;
+ this.cache = new Map();
+ this.oldCache = new Map();
+ this._size = 0;
+ }
+
+ // TODO: Use private class methods when targeting Node.js 16.
+ _emitEvictions(cache) {
+ if (typeof this.onEviction !== 'function') {
+ return;
+ }
+
+ for (const [key, item] of cache) {
+ this.onEviction(key, item.value);
+ }
+ }
+
+ _deleteIfExpired(key, item) {
+ if (typeof item.expiry === 'number' && item.expiry <= Date.now()) {
+ if (typeof this.onEviction === 'function') {
+ this.onEviction(key, item.value);
+ }
+
+ return this.delete(key);
+ }
+
+ return false;
+ }
+
+ _getOrDeleteIfExpired(key, item) {
+ const deleted = this._deleteIfExpired(key, item);
+ if (deleted === false) {
+ return item.value;
+ }
+ }
+
+ _getItemValue(key, item) {
+ return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
+ }
+
+ _peek(key, cache) {
+ const item = cache.get(key);
+
+ return this._getItemValue(key, item);
+ }
+
+ _set(key, value) {
+ this.cache.set(key, value);
+ this._size++;
+
+ if (this._size >= this.maxSize) {
+ this._size = 0;
+ this._emitEvictions(this.oldCache);
+ this.oldCache = this.cache;
+ this.cache = new Map();
+ }
+ }
+
+ _moveToRecent(key, item) {
+ this.oldCache.delete(key);
+ this._set(key, item);
+ }
+
+ * _entriesAscending() {
+ for (const item of this.oldCache) {
+ const [key, value] = item;
+ if (!this.cache.has(key)) {
+ const deleted = this._deleteIfExpired(key, value);
+ if (deleted === false) {
+ yield item;
+ }
+ }
+ }
+
+ for (const item of this.cache) {
+ const [key, value] = item;
+ const deleted = this._deleteIfExpired(key, value);
+ if (deleted === false) {
+ yield item;
+ }
+ }
+ }
+
+ get(key) {
+ if (this.cache.has(key)) {
+ const item = this.cache.get(key);
+
+ return this._getItemValue(key, item);
+ }
+
+ if (this.oldCache.has(key)) {
+ const item = this.oldCache.get(key);
+ if (this._deleteIfExpired(key, item) === false) {
+ this._moveToRecent(key, item);
+ return item.value;
+ }
+ }
+ }
+
+ set(key, value, {maxAge = this.maxAge} = {}) {
+ const expiry =
+ typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?
+ Date.now() + maxAge :
+ undefined;
+ if (this.cache.has(key)) {
+ this.cache.set(key, {
+ value,
+ expiry
+ });
+ } else {
+ this._set(key, {value, expiry});
+ }
+ }
+
+ has(key) {
+ if (this.cache.has(key)) {
+ return !this._deleteIfExpired(key, this.cache.get(key));
+ }
+
+ if (this.oldCache.has(key)) {
+ return !this._deleteIfExpired(key, this.oldCache.get(key));
+ }
+
+ return false;
+ }
+
+ peek(key) {
+ if (this.cache.has(key)) {
+ return this._peek(key, this.cache);
+ }
+
+ if (this.oldCache.has(key)) {
+ return this._peek(key, this.oldCache);
+ }
+ }
+
+ delete(key) {
+ const deleted = this.cache.delete(key);
+ if (deleted) {
+ this._size--;
+ }
+
+ return this.oldCache.delete(key) || deleted;
+ }
+
+ clear() {
+ this.cache.clear();
+ this.oldCache.clear();
+ this._size = 0;
+ }
+
+ resize(newSize) {
+ if (!(newSize && newSize > 0)) {
+ throw new TypeError('`maxSize` must be a number greater than 0');
+ }
+
+ const items = [...this._entriesAscending()];
+ const removeCount = items.length - newSize;
+ if (removeCount < 0) {
+ this.cache = new Map(items);
+ this.oldCache = new Map();
+ this._size = items.length;
+ } else {
+ if (removeCount > 0) {
+ this._emitEvictions(items.slice(0, removeCount));
+ }
+
+ this.oldCache = new Map(items.slice(removeCount));
+ this.cache = new Map();
+ this._size = 0;
+ }
+
+ this.maxSize = newSize;
+ }
+
+ * keys() {
+ for (const [key] of this) {
+ yield key;
+ }
+ }
+
+ * values() {
+ for (const [, value] of this) {
+ yield value;
+ }
+ }
+
+ * [Symbol.iterator]() {
+ for (const item of this.cache) {
+ const [key, value] = item;
+ const deleted = this._deleteIfExpired(key, value);
+ if (deleted === false) {
+ yield [key, value.value];
+ }
+ }
+
+ for (const item of this.oldCache) {
+ const [key, value] = item;
+ if (!this.cache.has(key)) {
+ const deleted = this._deleteIfExpired(key, value);
+ if (deleted === false) {
+ yield [key, value.value];
+ }
+ }
+ }
+ }
+
+ * entriesDescending() {
+ let items = [...this.cache];
+ for (let i = items.length - 1; i >= 0; --i) {
+ const item = items[i];
+ const [key, value] = item;
+ const deleted = this._deleteIfExpired(key, value);
+ if (deleted === false) {
+ yield [key, value.value];
+ }
+ }
+
+ items = [...this.oldCache];
+ for (let i = items.length - 1; i >= 0; --i) {
+ const item = items[i];
+ const [key, value] = item;
+ if (!this.cache.has(key)) {
+ const deleted = this._deleteIfExpired(key, value);
+ if (deleted === false) {
+ yield [key, value.value];
+ }
+ }
+ }
+ }
+
+ * entriesAscending() {
+ for (const [key, value] of this._entriesAscending()) {
+ yield [key, value.value];
+ }
+ }
+
+ get size() {
+ if (!this._size) {
+ return this.oldCache.size;
+ }
+
+ let oldCacheSize = 0;
+ for (const key of this.oldCache.keys()) {
+ if (!this.cache.has(key)) {
+ oldCacheSize++;
+ }
+ }
+
+ return Math.min(this._size + oldCacheSize, this.maxSize);
+ }
+
+ entries() {
+ return this.entriesAscending();
+ }
+
+ forEach(callbackFunction, thisArgument = this) {
+ for (const [key, value] of this.entriesAscending()) {
+ callbackFunction.call(thisArgument, value, key, this);
+ }
+ }
+
+ get [Symbol.toStringTag]() {
+ return JSON.stringify([...this.entriesAscending()]);
+ }
+}
+
+// Unique ID creation requires a high quality random # generator. In the browser we therefore
+// require the crypto API and do not support built-in fallback to lower quality random number
+// generators (like Math.random()).
+let getRandomValues;
+const rnds8 = new Uint8Array(16);
+function rng() {
+ // lazy load so that environments that need to polyfill have a chance to do so
+ if (!getRandomValues) {
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
+
+ if (!getRandomValues) {
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
+ }
+ }
+
+ return getRandomValues(rnds8);
+}
+
+/**
+ * Convert array of 16 byte values to UUID string format of the form:
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+ */
+
+const byteToHex = [];
+
+for (let i = 0; i < 256; ++i) {
+ byteToHex.push((i + 0x100).toString(16).slice(1));
+}
+
+function unsafeStringify(arr, offset = 0) {
+ // Note: Be careful editing this code! It's been tuned for performance
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
+}
+
+const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
+var native = {
+ randomUUID
+};
+
+function v4(options, buf, offset) {
+ if (native.randomUUID && !buf && !options) {
+ return native.randomUUID();
+ }
+
+ options = options || {};
+ const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
+ rnds[6] = rnds[6] & 0x0f | 0x40;
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
+
+ if (buf) {
+ offset = offset || 0;
+
+ for (let i = 0; i < 16; ++i) {
+ buf[offset + i] = rnds[i];
+ }
+
+ return buf;
+ }
+
+ return unsafeStringify(rnds);
+}
+
+function createParser(onParse) {
+ let isFirstChunk;
+ let buffer;
+ let startingPosition;
+ let startingFieldLength;
+ let eventId;
+ let eventName;
+ let data;
+ reset();
+ return {
+ feed,
+ reset
+ };
+
+ function reset() {
+ isFirstChunk = true;
+ buffer = "";
+ startingPosition = 0;
+ startingFieldLength = -1;
+ eventId = void 0;
+ eventName = void 0;
+ data = "";
+ }
+
+ function feed(chunk) {
+ buffer = buffer ? buffer + chunk : chunk;
+
+ if (isFirstChunk && hasBom(buffer)) {
+ buffer = buffer.slice(BOM.length);
+ }
+
+ isFirstChunk = false;
+ const length = buffer.length;
+ let position = 0;
+ let discardTrailingNewline = false;
+
+ while (position < length) {
+ if (discardTrailingNewline) {
+ if (buffer[position] === "\n") {
+ ++position;
+ }
+
+ discardTrailingNewline = false;
+ }
+
+ let lineLength = -1;
+ let fieldLength = startingFieldLength;
+ let character;
+
+ for (let index = startingPosition; lineLength < 0 && index < length; ++index) {
+ character = buffer[index];
+
+ if (character === ":" && fieldLength < 0) {
+ fieldLength = index - position;
+ } else if (character === "\r") {
+ discardTrailingNewline = true;
+ lineLength = index - position;
+ } else if (character === "\n") {
+ lineLength = index - position;
+ }
+ }
+
+ if (lineLength < 0) {
+ startingPosition = length - position;
+ startingFieldLength = fieldLength;
+ break;
+ } else {
+ startingPosition = 0;
+ startingFieldLength = -1;
+ }
+
+ parseEventStreamLine(buffer, position, fieldLength, lineLength);
+ position += lineLength + 1;
+ }
+
+ if (position === length) {
+ buffer = "";
+ } else if (position > 0) {
+ buffer = buffer.slice(position);
+ }
+ }
+
+ function parseEventStreamLine(lineBuffer, index, fieldLength, lineLength) {
+ if (lineLength === 0) {
+ if (data.length > 0) {
+ onParse({
+ type: "event",
+ id: eventId,
+ event: eventName || void 0,
+ data: data.slice(0, -1)
+ });
+ data = "";
+ eventId = void 0;
+ }
+
+ eventName = void 0;
+ return;
+ }
+
+ const noValue = fieldLength < 0;
+ const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength));
+ let step = 0;
+
+ if (noValue) {
+ step = lineLength;
+ } else if (lineBuffer[index + fieldLength + 1] === " ") {
+ step = fieldLength + 2;
+ } else {
+ step = fieldLength + 1;
+ }
+
+ const position = index + step;
+ const valueLength = lineLength - step;
+ const value = lineBuffer.slice(position, position + valueLength).toString();
+
+ if (field === "data") {
+ data += value ? "".concat(value, "\n") : "\n";
+ } else if (field === "event") {
+ eventName = value;
+ } else if (field === "id" && !value.includes("\0")) {
+ eventId = value;
+ } else if (field === "retry") {
+ const retry = parseInt(value, 10);
+
+ if (!Number.isNaN(retry)) {
+ onParse({
+ type: "reconnect-interval",
+ value: retry
+ });
+ }
+ }
+ }
+}
+
+const BOM = [239, 187, 191];
+
+function hasBom(buffer) {
+ return BOM.every((charCode, index) => buffer.charCodeAt(index) === charCode);
+}
+
+// src/chatgpt-api.ts
+
+// src/types.ts
+var ChatGPTError = class extends Error {
+};
+
+// src/fetch.ts
+var fetch = globalThis.fetch;
+if (typeof fetch !== "function") {
+ throw new Error("Invalid environment: global fetch not defined");
+}
+
+// src/stream-async-iterable.ts
+async function* streamAsyncIterable(stream) {
+ const reader = stream.getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ return;
+ }
+ yield value;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+// src/fetch-sse.ts
+async function fetchSSE(url, options) {
+ const { onMessage, ...fetchOptions } = options;
+ const res = await fetch(url, fetchOptions);
+ if (!res.ok) {
+ const msg = `ChatGPT error ${res.status || res.statusText}`;
+ const error = new ChatGPTError(msg, { cause: res });
+ error.statusCode = res.status;
+ error.statusText = res.statusText;
+ throw error;
+ }
+ const parser = createParser((event) => {
+ if (event.type === "event") {
+ onMessage(event.data);
+ }
+ });
+ if (!res.body.getReader) {
+ const body = res.body;
+ if (!body.on || !body.read) {
+ throw new ChatGPTError('unsupported "fetch" implementation');
+ }
+ body.on("readable", () => {
+ let chunk;
+ while (null !== (chunk = body.read())) {
+ parser.feed(chunk.toString());
+ }
+ });
+ } else {
+ for await (const chunk of streamAsyncIterable(res.body)) {
+ const str = new TextDecoder().decode(chunk);
+ parser.feed(str);
+ }
+ }
+}
+
+// src/chatgpt-api.ts
+var CHATGPT_MODEL = "text-davinci-003";
+var USER_LABEL_DEFAULT = "User";
+var ASSISTANT_LABEL_DEFAULT = "ChatGPT";
+var ChatGPTAPI = class {
+ constructor(opts) {
+ const {
+ apiKey,
+ apiBaseUrl = "https://api.openai.com",
+ debug = false,
+ messageStore,
+ completionParams,
+ maxModelTokens = 4096,
+ maxResponseTokens = 1e3,
+ userLabel = USER_LABEL_DEFAULT,
+ assistantLabel = ASSISTANT_LABEL_DEFAULT,
+ getMessageById = this._defaultGetMessageById,
+ upsertMessage = this._defaultUpsertMessage
+ } = opts;
+ this._apiKey = apiKey;
+ this._apiBaseUrl = apiBaseUrl;
+ this._debug = !!debug;
+ this._completionParams = {
+ model: CHATGPT_MODEL,
+ temperature: 0.7,
+ presence_penalty: 0.6,
+ stop: ["<|im_end|>"],
+ ...completionParams
+ };
+ this._maxModelTokens = maxModelTokens;
+ this._maxResponseTokens = maxResponseTokens;
+ this._userLabel = userLabel;
+ this._assistantLabel = assistantLabel;
+ this._getMessageById = getMessageById;
+ this._upsertMessage = upsertMessage;
+ if (messageStore) {
+ this._messageStore = messageStore;
+ } else {
+ this._messageStore = new src({
+ store: new QuickLRU({ maxSize: 1e4 })
+ });
+ }
+ if (!this._apiKey) {
+ throw new Error("ChatGPT invalid apiKey");
+ }
+ }
+ async sendMessage(text, opts = {}) {
+ const {
+ conversationId = v4(),
+ parentMessageId,
+ messageId = v4(),
+ timeoutMs,
+ onProgress,
+ stream = onProgress ? true : false
+ } = opts;
+ let { abortSignal } = opts;
+ let abortController = null;
+ if (timeoutMs && !abortSignal) {
+ abortController = new AbortController();
+ abortSignal = abortController.signal;
+ }
+ const message = {
+ role: "user",
+ id: messageId,
+ parentMessageId,
+ conversationId,
+ text
+ };
+ await this._upsertMessage(message);
+ const { prompt, maxTokens } = await this._buildPrompt(text, opts);
+ const result = {
+ role: "assistant",
+ id: v4(),
+ parentMessageId: messageId,
+ conversationId,
+ text: ""
+ };
+ const responseP = new Promise(
+ async (resolve, reject) => {
+ const url = `${this._apiBaseUrl}/v1/completions`;
+ const headers = {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${this._apiKey}`
+ };
+ const body = {
+ max_tokens: maxTokens,
+ ...this._completionParams,
+ prompt,
+ stream
+ };
+ if (this._debug) {
+ const numTokens = await this._getTokenCount(body.prompt);
+ console.log(`sendMessage (${numTokens} tokens)`, body);
+ }
+ if (stream) {
+ fetchSSE(url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ signal: abortSignal,
+ onMessage: (data) => {
+ var _a;
+ if (data === "[DONE]") {
+ result.text = result.text.trim();
+ return resolve(result);
+ }
+ try {
+ const response = JSON.parse(data);
+ if ((response == null ? void 0 : response.id) && ((_a = response == null ? void 0 : response.choices) == null ? void 0 : _a.length)) {
+ result.id = response.id;
+ result.text += response.choices[0].text;
+ onProgress == null ? void 0 : onProgress(result);
+ }
+ } catch (err) {
+ console.warn("ChatGPT stream SEE event unexpected error", err);
+ return reject(err);
+ }
+ }
+ }).catch(reject);
+ } else {
+ try {
+ const res = await fetch(url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ signal: abortSignal
+ });
+ if (!res.ok) {
+ const reason = await res.text();
+ const msg = `ChatGPT error ${res.status || res.statusText}: ${reason}`;
+ const error = new ChatGPTError(msg, { cause: res });
+ error.statusCode = res.status;
+ error.statusText = res.statusText;
+ return reject(error);
+ }
+ const response = await res.json();
+ if (this._debug) {
+ console.log(response);
+ }
+ result.id = response.id;
+ result.text = response.choices[0].text.trim();
+ return resolve(result);
+ } catch (err) {
+ return reject(err);
+ }
+ }
+ }
+ ).then((message2) => {
+ return this._upsertMessage(message2).then(() => message2);
+ });
+ if (timeoutMs) {
+ if (abortController) {
+ responseP.cancel = () => {
+ abortController.abort();
+ };
+ }
+ return pTimeout(responseP, {
+ milliseconds: timeoutMs,
+ message: "ChatGPT timed out waiting for response"
+ });
+ } else {
+ return responseP;
+ }
+ }
+ async _buildPrompt(message, opts) {
+ const currentDate = new Date().toISOString().split("T")[0];
+ const promptPrefix = opts.promptPrefix || `You are ${this._assistantLabel}, a large language model trained by OpenAI. You answer as concisely as possible for each response (e.g. don\u2019t be verbose). It is very important that you answer as concisely as possible, so please remember this. If you are generating a list, do not have too many items. Keep the number of items short.
+Current date: ${currentDate}
+
+`;
+ const promptSuffix = opts.promptSuffix || `
+
+${this._assistantLabel}:
+`;
+ const maxNumTokens = this._maxModelTokens - this._maxResponseTokens;
+ let { parentMessageId } = opts;
+ let nextPromptBody = `${this._userLabel}:
+
+${message}${this._completionParams.stop[0]}`;
+ let promptBody = "";
+ let prompt;
+ let numTokens;
+ do {
+ const nextPrompt = `${promptPrefix}${nextPromptBody}${promptSuffix}`;
+ const nextNumTokens = await this._getTokenCount(nextPrompt);
+ const isValidPrompt = nextNumTokens <= maxNumTokens;
+ if (prompt && !isValidPrompt) {
+ break;
+ }
+ promptBody = nextPromptBody;
+ prompt = nextPrompt;
+ numTokens = nextNumTokens;
+ if (!isValidPrompt) {
+ break;
+ }
+ if (!parentMessageId) {
+ break;
+ }
+ const parentMessage = await this._getMessageById(parentMessageId);
+ if (!parentMessage) {
+ break;
+ }
+ const parentMessageRole = parentMessage.role || "user";
+ const parentMessageRoleDesc = parentMessageRole === "user" ? this._userLabel : this._assistantLabel;
+ const parentMessageString = `${parentMessageRoleDesc}:
+
+${parentMessage.text}${this._completionParams.stop[0]}
+
+`;
+ nextPromptBody = `${parentMessageString}${promptBody}`;
+ parentMessageId = parentMessage.parentMessageId;
+ } while (true);
+ const maxTokens = Math.max(
+ 1,
+ Math.min(this._maxModelTokens - numTokens, this._maxResponseTokens)
+ );
+ return { prompt, maxTokens };
+ }
+ async _getTokenCount(text) {
+ if (this._completionParams.model === CHATGPT_MODEL) {
+ text = text.replace(/<\|im_end\|>/g, "<|endoftext|>");
+ }
+ return gpt3Encoder.encode(text).length;
+ }
+ async _defaultGetMessageById(id) {
+ return this._messageStore.get(id);
+ }
+ async _defaultUpsertMessage(message) {
+ this._messageStore.set(message.id, message);
+ }
+};
+
+class Chat {
+ chatAPI;
+ constructor(apikey) {
+ this.chatAPI = new ChatGPTAPI({
+ apiKey: apikey
+ });
+ }
+ generatePrompt = (patch) => {
+ return `Bellow is the code patch, please help me do the code review
+ ${patch}
+ `;
+ };
+ codeReview = async (patch) => {
+ if (!patch) {
+ return "";
+ }
+ console.time("code-review cost");
+ const prompt = this.generatePrompt(patch);
+ console.log(prompt);
+ const res = await this.chatAPI.sendMessage(prompt, {
+ promptPrefix: "hi,",
+ promptSuffix: "\nlet's start"
+ });
+ console.timeEnd("code-review cost");
+ return res.text;
+ };
+}
+
+const OPENAI_API_KEY = "OPENAI_API_KEY";
+const MAX_PATCH_COUNT = 4e3;
+const robot = (app) => {
+ const loadChat = async (context) => {
+ const repo = context.repo();
+ const { data } = await context.octokit.request(
+ "GET /repos/{owner}/{repo}/actions/variables/{name}",
+ {
+ owner: repo.owner,
+ repo: repo.repo,
+ name: OPENAI_API_KEY
+ }
+ );
+ if (!data?.value) {
+ return null;
+ }
+ return new Chat(data.value);
+ };
+ app.on(["pull_request.opened", "pull_request.synchronize"], async (context) => {
+ const repo = context.repo();
+ const chat = await loadChat(context);
+ const pull_request = context.payload.pull_request;
+ if (pull_request.state === "closed" || pull_request.locked || pull_request.draft) {
+ return;
+ }
+ const data = await context.octokit.request(
+ `GET /repos/{owner}/{repo}/compare/{basehead}`,
+ {
+ owner: repo.owner,
+ repo: repo.repo,
+ basehead: `${context.payload.pull_request.base.sha}...${context.payload.pull_request.head.sha}`
+ }
+ );
+ let { files: changedFiles, commits } = data.data;
+ if (context.payload.action === "synchronize") {
+ if (commits.length >= 2) {
+ const { data: { files } } = await context.octokit.request(
+ `GET /repos/{owner}/{repo}/compare/{basehead}`,
+ {
+ owner: repo.owner,
+ repo: repo.repo,
+ basehead: `${commits[commits.length - 2].sha}...${commits[commits.length - 1].sha}`
+ }
+ );
+ const filesNames = files?.map((file) => file.filename) || [];
+ changedFiles = changedFiles?.filter((file) => filesNames.includes(file.filename));
+ }
+ }
+ if (!changedFiles?.length) {
+ return;
+ }
+ for (let i = 0; i < changedFiles.length; i++) {
+ const file = changedFiles[i];
+ const patch = file.patch || "";
+ if (!patch || patch.length > MAX_PATCH_COUNT) {
+ continue;
+ }
+ const res = await chat?.codeReview(patch);
+ if (!!res) {
+ await context.octokit.pulls.createReviewComment({
+ repo: repo.repo,
+ owner: repo.owner,
+ pull_number: context.pullRequest().pull_number,
+ commit_id: commits[commits.length - 1].sha,
+ path: file.filename,
+ body: res,
+ position: patch.split("\n").length - 1
+ });
+ }
+ }
+ });
+};
+
+adapterGithubActions.run(robot);
+
+exports.File = File;
+exports.FormData = FormData;
diff --git a/ChatGPT-CodeReview/action/index.cjs b/ChatGPT-CodeReview/action/index.cjs
new file mode 100644
index 0000000..c394166
--- /dev/null
+++ b/ChatGPT-CodeReview/action/index.cjs
@@ -0,0 +1,167802 @@
+/******/ (() => { // webpackBootstrap
+/******/ var __webpack_modules__ = ({
+
+/***/ 87351:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.issue = exports.issueCommand = void 0;
+const os = __importStar(__nccwpck_require__(22037));
+const utils_1 = __nccwpck_require__(5278);
+/**
+ * Commands
+ *
+ * Command Format:
+ * ::name key=value,key=value::message
+ *
+ * Examples:
+ * ::warning::This is the message
+ * ::set-env name=MY_VAR::some value
+ */
+function issueCommand(command, properties, message) {
+ const cmd = new Command(command, properties, message);
+ process.stdout.write(cmd.toString() + os.EOL);
+}
+exports.issueCommand = issueCommand;
+function issue(name, message = '') {
+ issueCommand(name, {}, message);
+}
+exports.issue = issue;
+const CMD_STRING = '::';
+class Command {
+ constructor(command, properties, message) {
+ if (!command) {
+ command = 'missing.command';
+ }
+ this.command = command;
+ this.properties = properties;
+ this.message = message;
+ }
+ toString() {
+ let cmdStr = CMD_STRING + this.command;
+ if (this.properties && Object.keys(this.properties).length > 0) {
+ cmdStr += ' ';
+ let first = true;
+ for (const key in this.properties) {
+ if (this.properties.hasOwnProperty(key)) {
+ const val = this.properties[key];
+ if (val) {
+ if (first) {
+ first = false;
+ }
+ else {
+ cmdStr += ',';
+ }
+ cmdStr += `${key}=${escapeProperty(val)}`;
+ }
+ }
+ }
+ }
+ cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
+ return cmdStr;
+ }
+}
+function escapeData(s) {
+ return utils_1.toCommandValue(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A');
+}
+function escapeProperty(s) {
+ return utils_1.toCommandValue(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A')
+ .replace(/:/g, '%3A')
+ .replace(/,/g, '%2C');
+}
+//# sourceMappingURL=command.js.map
+
+/***/ }),
+
+/***/ 42186:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;
+const command_1 = __nccwpck_require__(87351);
+const file_command_1 = __nccwpck_require__(717);
+const utils_1 = __nccwpck_require__(5278);
+const os = __importStar(__nccwpck_require__(22037));
+const path = __importStar(__nccwpck_require__(71017));
+const oidc_utils_1 = __nccwpck_require__(98041);
+/**
+ * The code to exit an action
+ */
+var ExitCode;
+(function (ExitCode) {
+ /**
+ * A code indicating that the action was successful
+ */
+ ExitCode[ExitCode["Success"] = 0] = "Success";
+ /**
+ * A code indicating that the action was a failure
+ */
+ ExitCode[ExitCode["Failure"] = 1] = "Failure";
+})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
+//-----------------------------------------------------------------------
+// Variables
+//-----------------------------------------------------------------------
+/**
+ * Sets env variable for this action and future actions in the job
+ * @param name the name of the variable to set
+ * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function exportVariable(name, val) {
+ const convertedVal = utils_1.toCommandValue(val);
+ process.env[name] = convertedVal;
+ const filePath = process.env['GITHUB_ENV'] || '';
+ if (filePath) {
+ return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val));
+ }
+ command_1.issueCommand('set-env', { name }, convertedVal);
+}
+exports.exportVariable = exportVariable;
+/**
+ * Registers a secret which will get masked from logs
+ * @param secret value of the secret
+ */
+function setSecret(secret) {
+ command_1.issueCommand('add-mask', {}, secret);
+}
+exports.setSecret = setSecret;
+/**
+ * Prepends inputPath to the PATH (for this action and future actions)
+ * @param inputPath
+ */
+function addPath(inputPath) {
+ const filePath = process.env['GITHUB_PATH'] || '';
+ if (filePath) {
+ file_command_1.issueFileCommand('PATH', inputPath);
+ }
+ else {
+ command_1.issueCommand('add-path', {}, inputPath);
+ }
+ process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
+}
+exports.addPath = addPath;
+/**
+ * Gets the value of an input.
+ * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
+ * Returns an empty string if the value is not defined.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string
+ */
+function getInput(name, options) {
+ const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
+ if (options && options.required && !val) {
+ throw new Error(`Input required and not supplied: ${name}`);
+ }
+ if (options && options.trimWhitespace === false) {
+ return val;
+ }
+ return val.trim();
+}
+exports.getInput = getInput;
+/**
+ * Gets the values of an multiline input. Each value is also trimmed.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string[]
+ *
+ */
+function getMultilineInput(name, options) {
+ const inputs = getInput(name, options)
+ .split('\n')
+ .filter(x => x !== '');
+ if (options && options.trimWhitespace === false) {
+ return inputs;
+ }
+ return inputs.map(input => input.trim());
+}
+exports.getMultilineInput = getMultilineInput;
+/**
+ * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
+ * Support boolean input list: `true | True | TRUE | false | False | FALSE` .
+ * The return value is also in boolean type.
+ * ref: https://yaml.org/spec/1.2/spec.html#id2804923
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns boolean
+ */
+function getBooleanInput(name, options) {
+ const trueValue = ['true', 'True', 'TRUE'];
+ const falseValue = ['false', 'False', 'FALSE'];
+ const val = getInput(name, options);
+ if (trueValue.includes(val))
+ return true;
+ if (falseValue.includes(val))
+ return false;
+ throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
+ `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
+}
+exports.getBooleanInput = getBooleanInput;
+/**
+ * Sets the value of an output.
+ *
+ * @param name name of the output to set
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function setOutput(name, value) {
+ const filePath = process.env['GITHUB_OUTPUT'] || '';
+ if (filePath) {
+ return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value));
+ }
+ process.stdout.write(os.EOL);
+ command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value));
+}
+exports.setOutput = setOutput;
+/**
+ * Enables or disables the echoing of commands into stdout for the rest of the step.
+ * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
+ *
+ */
+function setCommandEcho(enabled) {
+ command_1.issue('echo', enabled ? 'on' : 'off');
+}
+exports.setCommandEcho = setCommandEcho;
+//-----------------------------------------------------------------------
+// Results
+//-----------------------------------------------------------------------
+/**
+ * Sets the action status to failed.
+ * When the action exits it will be with an exit code of 1
+ * @param message add error issue message
+ */
+function setFailed(message) {
+ process.exitCode = ExitCode.Failure;
+ error(message);
+}
+exports.setFailed = setFailed;
+//-----------------------------------------------------------------------
+// Logging Commands
+//-----------------------------------------------------------------------
+/**
+ * Gets whether Actions Step Debug is on or not
+ */
+function isDebug() {
+ return process.env['RUNNER_DEBUG'] === '1';
+}
+exports.isDebug = isDebug;
+/**
+ * Writes debug message to user log
+ * @param message debug message
+ */
+function debug(message) {
+ command_1.issueCommand('debug', {}, message);
+}
+exports.debug = debug;
+/**
+ * Adds an error issue
+ * @param message error issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function error(message, properties = {}) {
+ command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+}
+exports.error = error;
+/**
+ * Adds a warning issue
+ * @param message warning issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function warning(message, properties = {}) {
+ command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+}
+exports.warning = warning;
+/**
+ * Adds a notice issue
+ * @param message notice issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function notice(message, properties = {}) {
+ command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+}
+exports.notice = notice;
+/**
+ * Writes info to log with console.log.
+ * @param message info message
+ */
+function info(message) {
+ process.stdout.write(message + os.EOL);
+}
+exports.info = info;
+/**
+ * Begin an output group.
+ *
+ * Output until the next `groupEnd` will be foldable in this group
+ *
+ * @param name The name of the output group
+ */
+function startGroup(name) {
+ command_1.issue('group', name);
+}
+exports.startGroup = startGroup;
+/**
+ * End an output group.
+ */
+function endGroup() {
+ command_1.issue('endgroup');
+}
+exports.endGroup = endGroup;
+/**
+ * Wrap an asynchronous function call in a group.
+ *
+ * Returns the same type as the function itself.
+ *
+ * @param name The name of the group
+ * @param fn The function to wrap in the group
+ */
+function group(name, fn) {
+ return __awaiter(this, void 0, void 0, function* () {
+ startGroup(name);
+ let result;
+ try {
+ result = yield fn();
+ }
+ finally {
+ endGroup();
+ }
+ return result;
+ });
+}
+exports.group = group;
+//-----------------------------------------------------------------------
+// Wrapper action state
+//-----------------------------------------------------------------------
+/**
+ * Saves state for current action, the state can only be retrieved by this action's post job execution.
+ *
+ * @param name name of the state to store
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function saveState(name, value) {
+ const filePath = process.env['GITHUB_STATE'] || '';
+ if (filePath) {
+ return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value));
+ }
+ command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value));
+}
+exports.saveState = saveState;
+/**
+ * Gets the value of an state set by this action's main execution.
+ *
+ * @param name name of the state to get
+ * @returns string
+ */
+function getState(name) {
+ return process.env[`STATE_${name}`] || '';
+}
+exports.getState = getState;
+function getIDToken(aud) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return yield oidc_utils_1.OidcClient.getIDToken(aud);
+ });
+}
+exports.getIDToken = getIDToken;
+/**
+ * Summary exports
+ */
+var summary_1 = __nccwpck_require__(81327);
+Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } }));
+/**
+ * @deprecated use core.summary
+ */
+var summary_2 = __nccwpck_require__(81327);
+Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } }));
+/**
+ * Path exports
+ */
+var path_utils_1 = __nccwpck_require__(2981);
+Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } }));
+Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } }));
+Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } }));
+//# sourceMappingURL=core.js.map
+
+/***/ }),
+
+/***/ 717:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+// For internal use, subject to change.
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+const fs = __importStar(__nccwpck_require__(57147));
+const os = __importStar(__nccwpck_require__(22037));
+const uuid_1 = __nccwpck_require__(75840);
+const utils_1 = __nccwpck_require__(5278);
+function issueFileCommand(command, message) {
+ const filePath = process.env[`GITHUB_${command}`];
+ if (!filePath) {
+ throw new Error(`Unable to find environment variable for file command ${command}`);
+ }
+ if (!fs.existsSync(filePath)) {
+ throw new Error(`Missing file at path: ${filePath}`);
+ }
+ fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
+ encoding: 'utf8'
+ });
+}
+exports.issueFileCommand = issueFileCommand;
+function prepareKeyValueMessage(key, value) {
+ const delimiter = `ghadelimiter_${uuid_1.v4()}`;
+ const convertedValue = utils_1.toCommandValue(value);
+ // These should realistically never happen, but just in case someone finds a
+ // way to exploit uuid generation let's not allow keys or values that contain
+ // the delimiter.
+ if (key.includes(delimiter)) {
+ throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
+ }
+ if (convertedValue.includes(delimiter)) {
+ throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
+ }
+ return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`;
+}
+exports.prepareKeyValueMessage = prepareKeyValueMessage;
+//# sourceMappingURL=file-command.js.map
+
+/***/ }),
+
+/***/ 98041:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.OidcClient = void 0;
+const http_client_1 = __nccwpck_require__(96255);
+const auth_1 = __nccwpck_require__(35526);
+const core_1 = __nccwpck_require__(42186);
+class OidcClient {
+ static createHttpClient(allowRetry = true, maxRetry = 10) {
+ const requestOptions = {
+ allowRetries: allowRetry,
+ maxRetries: maxRetry
+ };
+ return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions);
+ }
+ static getRequestToken() {
+ const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
+ if (!token) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
+ }
+ return token;
+ }
+ static getIDTokenUrl() {
+ const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
+ if (!runtimeUrl) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
+ }
+ return runtimeUrl;
+ }
+ static getCall(id_token_url) {
+ var _a;
+ return __awaiter(this, void 0, void 0, function* () {
+ const httpclient = OidcClient.createHttpClient();
+ const res = yield httpclient
+ .getJson(id_token_url)
+ .catch(error => {
+ throw new Error(`Failed to get ID Token. \n
+ Error Code : ${error.statusCode}\n
+ Error Message: ${error.result.message}`);
+ });
+ const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
+ if (!id_token) {
+ throw new Error('Response json body do not have ID Token field');
+ }
+ return id_token;
+ });
+ }
+ static getIDToken(audience) {
+ return __awaiter(this, void 0, void 0, function* () {
+ try {
+ // New ID Token is requested from action service
+ let id_token_url = OidcClient.getIDTokenUrl();
+ if (audience) {
+ const encodedAudience = encodeURIComponent(audience);
+ id_token_url = `${id_token_url}&audience=${encodedAudience}`;
+ }
+ core_1.debug(`ID token url is ${id_token_url}`);
+ const id_token = yield OidcClient.getCall(id_token_url);
+ core_1.setSecret(id_token);
+ return id_token;
+ }
+ catch (error) {
+ throw new Error(`Error message: ${error.message}`);
+ }
+ });
+ }
+}
+exports.OidcClient = OidcClient;
+//# sourceMappingURL=oidc-utils.js.map
+
+/***/ }),
+
+/***/ 2981:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
+const path = __importStar(__nccwpck_require__(71017));
+/**
+ * toPosixPath converts the given path to the posix form. On Windows, \\ will be
+ * replaced with /.
+ *
+ * @param pth. Path to transform.
+ * @return string Posix path.
+ */
+function toPosixPath(pth) {
+ return pth.replace(/[\\]/g, '/');
+}
+exports.toPosixPath = toPosixPath;
+/**
+ * toWin32Path converts the given path to the win32 form. On Linux, / will be
+ * replaced with \\.
+ *
+ * @param pth. Path to transform.
+ * @return string Win32 path.
+ */
+function toWin32Path(pth) {
+ return pth.replace(/[/]/g, '\\');
+}
+exports.toWin32Path = toWin32Path;
+/**
+ * toPlatformPath converts the given path to a platform-specific path. It does
+ * this by replacing instances of / and \ with the platform-specific path
+ * separator.
+ *
+ * @param pth The path to platformize.
+ * @return string The platform-specific path.
+ */
+function toPlatformPath(pth) {
+ return pth.replace(/[/\\]/g, path.sep);
+}
+exports.toPlatformPath = toPlatformPath;
+//# sourceMappingURL=path-utils.js.map
+
+/***/ }),
+
+/***/ 81327:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
+const os_1 = __nccwpck_require__(22037);
+const fs_1 = __nccwpck_require__(57147);
+const { access, appendFile, writeFile } = fs_1.promises;
+exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
+exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
+class Summary {
+ constructor() {
+ this._buffer = '';
+ }
+ /**
+ * Finds the summary file path from the environment, rejects if env var is not found or file does not exist
+ * Also checks r/w permissions.
+ *
+ * @returns step summary file path
+ */
+ filePath() {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this._filePath) {
+ return this._filePath;
+ }
+ const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR];
+ if (!pathFromEnv) {
+ throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
+ }
+ try {
+ yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK);
+ }
+ catch (_a) {
+ throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
+ }
+ this._filePath = pathFromEnv;
+ return this._filePath;
+ });
+ }
+ /**
+ * Wraps content in an HTML tag, adding any HTML attributes
+ *
+ * @param {string} tag HTML tag to wrap
+ * @param {string | null} content content within the tag
+ * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
+ *
+ * @returns {string} content wrapped in HTML element
+ */
+ wrap(tag, content, attrs = {}) {
+ const htmlAttrs = Object.entries(attrs)
+ .map(([key, value]) => ` ${key}="${value}"`)
+ .join('');
+ if (!content) {
+ return `<${tag}${htmlAttrs}>`;
+ }
+ return `<${tag}${htmlAttrs}>${content}${tag}>`;
+ }
+ /**
+ * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
+ *
+ * @param {SummaryWriteOptions} [options] (optional) options for write operation
+ *
+ * @returns {Promise} summary instance
+ */
+ write(options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
+ const filePath = yield this.filePath();
+ const writeFunc = overwrite ? writeFile : appendFile;
+ yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
+ return this.emptyBuffer();
+ });
+ }
+ /**
+ * Clears the summary buffer and wipes the summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ clear() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.emptyBuffer().write({ overwrite: true });
+ });
+ }
+ /**
+ * Returns the current summary buffer as a string
+ *
+ * @returns {string} string of summary buffer
+ */
+ stringify() {
+ return this._buffer;
+ }
+ /**
+ * If the summary buffer is empty
+ *
+ * @returns {boolen} true if the buffer is empty
+ */
+ isEmptyBuffer() {
+ return this._buffer.length === 0;
+ }
+ /**
+ * Resets the summary buffer without writing to summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ emptyBuffer() {
+ this._buffer = '';
+ return this;
+ }
+ /**
+ * Adds raw text to the summary buffer
+ *
+ * @param {string} text content to add
+ * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addRaw(text, addEOL = false) {
+ this._buffer += text;
+ return addEOL ? this.addEOL() : this;
+ }
+ /**
+ * Adds the operating system-specific end-of-line marker to the buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addEOL() {
+ return this.addRaw(os_1.EOL);
+ }
+ /**
+ * Adds an HTML codeblock to the summary buffer
+ *
+ * @param {string} code content to render within fenced code block
+ * @param {string} lang (optional) language to syntax highlight code
+ *
+ * @returns {Summary} summary instance
+ */
+ addCodeBlock(code, lang) {
+ const attrs = Object.assign({}, (lang && { lang }));
+ const element = this.wrap('pre', this.wrap('code', code), attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML list to the summary buffer
+ *
+ * @param {string[]} items list of items to render
+ * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addList(items, ordered = false) {
+ const tag = ordered ? 'ol' : 'ul';
+ const listItems = items.map(item => this.wrap('li', item)).join('');
+ const element = this.wrap(tag, listItems);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML table to the summary buffer
+ *
+ * @param {SummaryTableCell[]} rows table rows
+ *
+ * @returns {Summary} summary instance
+ */
+ addTable(rows) {
+ const tableBody = rows
+ .map(row => {
+ const cells = row
+ .map(cell => {
+ if (typeof cell === 'string') {
+ return this.wrap('td', cell);
+ }
+ const { header, data, colspan, rowspan } = cell;
+ const tag = header ? 'th' : 'td';
+ const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
+ return this.wrap(tag, data, attrs);
+ })
+ .join('');
+ return this.wrap('tr', cells);
+ })
+ .join('');
+ const element = this.wrap('table', tableBody);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds a collapsable HTML details element to the summary buffer
+ *
+ * @param {string} label text for the closed state
+ * @param {string} content collapsable content
+ *
+ * @returns {Summary} summary instance
+ */
+ addDetails(label, content) {
+ const element = this.wrap('details', this.wrap('summary', label) + content);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML image tag to the summary buffer
+ *
+ * @param {string} src path to the image you to embed
+ * @param {string} alt text description of the image
+ * @param {SummaryImageOptions} options (optional) addition image attributes
+ *
+ * @returns {Summary} summary instance
+ */
+ addImage(src, alt, options) {
+ const { width, height } = options || {};
+ const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
+ const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML section heading element
+ *
+ * @param {string} text heading text
+ * @param {number | string} [level=1] (optional) the heading level, default: 1
+ *
+ * @returns {Summary} summary instance
+ */
+ addHeading(text, level) {
+ const tag = `h${level}`;
+ const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
+ ? tag
+ : 'h1';
+ const element = this.wrap(allowedTag, text);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML thematic break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addSeparator() {
+ const element = this.wrap('hr', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML line break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addBreak() {
+ const element = this.wrap('br', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML blockquote to the summary buffer
+ *
+ * @param {string} text quote text
+ * @param {string} cite (optional) citation url
+ *
+ * @returns {Summary} summary instance
+ */
+ addQuote(text, cite) {
+ const attrs = Object.assign({}, (cite && { cite }));
+ const element = this.wrap('blockquote', text, attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML anchor tag to the summary buffer
+ *
+ * @param {string} text link text/content
+ * @param {string} href hyperlink
+ *
+ * @returns {Summary} summary instance
+ */
+ addLink(text, href) {
+ const element = this.wrap('a', text, { href });
+ return this.addRaw(element).addEOL();
+ }
+}
+const _summary = new Summary();
+/**
+ * @deprecated use `core.summary`
+ */
+exports.markdownSummary = _summary;
+exports.summary = _summary;
+//# sourceMappingURL=summary.js.map
+
+/***/ }),
+
+/***/ 5278:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toCommandProperties = exports.toCommandValue = void 0;
+/**
+ * Sanitizes an input into a string so it can be passed into issueCommand safely
+ * @param input input to sanitize into a string
+ */
+function toCommandValue(input) {
+ if (input === null || input === undefined) {
+ return '';
+ }
+ else if (typeof input === 'string' || input instanceof String) {
+ return input;
+ }
+ return JSON.stringify(input);
+}
+exports.toCommandValue = toCommandValue;
+/**
+ *
+ * @param annotationProperties
+ * @returns The command properties to send with the actual annotation command
+ * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
+ */
+function toCommandProperties(annotationProperties) {
+ if (!Object.keys(annotationProperties).length) {
+ return {};
+ }
+ return {
+ title: annotationProperties.title,
+ file: annotationProperties.file,
+ line: annotationProperties.startLine,
+ endLine: annotationProperties.endLine,
+ col: annotationProperties.startColumn,
+ endColumn: annotationProperties.endColumn
+ };
+}
+exports.toCommandProperties = toCommandProperties;
+//# sourceMappingURL=utils.js.map
+
+/***/ }),
+
+/***/ 35526:
+/***/ (function(__unused_webpack_module, exports) {
+
+"use strict";
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0;
+class BasicCredentialHandler {
+ constructor(username, password) {
+ this.username = username;
+ this.password = password;
+ }
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
+}
+exports.BasicCredentialHandler = BasicCredentialHandler;
+class BearerCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Bearer ${this.token}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
+}
+exports.BearerCredentialHandler = BearerCredentialHandler;
+class PersonalAccessTokenCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return __awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
+}
+exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
+//# sourceMappingURL=auth.js.map
+
+/***/ }),
+
+/***/ 96255:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
+const http = __importStar(__nccwpck_require__(13685));
+const https = __importStar(__nccwpck_require__(95687));
+const pm = __importStar(__nccwpck_require__(19835));
+const tunnel = __importStar(__nccwpck_require__(74294));
+var HttpCodes;
+(function (HttpCodes) {
+ HttpCodes[HttpCodes["OK"] = 200] = "OK";
+ HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
+ HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
+ HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
+ HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
+ HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
+ HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
+ HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
+ HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+ HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
+ HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
+ HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
+ HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
+ HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
+ HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
+ HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+ HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
+ HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+ HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
+ HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
+ HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
+ HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
+ HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
+ HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
+ HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
+ HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+ HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
+})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
+var Headers;
+(function (Headers) {
+ Headers["Accept"] = "accept";
+ Headers["ContentType"] = "content-type";
+})(Headers = exports.Headers || (exports.Headers = {}));
+var MediaTypes;
+(function (MediaTypes) {
+ MediaTypes["ApplicationJson"] = "application/json";
+})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
+/**
+ * Returns the proxy URL, depending upon the supplied url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+function getProxyUrl(serverUrl) {
+ const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+ return proxyUrl ? proxyUrl.href : '';
+}
+exports.getProxyUrl = getProxyUrl;
+const HttpRedirectCodes = [
+ HttpCodes.MovedPermanently,
+ HttpCodes.ResourceMoved,
+ HttpCodes.SeeOther,
+ HttpCodes.TemporaryRedirect,
+ HttpCodes.PermanentRedirect
+];
+const HttpResponseRetryCodes = [
+ HttpCodes.BadGateway,
+ HttpCodes.ServiceUnavailable,
+ HttpCodes.GatewayTimeout
+];
+const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
+const ExponentialBackoffCeiling = 10;
+const ExponentialBackoffTimeSlice = 5;
+class HttpClientError extends Error {
+ constructor(message, statusCode) {
+ super(message);
+ this.name = 'HttpClientError';
+ this.statusCode = statusCode;
+ Object.setPrototypeOf(this, HttpClientError.prototype);
+ }
+}
+exports.HttpClientError = HttpClientError;
+class HttpClientResponse {
+ constructor(message) {
+ this.message = message;
+ }
+ readBody() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ let output = Buffer.alloc(0);
+ this.message.on('data', (chunk) => {
+ output = Buffer.concat([output, chunk]);
+ });
+ this.message.on('end', () => {
+ resolve(output.toString());
+ });
+ }));
+ });
+ }
+}
+exports.HttpClientResponse = HttpClientResponse;
+function isHttps(requestUrl) {
+ const parsedUrl = new URL(requestUrl);
+ return parsedUrl.protocol === 'https:';
+}
+exports.isHttps = isHttps;
+class HttpClient {
+ constructor(userAgent, handlers, requestOptions) {
+ this._ignoreSslError = false;
+ this._allowRedirects = true;
+ this._allowRedirectDowngrade = false;
+ this._maxRedirects = 50;
+ this._allowRetries = false;
+ this._maxRetries = 1;
+ this._keepAlive = false;
+ this._disposed = false;
+ this.userAgent = userAgent;
+ this.handlers = handlers || [];
+ this.requestOptions = requestOptions;
+ if (requestOptions) {
+ if (requestOptions.ignoreSslError != null) {
+ this._ignoreSslError = requestOptions.ignoreSslError;
+ }
+ this._socketTimeout = requestOptions.socketTimeout;
+ if (requestOptions.allowRedirects != null) {
+ this._allowRedirects = requestOptions.allowRedirects;
+ }
+ if (requestOptions.allowRedirectDowngrade != null) {
+ this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+ }
+ if (requestOptions.maxRedirects != null) {
+ this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+ }
+ if (requestOptions.keepAlive != null) {
+ this._keepAlive = requestOptions.keepAlive;
+ }
+ if (requestOptions.allowRetries != null) {
+ this._allowRetries = requestOptions.allowRetries;
+ }
+ if (requestOptions.maxRetries != null) {
+ this._maxRetries = requestOptions.maxRetries;
+ }
+ }
+ }
+ options(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ get(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('GET', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ del(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('DELETE', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ post(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('POST', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ patch(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PATCH', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ put(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PUT', requestUrl, data, additionalHeaders || {});
+ });
+ }
+ head(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('HEAD', requestUrl, null, additionalHeaders || {});
+ });
+ }
+ sendStream(verb, requestUrl, stream, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request(verb, requestUrl, stream, additionalHeaders);
+ });
+ }
+ /**
+ * Gets a typed object from an endpoint
+ * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
+ */
+ getJson(requestUrl, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ const res = yield this.get(requestUrl, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ postJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.post(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ putJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.put(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ patchJson(requestUrl, obj, additionalHeaders = {}) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
+ const res = yield this.patch(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
+ }
+ /**
+ * Makes a raw http request.
+ * All other methods such as get, post, patch, and request ultimately call this.
+ * Prefer get, del, post and patch
+ */
+ request(verb, requestUrl, data, headers) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this._disposed) {
+ throw new Error('Client has already been disposed.');
+ }
+ const parsedUrl = new URL(requestUrl);
+ let info = this._prepareRequest(verb, parsedUrl, headers);
+ // Only perform retries on reads since writes may not be idempotent.
+ const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
+ ? this._maxRetries + 1
+ : 1;
+ let numTries = 0;
+ let response;
+ do {
+ response = yield this.requestRaw(info, data);
+ // Check if it's an authentication challenge
+ if (response &&
+ response.message &&
+ response.message.statusCode === HttpCodes.Unauthorized) {
+ let authenticationHandler;
+ for (const handler of this.handlers) {
+ if (handler.canHandleAuthentication(response)) {
+ authenticationHandler = handler;
+ break;
+ }
+ }
+ if (authenticationHandler) {
+ return authenticationHandler.handleAuthentication(this, info, data);
+ }
+ else {
+ // We have received an unauthorized response but have no handlers to handle it.
+ // Let the response return to the caller.
+ return response;
+ }
+ }
+ let redirectsRemaining = this._maxRedirects;
+ while (response.message.statusCode &&
+ HttpRedirectCodes.includes(response.message.statusCode) &&
+ this._allowRedirects &&
+ redirectsRemaining > 0) {
+ const redirectUrl = response.message.headers['location'];
+ if (!redirectUrl) {
+ // if there's no location to redirect to, we won't
+ break;
+ }
+ const parsedRedirectUrl = new URL(redirectUrl);
+ if (parsedUrl.protocol === 'https:' &&
+ parsedUrl.protocol !== parsedRedirectUrl.protocol &&
+ !this._allowRedirectDowngrade) {
+ throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
+ }
+ // we need to finish reading the response before reassigning response
+ // which will leak the open socket.
+ yield response.readBody();
+ // strip authorization header if redirected to a different hostname
+ if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+ for (const header in headers) {
+ // header names are case insensitive
+ if (header.toLowerCase() === 'authorization') {
+ delete headers[header];
+ }
+ }
+ }
+ // let's make the request with the new redirectUrl
+ info = this._prepareRequest(verb, parsedRedirectUrl, headers);
+ response = yield this.requestRaw(info, data);
+ redirectsRemaining--;
+ }
+ if (!response.message.statusCode ||
+ !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+ // If not a retry code, return immediately instead of retrying
+ return response;
+ }
+ numTries += 1;
+ if (numTries < maxTries) {
+ yield response.readBody();
+ yield this._performExponentialBackoff(numTries);
+ }
+ } while (numTries < maxTries);
+ return response;
+ });
+ }
+ /**
+ * Needs to be called if keepAlive is set to true in request options.
+ */
+ dispose() {
+ if (this._agent) {
+ this._agent.destroy();
+ }
+ this._disposed = true;
+ }
+ /**
+ * Raw request.
+ * @param info
+ * @param data
+ */
+ requestRaw(info, data) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => {
+ function callbackForResult(err, res) {
+ if (err) {
+ reject(err);
+ }
+ else if (!res) {
+ // If `err` is not passed, then `res` must be passed.
+ reject(new Error('Unknown error'));
+ }
+ else {
+ resolve(res);
+ }
+ }
+ this.requestRawWithCallback(info, data, callbackForResult);
+ });
+ });
+ }
+ /**
+ * Raw request with callback.
+ * @param info
+ * @param data
+ * @param onResult
+ */
+ requestRawWithCallback(info, data, onResult) {
+ if (typeof data === 'string') {
+ if (!info.options.headers) {
+ info.options.headers = {};
+ }
+ info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
+ }
+ let callbackCalled = false;
+ function handleResult(err, res) {
+ if (!callbackCalled) {
+ callbackCalled = true;
+ onResult(err, res);
+ }
+ }
+ const req = info.httpModule.request(info.options, (msg) => {
+ const res = new HttpClientResponse(msg);
+ handleResult(undefined, res);
+ });
+ let socket;
+ req.on('socket', sock => {
+ socket = sock;
+ });
+ // If we ever get disconnected, we want the socket to timeout eventually
+ req.setTimeout(this._socketTimeout || 3 * 60000, () => {
+ if (socket) {
+ socket.end();
+ }
+ handleResult(new Error(`Request timeout: ${info.options.path}`));
+ });
+ req.on('error', function (err) {
+ // err has statusCode property
+ // res should have headers
+ handleResult(err);
+ });
+ if (data && typeof data === 'string') {
+ req.write(data, 'utf8');
+ }
+ if (data && typeof data !== 'string') {
+ data.on('close', function () {
+ req.end();
+ });
+ data.pipe(req);
+ }
+ else {
+ req.end();
+ }
+ }
+ /**
+ * Gets an http agent. This function is useful when you need an http agent that handles
+ * routing through a proxy server - depending upon the url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+ getAgent(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ return this._getAgent(parsedUrl);
+ }
+ _prepareRequest(method, requestUrl, headers) {
+ const info = {};
+ info.parsedUrl = requestUrl;
+ const usingSsl = info.parsedUrl.protocol === 'https:';
+ info.httpModule = usingSsl ? https : http;
+ const defaultPort = usingSsl ? 443 : 80;
+ info.options = {};
+ info.options.host = info.parsedUrl.hostname;
+ info.options.port = info.parsedUrl.port
+ ? parseInt(info.parsedUrl.port)
+ : defaultPort;
+ info.options.path =
+ (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
+ info.options.method = method;
+ info.options.headers = this._mergeHeaders(headers);
+ if (this.userAgent != null) {
+ info.options.headers['user-agent'] = this.userAgent;
+ }
+ info.options.agent = this._getAgent(info.parsedUrl);
+ // gives handlers an opportunity to participate
+ if (this.handlers) {
+ for (const handler of this.handlers) {
+ handler.prepareRequest(info.options);
+ }
+ }
+ return info;
+ }
+ _mergeHeaders(headers) {
+ if (this.requestOptions && this.requestOptions.headers) {
+ return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+ }
+ return lowercaseKeys(headers || {});
+ }
+ _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
+ let clientHeader;
+ if (this.requestOptions && this.requestOptions.headers) {
+ clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
+ }
+ return additionalHeaders[header] || clientHeader || _default;
+ }
+ _getAgent(parsedUrl) {
+ let agent;
+ const proxyUrl = pm.getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (this._keepAlive && useProxy) {
+ agent = this._proxyAgent;
+ }
+ if (this._keepAlive && !useProxy) {
+ agent = this._agent;
+ }
+ // if agent is already assigned use that agent.
+ if (agent) {
+ return agent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ let maxSockets = 100;
+ if (this.requestOptions) {
+ maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
+ }
+ // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
+ if (proxyUrl && proxyUrl.hostname) {
+ const agentOptions = {
+ maxSockets,
+ keepAlive: this._keepAlive,
+ proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
+ proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+ })), { host: proxyUrl.hostname, port: proxyUrl.port })
+ };
+ let tunnelAgent;
+ const overHttps = proxyUrl.protocol === 'https:';
+ if (usingSsl) {
+ tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+ }
+ else {
+ tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+ }
+ agent = tunnelAgent(agentOptions);
+ this._proxyAgent = agent;
+ }
+ // if reusing agent across request and tunneling agent isn't assigned create a new agent
+ if (this._keepAlive && !agent) {
+ const options = { keepAlive: this._keepAlive, maxSockets };
+ agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
+ this._agent = agent;
+ }
+ // if not using private agent and tunnel agent isn't setup then use global agent
+ if (!agent) {
+ agent = usingSsl ? https.globalAgent : http.globalAgent;
+ }
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ agent.options = Object.assign(agent.options || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return agent;
+ }
+ _performExponentialBackoff(retryNumber) {
+ return __awaiter(this, void 0, void 0, function* () {
+ retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+ const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+ return new Promise(resolve => setTimeout(() => resolve(), ms));
+ });
+ }
+ _processResponse(res, options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
+ const statusCode = res.message.statusCode || 0;
+ const response = {
+ statusCode,
+ result: null,
+ headers: {}
+ };
+ // not found leads to null obj returned
+ if (statusCode === HttpCodes.NotFound) {
+ resolve(response);
+ }
+ // get the result from the body
+ function dateTimeDeserializer(key, value) {
+ if (typeof value === 'string') {
+ const a = new Date(value);
+ if (!isNaN(a.valueOf())) {
+ return a;
+ }
+ }
+ return value;
+ }
+ let obj;
+ let contents;
+ try {
+ contents = yield res.readBody();
+ if (contents && contents.length > 0) {
+ if (options && options.deserializeDates) {
+ obj = JSON.parse(contents, dateTimeDeserializer);
+ }
+ else {
+ obj = JSON.parse(contents);
+ }
+ response.result = obj;
+ }
+ response.headers = res.message.headers;
+ }
+ catch (err) {
+ // Invalid resource (contents not json); leaving result obj null
+ }
+ // note that 3xx redirects are handled by the http layer.
+ if (statusCode > 299) {
+ let msg;
+ // if exception/error in body, attempt to get better error
+ if (obj && obj.message) {
+ msg = obj.message;
+ }
+ else if (contents && contents.length > 0) {
+ // it may be the case that the exception is in the body message as string
+ msg = contents;
+ }
+ else {
+ msg = `Failed request: (${statusCode})`;
+ }
+ const err = new HttpClientError(msg, statusCode);
+ err.result = response.result;
+ reject(err);
+ }
+ else {
+ resolve(response);
+ }
+ }));
+ });
+ }
+}
+exports.HttpClient = HttpClient;
+const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 19835:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.checkBypass = exports.getProxyUrl = void 0;
+function getProxyUrl(reqUrl) {
+ const usingSsl = reqUrl.protocol === 'https:';
+ if (checkBypass(reqUrl)) {
+ return undefined;
+ }
+ const proxyVar = (() => {
+ if (usingSsl) {
+ return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
+ }
+ else {
+ return process.env['http_proxy'] || process.env['HTTP_PROXY'];
+ }
+ })();
+ if (proxyVar) {
+ return new URL(proxyVar);
+ }
+ else {
+ return undefined;
+ }
+}
+exports.getProxyUrl = getProxyUrl;
+function checkBypass(reqUrl) {
+ if (!reqUrl.hostname) {
+ return false;
+ }
+ const reqHost = reqUrl.hostname;
+ if (isLoopbackAddress(reqHost)) {
+ return true;
+ }
+ const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
+ if (!noProxy) {
+ return false;
+ }
+ // Determine the request port
+ let reqPort;
+ if (reqUrl.port) {
+ reqPort = Number(reqUrl.port);
+ }
+ else if (reqUrl.protocol === 'http:') {
+ reqPort = 80;
+ }
+ else if (reqUrl.protocol === 'https:') {
+ reqPort = 443;
+ }
+ // Format the request hostname and hostname with port
+ const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+ if (typeof reqPort === 'number') {
+ upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
+ }
+ // Compare request host against noproxy
+ for (const upperNoProxyItem of noProxy
+ .split(',')
+ .map(x => x.trim().toUpperCase())
+ .filter(x => x)) {
+ if (upperNoProxyItem === '*' ||
+ upperReqHosts.some(x => x === upperNoProxyItem ||
+ x.endsWith(`.${upperNoProxyItem}`) ||
+ (upperNoProxyItem.startsWith('.') &&
+ x.endsWith(`${upperNoProxyItem}`)))) {
+ return true;
+ }
+ }
+ return false;
+}
+exports.checkBypass = checkBypass;
+function isLoopbackAddress(host) {
+ const hostLower = host.toLowerCase();
+ return (hostLower === 'localhost' ||
+ hostLower.startsWith('127.') ||
+ hostLower.startsWith('[::1]') ||
+ hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
+}
+//# sourceMappingURL=proxy.js.map
+
+/***/ }),
+
+/***/ 97174:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+
+const internals = {
+ suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/
+};
+
+
+exports.parse = function (text, ...args) {
+
+ // Normalize arguments
+
+ const firstOptions = typeof args[0] === 'object' && args[0];
+ const reviver = args.length > 1 || !firstOptions ? args[0] : undefined;
+ const options = (args.length > 1 && args[1]) || firstOptions || {};
+
+ // Parse normally, allowing exceptions
+
+ const obj = JSON.parse(text, reviver);
+
+ // options.protoAction: 'error' (default) / 'remove' / 'ignore'
+
+ if (options.protoAction === 'ignore') {
+ return obj;
+ }
+
+ // Ignore null and non-objects
+
+ if (!obj ||
+ typeof obj !== 'object') {
+
+ return obj;
+ }
+
+ // Check original string for potential exploit
+
+ if (!text.match(internals.suspectRx)) {
+ return obj;
+ }
+
+ // Scan result for proto keys
+
+ exports.scan(obj, options);
+
+ return obj;
+};
+
+
+exports.scan = function (obj, options = {}) {
+
+ let next = [obj];
+
+ while (next.length) {
+ const nodes = next;
+ next = [];
+
+ for (const node of nodes) {
+ if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly
+ if (options.protoAction !== 'remove') {
+ throw new SyntaxError('Object contains forbidden prototype property');
+ }
+
+ delete node.__proto__;
+ }
+
+ for (const key in node) {
+ const value = node[key];
+ if (value &&
+ typeof value === 'object') {
+
+ next.push(node[key]);
+ }
+ }
+ }
+ }
+};
+
+
+exports.safeParse = function (text, reviver) {
+
+ try {
+ return exports.parse(text, reviver);
+ }
+ catch (ignoreError) {
+ return null;
+ }
+};
+
+
+/***/ }),
+
+/***/ 47541:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var universalUserAgent = __nccwpck_require__(45030);
+var request = __nccwpck_require__(36234);
+var authOauthApp = __nccwpck_require__(58459);
+var deprecation = __nccwpck_require__(58932);
+var universalGithubAppJwt = __nccwpck_require__(84419);
+var LRU = _interopDefault(__nccwpck_require__(7129));
+var authOauthUser = __nccwpck_require__(11591);
+
+async function getAppAuthentication({
+ appId,
+ privateKey,
+ timeDifference
+}) {
+ try {
+ const appAuthentication = await universalGithubAppJwt.githubAppJwt({
+ id: +appId,
+ privateKey,
+ now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference
+ });
+ return {
+ type: "app",
+ token: appAuthentication.token,
+ appId: appAuthentication.appId,
+ expiresAt: new Date(appAuthentication.expiration * 1000).toISOString()
+ };
+ } catch (error) {
+ if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") {
+ throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'");
+ } else {
+ throw error;
+ }
+ }
+}
+
+// https://github.com/isaacs/node-lru-cache#readme
+function getCache() {
+ return new LRU({
+ // cache max. 15000 tokens, that will use less than 10mb memory
+ max: 15000,
+ // Cache for 1 minute less than GitHub expiry
+ maxAge: 1000 * 60 * 59
+ });
+}
+async function get(cache, options) {
+ const cacheKey = optionsToCacheKey(options);
+ const result = await cache.get(cacheKey);
+ if (!result) {
+ return;
+ }
+ const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|");
+ const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => {
+ if (/!$/.test(string)) {
+ permissions[string.slice(0, -1)] = "write";
+ } else {
+ permissions[string] = "read";
+ }
+ return permissions;
+ }, {});
+ return {
+ token,
+ createdAt,
+ expiresAt,
+ permissions,
+ repositoryIds: options.repositoryIds,
+ repositoryNames: options.repositoryNames,
+ singleFileName,
+ repositorySelection: repositorySelection
+ };
+}
+async function set(cache, options, data) {
+ const key = optionsToCacheKey(options);
+ const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(",");
+ const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|");
+ await cache.set(key, value);
+}
+function optionsToCacheKey({
+ installationId,
+ permissions = {},
+ repositoryIds = [],
+ repositoryNames = []
+}) {
+ const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(",");
+ const repositoryIdsString = repositoryIds.sort().join(",");
+ const repositoryNamesString = repositoryNames.join(",");
+ return [installationId, repositoryIdsString, repositoryNamesString, permissionsString].filter(Boolean).join("|");
+}
+
+function toTokenAuthentication({
+ installationId,
+ token,
+ createdAt,
+ expiresAt,
+ repositorySelection,
+ permissions,
+ repositoryIds,
+ repositoryNames,
+ singleFileName
+}) {
+ return Object.assign({
+ type: "token",
+ tokenType: "installation",
+ token,
+ installationId,
+ permissions,
+ createdAt,
+ expiresAt,
+ repositorySelection
+ }, repositoryIds ? {
+ repositoryIds
+ } : null, repositoryNames ? {
+ repositoryNames
+ } : null, singleFileName ? {
+ singleFileName
+ } : null);
+}
+
+async function getInstallationAuthentication(state, options, customRequest) {
+ const installationId = Number(options.installationId || state.installationId);
+ if (!installationId) {
+ throw new Error("[@octokit/auth-app] installationId option is required for installation authentication.");
+ }
+ if (options.factory) {
+ const {
+ type,
+ factory,
+ oauthApp,
+ ...factoryAuthOptions
+ } = {
+ ...state,
+ ...options
+ };
+ // @ts-expect-error if `options.factory` is set, the return type for `auth()` should be `Promise>`
+ return factory(factoryAuthOptions);
+ }
+ const optionsWithInstallationTokenFromState = Object.assign({
+ installationId
+ }, options);
+ if (!options.refresh) {
+ const result = await get(state.cache, optionsWithInstallationTokenFromState);
+ if (result) {
+ const {
+ token,
+ createdAt,
+ expiresAt,
+ permissions,
+ repositoryIds,
+ repositoryNames,
+ singleFileName,
+ repositorySelection
+ } = result;
+ return toTokenAuthentication({
+ installationId,
+ token,
+ createdAt,
+ expiresAt,
+ permissions,
+ repositorySelection,
+ repositoryIds,
+ repositoryNames,
+ singleFileName
+ });
+ }
+ }
+ const appAuthentication = await getAppAuthentication(state);
+ const request = customRequest || state.request;
+ const {
+ data: {
+ token,
+ expires_at: expiresAt,
+ repositories,
+ permissions: permissionsOptional,
+ repository_selection: repositorySelectionOptional,
+ single_file: singleFileName
+ }
+ } = await request("POST /app/installations/{installation_id}/access_tokens", {
+ installation_id: installationId,
+ repository_ids: options.repositoryIds,
+ repositories: options.repositoryNames,
+ permissions: options.permissions,
+ mediaType: {
+ previews: ["machine-man"]
+ },
+ headers: {
+ authorization: `bearer ${appAuthentication.token}`
+ }
+ });
+ /* istanbul ignore next - permissions are optional per OpenAPI spec, but we think that is incorrect */
+ const permissions = permissionsOptional || {};
+ /* istanbul ignore next - repositorySelection are optional per OpenAPI spec, but we think that is incorrect */
+ const repositorySelection = repositorySelectionOptional || "all";
+ const repositoryIds = repositories ? repositories.map(r => r.id) : void 0;
+ const repositoryNames = repositories ? repositories.map(repo => repo.name) : void 0;
+ const createdAt = new Date().toISOString();
+ await set(state.cache, optionsWithInstallationTokenFromState, {
+ token,
+ createdAt,
+ expiresAt,
+ repositorySelection,
+ permissions,
+ repositoryIds,
+ repositoryNames,
+ singleFileName
+ });
+ return toTokenAuthentication({
+ installationId,
+ token,
+ createdAt,
+ expiresAt,
+ repositorySelection,
+ permissions,
+ repositoryIds,
+ repositoryNames,
+ singleFileName
+ });
+}
+
+async function auth(state, authOptions) {
+ switch (authOptions.type) {
+ case "app":
+ return getAppAuthentication(state);
+ // @ts-expect-error "oauth" is not supperted in types
+ case "oauth":
+ state.log.warn(
+ // @ts-expect-error `log.warn()` expects string
+ new deprecation.Deprecation(`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`));
+ case "oauth-app":
+ return state.oauthApp({
+ type: "oauth-app"
+ });
+ case "installation":
+ return getInstallationAuthentication(state, {
+ ...authOptions,
+ type: "installation"
+ });
+ case "oauth-user":
+ // @ts-expect-error TODO: infer correct auth options type based on type. authOptions should be typed as "WebFlowAuthOptions | OAuthAppDeviceFlowAuthOptions | GitHubAppDeviceFlowAuthOptions"
+ return state.oauthApp(authOptions);
+ default:
+ // @ts-expect-error type is "never" at this point
+ throw new Error(`Invalid auth type: ${authOptions.type}`);
+ }
+}
+
+const PATHS = ["/app", "/app/hook/config", "/app/hook/deliveries", "/app/hook/deliveries/{delivery_id}", "/app/hook/deliveries/{delivery_id}/attempts", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"];
+// CREDIT: Simon Grondin (https://github.com/SGrondin)
+// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js
+function routeMatcher(paths) {
+ // EXAMPLE. For the following paths:
+ /* [
+ "/orgs/{org}/invitations",
+ "/repos/{owner}/{repo}/collaborators/{username}"
+ ] */
+ const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/"));
+ // 'regexes' would contain:
+ /* [
+ '/orgs/(?:.+?)/invitations',
+ '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)'
+ ] */
+ const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`;
+ // 'regex' would contain:
+ /*
+ ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$
+ It may look scary, but paste it into https://www.debuggex.com/
+ and it will make a lot more sense!
+ */
+ return new RegExp(regex, "i");
+}
+const REGEX = routeMatcher(PATHS);
+function requiresAppAuth(url) {
+ return !!url && REGEX.test(url);
+}
+
+const FIVE_SECONDS_IN_MS = 5 * 1000;
+function isNotTimeSkewError(error) {
+ return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/));
+}
+async function hook(state, request, route, parameters) {
+ const endpoint = request.endpoint.merge(route, parameters);
+ const url = endpoint.url;
+ // Do not intercept request to retrieve a new token
+ if (/\/login\/oauth\/access_token$/.test(url)) {
+ return request(endpoint);
+ }
+ if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) {
+ const {
+ token
+ } = await getAppAuthentication(state);
+ endpoint.headers.authorization = `bearer ${token}`;
+ let response;
+ try {
+ response = await request(endpoint);
+ } catch (error) {
+ // If there's an issue with the expiration, regenerate the token and try again.
+ // Otherwise rethrow the error for upstream handling.
+ if (isNotTimeSkewError(error)) {
+ throw error;
+ }
+ // If the date header is missing, we can't correct the system time skew.
+ // Throw the error to be handled upstream.
+ if (typeof error.response.headers.date === "undefined") {
+ throw error;
+ }
+ const diff = Math.floor((Date.parse(error.response.headers.date) - Date.parse(new Date().toString())) / 1000);
+ state.log.warn(error.message);
+ state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`);
+ const {
+ token
+ } = await getAppAuthentication({
+ ...state,
+ timeDifference: diff
+ });
+ endpoint.headers.authorization = `bearer ${token}`;
+ return request(endpoint);
+ }
+ return response;
+ }
+ if (authOauthUser.requiresBasicAuth(url)) {
+ const authentication = await state.oauthApp({
+ type: "oauth-app"
+ });
+ endpoint.headers.authorization = authentication.headers.authorization;
+ return request(endpoint);
+ }
+ const {
+ token,
+ createdAt
+ } = await getInstallationAuthentication(state,
+ // @ts-expect-error TBD
+ {}, request);
+ endpoint.headers.authorization = `token ${token}`;
+ return sendRequestWithRetries(state, request, endpoint, createdAt);
+}
+/**
+ * Newly created tokens might not be accessible immediately after creation.
+ * In case of a 401 response, we retry with an exponential delay until more
+ * than five seconds pass since the creation of the token.
+ *
+ * @see https://github.com/octokit/auth-app.js/issues/65
+ */
+async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) {
+ const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt);
+ try {
+ return await request(options);
+ } catch (error) {
+ if (error.status !== 401) {
+ throw error;
+ }
+ if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) {
+ if (retries > 0) {
+ error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`;
+ }
+ throw error;
+ }
+ ++retries;
+ const awaitTime = retries * 1000;
+ state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`);
+ await new Promise(resolve => setTimeout(resolve, awaitTime));
+ return sendRequestWithRetries(state, request, options, createdAt, retries);
+ }
+}
+
+const VERSION = "4.0.9";
+
+function createAppAuth(options) {
+ if (!options.appId) {
+ throw new Error("[@octokit/auth-app] appId option is required");
+ }
+ if (!Number.isFinite(+options.appId)) {
+ throw new Error("[@octokit/auth-app] appId option must be a number or numeric string");
+ }
+ if (!options.privateKey) {
+ throw new Error("[@octokit/auth-app] privateKey option is required");
+ }
+ if ("installationId" in options && !options.installationId) {
+ throw new Error("[@octokit/auth-app] installationId is set to a falsy value");
+ }
+ const log = Object.assign({
+ warn: console.warn.bind(console)
+ }, options.log);
+ const request$1 = options.request || request.request.defaults({
+ headers: {
+ "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+ });
+ const state = Object.assign({
+ request: request$1,
+ cache: getCache()
+ }, options, options.installationId ? {
+ installationId: Number(options.installationId)
+ } : {}, {
+ log,
+ oauthApp: authOauthApp.createOAuthAppAuth({
+ clientType: "github-app",
+ clientId: options.clientId || "",
+ clientSecret: options.clientSecret || "",
+ request: request$1
+ })
+ });
+ // @ts-expect-error not worth the extra code to appease TS
+ return Object.assign(auth.bind(null, state), {
+ hook: hook.bind(null, state)
+ });
+}
+
+Object.defineProperty(exports, "createOAuthUserAuth", ({
+ enumerable: true,
+ get: function () {
+ return authOauthUser.createOAuthUserAuth;
+ }
+}));
+exports.createAppAuth = createAppAuth;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 58459:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var universalUserAgent = __nccwpck_require__(45030);
+var request = __nccwpck_require__(36234);
+var btoa = _interopDefault(__nccwpck_require__(72358));
+var authOauthUser = __nccwpck_require__(11591);
+
+async function auth(state, authOptions) {
+ if (authOptions.type === "oauth-app") {
+ return {
+ type: "oauth-app",
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ clientType: state.clientType,
+ headers: {
+ authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}`
+ }
+ };
+ }
+ if ("factory" in authOptions) {
+ const {
+ type,
+ ...options
+ } = {
+ ...authOptions,
+ ...state
+ };
+ // @ts-expect-error TODO: `option` cannot be never, is this a bug?
+ return authOptions.factory(options);
+ }
+ const common = {
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ request: state.request,
+ ...authOptions
+ };
+ // TS: Look what you made me do
+ const userAuth = state.clientType === "oauth-app" ? await authOauthUser.createOAuthUserAuth({
+ ...common,
+ clientType: state.clientType
+ }) : await authOauthUser.createOAuthUserAuth({
+ ...common,
+ clientType: state.clientType
+ });
+ return userAuth();
+}
+
+async function hook(state, request, route, parameters) {
+ let endpoint = request.endpoint.merge(route, parameters);
+ // Do not intercept OAuth Web/Device flow request
+ if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
+ return request(endpoint);
+ }
+ if (state.clientType === "github-app" && !authOauthUser.requiresBasicAuth(endpoint.url)) {
+ throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`);
+ }
+ const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
+ endpoint.headers.authorization = `basic ${credentials}`;
+ try {
+ return await request(endpoint);
+ } catch (error) {
+ /* istanbul ignore if */
+ if (error.status !== 401) throw error;
+ error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`;
+ throw error;
+ }
+}
+
+const VERSION = "5.0.5";
+
+function createOAuthAppAuth(options) {
+ const state = Object.assign({
+ request: request.request.defaults({
+ headers: {
+ "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+ }),
+ clientType: "oauth-app"
+ }, options);
+ // @ts-expect-error not worth the extra code to appease TS
+ return Object.assign(auth.bind(null, state), {
+ hook: hook.bind(null, state)
+ });
+}
+
+Object.defineProperty(exports, "createOAuthUserAuth", ({
+ enumerable: true,
+ get: function () {
+ return authOauthUser.createOAuthUserAuth;
+ }
+}));
+exports.createOAuthAppAuth = createOAuthAppAuth;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 44344:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var universalUserAgent = __nccwpck_require__(45030);
+var request = __nccwpck_require__(36234);
+var oauthMethods = __nccwpck_require__(88445);
+
+async function getOAuthAccessToken(state, options) {
+ const cachedAuthentication = getCachedAuthentication(state, options.auth);
+ if (cachedAuthentication) return cachedAuthentication;
+ // Step 1: Request device and user codes
+ // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-1-app-requests-the-device-and-user-verification-codes-from-github
+ const {
+ data: verification
+ } = await oauthMethods.createDeviceCode({
+ clientType: state.clientType,
+ clientId: state.clientId,
+ request: options.request || state.request,
+ // @ts-expect-error the extra code to make TS happy is not worth it
+ scopes: options.auth.scopes || state.scopes
+ });
+ // Step 2: User must enter the user code on https://github.com/login/device
+ // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-2-prompt-the-user-to-enter-the-user-code-in-a-browser
+ await state.onVerification(verification);
+ // Step 3: Exchange device code for access token
+ // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-3-app-polls-github-to-check-if-the-user-authorized-the-device
+ const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification);
+ state.authentication = authentication;
+ return authentication;
+}
+function getCachedAuthentication(state, auth) {
+ if (auth.refresh === true) return false;
+ if (!state.authentication) return false;
+ if (state.clientType === "github-app") {
+ return state.authentication;
+ }
+ const authentication = state.authentication;
+ const newScope = ("scopes" in auth && auth.scopes || state.scopes).join(" ");
+ const currentScope = authentication.scopes.join(" ");
+ return newScope === currentScope ? authentication : false;
+}
+async function wait(seconds) {
+ await new Promise(resolve => setTimeout(resolve, seconds * 1000));
+}
+async function waitForAccessToken(request, clientId, clientType, verification) {
+ try {
+ const options = {
+ clientId,
+ request,
+ code: verification.device_code
+ };
+ // WHY TYPESCRIPT WHY ARE YOU DOING THIS TO ME
+ const {
+ authentication
+ } = clientType === "oauth-app" ? await oauthMethods.exchangeDeviceCode({
+ ...options,
+ clientType: "oauth-app"
+ }) : await oauthMethods.exchangeDeviceCode({
+ ...options,
+ clientType: "github-app"
+ });
+ return {
+ type: "token",
+ tokenType: "oauth",
+ ...authentication
+ };
+ } catch (error) {
+ // istanbul ignore if
+ // @ts-ignore
+ if (!error.response) throw error;
+ // @ts-ignore
+ const errorType = error.response.data.error;
+ if (errorType === "authorization_pending") {
+ await wait(verification.interval);
+ return waitForAccessToken(request, clientId, clientType, verification);
+ }
+ if (errorType === "slow_down") {
+ await wait(verification.interval + 5);
+ return waitForAccessToken(request, clientId, clientType, verification);
+ }
+ throw error;
+ }
+}
+
+async function auth(state, authOptions) {
+ return getOAuthAccessToken(state, {
+ auth: authOptions
+ });
+}
+
+async function hook(state, request, route, parameters) {
+ let endpoint = request.endpoint.merge(route, parameters);
+ // Do not intercept request to retrieve codes or token
+ if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
+ return request(endpoint);
+ }
+ const {
+ token
+ } = await getOAuthAccessToken(state, {
+ request,
+ auth: {
+ type: "oauth"
+ }
+ });
+ endpoint.headers.authorization = `token ${token}`;
+ return request(endpoint);
+}
+
+const VERSION = "4.0.4";
+
+function createOAuthDeviceAuth(options) {
+ const requestWithDefaults = options.request || request.request.defaults({
+ headers: {
+ "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+ });
+ const {
+ request: request$1 = requestWithDefaults,
+ ...otherOptions
+ } = options;
+ const state = options.clientType === "github-app" ? {
+ ...otherOptions,
+ clientType: "github-app",
+ request: request$1
+ } : {
+ ...otherOptions,
+ clientType: "oauth-app",
+ request: request$1,
+ scopes: options.scopes || []
+ };
+ if (!options.clientId) {
+ throw new Error('[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)');
+ }
+ if (!options.onVerification) {
+ throw new Error('[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)');
+ }
+ // @ts-ignore too much for tsc / ts-jest ¯\_(ツ)_/¯
+ return Object.assign(auth.bind(null, state), {
+ hook: hook.bind(null, state)
+ });
+}
+
+exports.createOAuthDeviceAuth = createOAuthDeviceAuth;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 11591:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var universalUserAgent = __nccwpck_require__(45030);
+var request = __nccwpck_require__(36234);
+var authOauthDevice = __nccwpck_require__(44344);
+var oauthMethods = __nccwpck_require__(88445);
+var btoa = _interopDefault(__nccwpck_require__(72358));
+
+const VERSION = "2.1.1";
+
+// @ts-nocheck there is only place for one of us in this file. And it's not you, TS
+async function getAuthentication(state) {
+ // handle code exchange form OAuth Web Flow
+ if ("code" in state.strategyOptions) {
+ const {
+ authentication
+ } = await oauthMethods.exchangeWebFlowCode({
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ clientType: state.clientType,
+ onTokenCreated: state.onTokenCreated,
+ ...state.strategyOptions,
+ request: state.request
+ });
+ return {
+ type: "token",
+ tokenType: "oauth",
+ ...authentication
+ };
+ }
+ // handle OAuth device flow
+ if ("onVerification" in state.strategyOptions) {
+ const deviceAuth = authOauthDevice.createOAuthDeviceAuth({
+ clientType: state.clientType,
+ clientId: state.clientId,
+ onTokenCreated: state.onTokenCreated,
+ ...state.strategyOptions,
+ request: state.request
+ });
+ const authentication = await deviceAuth({
+ type: "oauth"
+ });
+ return {
+ clientSecret: state.clientSecret,
+ ...authentication
+ };
+ }
+ // use existing authentication
+ if ("token" in state.strategyOptions) {
+ return {
+ type: "token",
+ tokenType: "oauth",
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ clientType: state.clientType,
+ onTokenCreated: state.onTokenCreated,
+ ...state.strategyOptions
+ };
+ }
+ throw new Error("[@octokit/auth-oauth-user] Invalid strategy options");
+}
+
+async function auth(state, options = {}) {
+ if (!state.authentication) {
+ // This is what TS makes us do ¯\_(ツ)_/¯
+ state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state);
+ }
+ if (state.authentication.invalid) {
+ throw new Error("[@octokit/auth-oauth-user] Token is invalid");
+ }
+ const currentAuthentication = state.authentication;
+ // (auto) refresh for user-to-server tokens
+ if ("expiresAt" in currentAuthentication) {
+ if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < new Date()) {
+ const {
+ authentication
+ } = await oauthMethods.refreshToken({
+ clientType: "github-app",
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ refreshToken: currentAuthentication.refreshToken,
+ request: state.request
+ });
+ state.authentication = {
+ tokenType: "oauth",
+ type: "token",
+ ...authentication
+ };
+ }
+ }
+ // throw error for invalid refresh call
+ if (options.type === "refresh") {
+ var _state$onTokenCreated;
+ if (state.clientType === "oauth-app") {
+ throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens");
+ }
+ if (!currentAuthentication.hasOwnProperty("expiresAt")) {
+ throw new Error("[@octokit/auth-oauth-user] Refresh token missing");
+ }
+ await ((_state$onTokenCreated = state.onTokenCreated) === null || _state$onTokenCreated === void 0 ? void 0 : _state$onTokenCreated.call(state, state.authentication, {
+ type: options.type
+ }));
+ }
+ // check or reset token
+ if (options.type === "check" || options.type === "reset") {
+ const method = options.type === "check" ? oauthMethods.checkToken : oauthMethods.resetToken;
+ try {
+ const {
+ authentication
+ } = await method({
+ // @ts-expect-error making TS happy would require unnecessary code so no
+ clientType: state.clientType,
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ token: state.authentication.token,
+ request: state.request
+ });
+ state.authentication = {
+ tokenType: "oauth",
+ type: "token",
+ // @ts-expect-error TBD
+ ...authentication
+ };
+ if (options.type === "reset") {
+ var _state$onTokenCreated2;
+ await ((_state$onTokenCreated2 = state.onTokenCreated) === null || _state$onTokenCreated2 === void 0 ? void 0 : _state$onTokenCreated2.call(state, state.authentication, {
+ type: options.type
+ }));
+ }
+ return state.authentication;
+ } catch (error) {
+ // istanbul ignore else
+ if (error.status === 404) {
+ error.message = "[@octokit/auth-oauth-user] Token is invalid";
+ // @ts-expect-error TBD
+ state.authentication.invalid = true;
+ }
+ throw error;
+ }
+ }
+ // invalidate
+ if (options.type === "delete" || options.type === "deleteAuthorization") {
+ const method = options.type === "delete" ? oauthMethods.deleteToken : oauthMethods.deleteAuthorization;
+ try {
+ await method({
+ // @ts-expect-error making TS happy would require unnecessary code so no
+ clientType: state.clientType,
+ clientId: state.clientId,
+ clientSecret: state.clientSecret,
+ token: state.authentication.token,
+ request: state.request
+ });
+ } catch (error) {
+ // istanbul ignore if
+ if (error.status !== 404) throw error;
+ }
+ state.authentication.invalid = true;
+ return state.authentication;
+ }
+ return state.authentication;
+}
+
+/**
+ * The following endpoints require an OAuth App to authenticate using its client_id and client_secret.
+ *
+ * - [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) - Check a token
+ * - [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) - Reset a token
+ * - [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) - Create a scoped access token
+ * - [`DELETE /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) - Delete an app token
+ * - [`DELETE /applications/{client_id}/grant`](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) - Delete an app authorization
+ *
+ * deprecated:
+ *
+ * - [`GET /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#check-an-authorization) - Check an authorization
+ * - [`POST /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#reset-an-authorization) - Reset an authorization
+ * - [`DELETE /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-an-authorization-for-an-application) - Revoke an authorization for an application
+ * - [`DELETE /applications/{client_id}/grants/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-a-grant-for-an-application) - Revoke a grant for an application
+ */
+const ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/;
+function requiresBasicAuth(url) {
+ return url && ROUTES_REQUIRING_BASIC_AUTH.test(url);
+}
+
+async function hook(state, request, route, parameters = {}) {
+ const endpoint = request.endpoint.merge(route, parameters);
+ // Do not intercept OAuth Web/Device flow request
+ if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) {
+ return request(endpoint);
+ }
+ if (requiresBasicAuth(endpoint.url)) {
+ const credentials = btoa(`${state.clientId}:${state.clientSecret}`);
+ endpoint.headers.authorization = `basic ${credentials}`;
+ return request(endpoint);
+ }
+ // TS makes us do this ¯\_(ツ)_/¯
+ const {
+ token
+ } = state.clientType === "oauth-app" ? await auth({
+ ...state,
+ request
+ }) : await auth({
+ ...state,
+ request
+ });
+ endpoint.headers.authorization = "token " + token;
+ return request(endpoint);
+}
+
+function createOAuthUserAuth({
+ clientId,
+ clientSecret,
+ clientType = "oauth-app",
+ request: request$1 = request.request.defaults({
+ headers: {
+ "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+ }),
+ onTokenCreated,
+ ...strategyOptions
+}) {
+ const state = Object.assign({
+ clientType,
+ clientId,
+ clientSecret,
+ onTokenCreated,
+ strategyOptions,
+ request: request$1
+ });
+ // @ts-expect-error not worth the extra code needed to appease TS
+ return Object.assign(auth.bind(null, state), {
+ // @ts-expect-error not worth the extra code needed to appease TS
+ hook: hook.bind(null, state)
+ });
+}
+createOAuthUserAuth.VERSION = VERSION;
+
+exports.createOAuthUserAuth = createOAuthUserAuth;
+exports.requiresBasicAuth = requiresBasicAuth;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 40334:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+const REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
+const REGEX_IS_INSTALLATION = /^ghs_/;
+const REGEX_IS_USER_TO_SERVER = /^ghu_/;
+async function auth(token) {
+ const isApp = token.split(/\./).length === 3;
+ const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
+ const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
+ const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
+ return {
+ type: "token",
+ token: token,
+ tokenType
+ };
+}
+
+/**
+ * Prefix token for usage in the Authorization header
+ *
+ * @param token OAuth token or JSON Web Token
+ */
+function withAuthorizationPrefix(token) {
+ if (token.split(/\./).length === 3) {
+ return `bearer ${token}`;
+ }
+
+ return `token ${token}`;
+}
+
+async function hook(token, request, route, parameters) {
+ const endpoint = request.endpoint.merge(route, parameters);
+ endpoint.headers.authorization = withAuthorizationPrefix(token);
+ return request(endpoint);
+}
+
+const createTokenAuth = function createTokenAuth(token) {
+ if (!token) {
+ throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
+ }
+
+ if (typeof token !== "string") {
+ throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");
+ }
+
+ token = token.replace(/^(token|bearer) +/i, "");
+ return Object.assign(auth.bind(null, token), {
+ hook: hook.bind(null, token)
+ });
+};
+
+exports.createTokenAuth = createTokenAuth;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 79567:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+async function auth(reason) {
+ return {
+ type: "unauthenticated",
+ reason
+ };
+}
+
+function isRateLimitError(error) {
+ if (error.status !== 403) {
+ return false;
+ }
+ /* istanbul ignore if */
+ if (!error.response) {
+ return false;
+ }
+ return error.response.headers["x-ratelimit-remaining"] === "0";
+}
+
+const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i;
+function isAbuseLimitError(error) {
+ if (error.status !== 403) {
+ return false;
+ }
+ return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message);
+}
+
+async function hook(reason, request, route, parameters) {
+ const endpoint = request.endpoint.merge(route, parameters);
+ return request(endpoint).catch(error => {
+ if (error.status === 404) {
+ error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`;
+ throw error;
+ }
+ if (isRateLimitError(error)) {
+ error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`;
+ throw error;
+ }
+ if (isAbuseLimitError(error)) {
+ error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`;
+ throw error;
+ }
+ if (error.status === 401) {
+ error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`;
+ throw error;
+ }
+ if (error.status >= 400 && error.status < 500) {
+ error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`);
+ }
+ throw error;
+ });
+}
+
+const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) {
+ if (!options || !options.reason) {
+ throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth");
+ }
+ return Object.assign(auth.bind(null, options.reason), {
+ hook: hook.bind(null, options.reason)
+ });
+};
+
+exports.createUnauthenticatedAuth = createUnauthenticatedAuth;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 76762:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var universalUserAgent = __nccwpck_require__(45030);
+var beforeAfterHook = __nccwpck_require__(83682);
+var request = __nccwpck_require__(6039);
+var graphql = __nccwpck_require__(88467);
+var authToken = __nccwpck_require__(40334);
+
+function _objectWithoutPropertiesLoose(source, excluded) {
+ if (source == null) return {};
+ var target = {};
+ var sourceKeys = Object.keys(source);
+ var key, i;
+
+ for (i = 0; i < sourceKeys.length; i++) {
+ key = sourceKeys[i];
+ if (excluded.indexOf(key) >= 0) continue;
+ target[key] = source[key];
+ }
+
+ return target;
+}
+
+function _objectWithoutProperties(source, excluded) {
+ if (source == null) return {};
+
+ var target = _objectWithoutPropertiesLoose(source, excluded);
+
+ var key, i;
+
+ if (Object.getOwnPropertySymbols) {
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
+
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
+ key = sourceSymbolKeys[i];
+ if (excluded.indexOf(key) >= 0) continue;
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
+ target[key] = source[key];
+ }
+ }
+
+ return target;
+}
+
+const VERSION = "3.6.0";
+
+const _excluded = ["authStrategy"];
+class Octokit {
+ constructor(options = {}) {
+ const hook = new beforeAfterHook.Collection();
+ const requestDefaults = {
+ baseUrl: request.request.endpoint.DEFAULTS.baseUrl,
+ headers: {},
+ request: Object.assign({}, options.request, {
+ // @ts-ignore internal usage only, no need to type
+ hook: hook.bind(null, "request")
+ }),
+ mediaType: {
+ previews: [],
+ format: ""
+ }
+ }; // prepend default user agent with `options.userAgent` if set
+
+ requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" ");
+
+ if (options.baseUrl) {
+ requestDefaults.baseUrl = options.baseUrl;
+ }
+
+ if (options.previews) {
+ requestDefaults.mediaType.previews = options.previews;
+ }
+
+ if (options.timeZone) {
+ requestDefaults.headers["time-zone"] = options.timeZone;
+ }
+
+ this.request = request.request.defaults(requestDefaults);
+ this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults);
+ this.log = Object.assign({
+ debug: () => {},
+ info: () => {},
+ warn: console.warn.bind(console),
+ error: console.error.bind(console)
+ }, options.log);
+ this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
+ // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered.
+ // (2) If only `options.auth` is set, use the default token authentication strategy.
+ // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
+ // TODO: type `options.auth` based on `options.authStrategy`.
+
+ if (!options.authStrategy) {
+ if (!options.auth) {
+ // (1)
+ this.auth = async () => ({
+ type: "unauthenticated"
+ });
+ } else {
+ // (2)
+ const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯
+
+ hook.wrap("request", auth.hook);
+ this.auth = auth;
+ }
+ } else {
+ const {
+ authStrategy
+ } = options,
+ otherOptions = _objectWithoutProperties(options, _excluded);
+
+ const auth = authStrategy(Object.assign({
+ request: this.request,
+ log: this.log,
+ // we pass the current octokit instance as well as its constructor options
+ // to allow for authentication strategies that return a new octokit instance
+ // that shares the same internal state as the current one. The original
+ // requirement for this was the "event-octokit" authentication strategy
+ // of https://github.com/probot/octokit-auth-probot.
+ octokit: this,
+ octokitOptions: otherOptions
+ }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯
+
+ hook.wrap("request", auth.hook);
+ this.auth = auth;
+ } // apply plugins
+ // https://stackoverflow.com/a/16345172
+
+
+ const classConstructor = this.constructor;
+ classConstructor.plugins.forEach(plugin => {
+ Object.assign(this, plugin(this, options));
+ });
+ }
+
+ static defaults(defaults) {
+ const OctokitWithDefaults = class extends this {
+ constructor(...args) {
+ const options = args[0] || {};
+
+ if (typeof defaults === "function") {
+ super(defaults(options));
+ return;
+ }
+
+ super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? {
+ userAgent: `${options.userAgent} ${defaults.userAgent}`
+ } : null));
+ }
+
+ };
+ return OctokitWithDefaults;
+ }
+ /**
+ * Attach a plugin (or many) to your Octokit instance.
+ *
+ * @example
+ * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
+ */
+
+
+ static plugin(...newPlugins) {
+ var _a;
+
+ const currentPlugins = this.plugins;
+ const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a);
+ return NewOctokit;
+ }
+
+}
+Octokit.VERSION = VERSION;
+Octokit.plugins = [];
+
+exports.Octokit = Octokit;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 42040:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var isPlainObject = __nccwpck_require__(63287);
+var universalUserAgent = __nccwpck_require__(45030);
+
+function lowercaseKeys(object) {
+ if (!object) {
+ return {};
+ }
+
+ return Object.keys(object).reduce((newObj, key) => {
+ newObj[key.toLowerCase()] = object[key];
+ return newObj;
+ }, {});
+}
+
+function mergeDeep(defaults, options) {
+ const result = Object.assign({}, defaults);
+ Object.keys(options).forEach(key => {
+ if (isPlainObject.isPlainObject(options[key])) {
+ if (!(key in defaults)) Object.assign(result, {
+ [key]: options[key]
+ });else result[key] = mergeDeep(defaults[key], options[key]);
+ } else {
+ Object.assign(result, {
+ [key]: options[key]
+ });
+ }
+ });
+ return result;
+}
+
+function removeUndefinedProperties(obj) {
+ for (const key in obj) {
+ if (obj[key] === undefined) {
+ delete obj[key];
+ }
+ }
+
+ return obj;
+}
+
+function merge(defaults, route, options) {
+ if (typeof route === "string") {
+ let [method, url] = route.split(" ");
+ options = Object.assign(url ? {
+ method,
+ url
+ } : {
+ url: method
+ }, options);
+ } else {
+ options = Object.assign({}, route);
+ } // lowercase header names before merging with defaults to avoid duplicates
+
+
+ options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging
+
+ removeUndefinedProperties(options);
+ removeUndefinedProperties(options.headers);
+ const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
+
+ if (defaults && defaults.mediaType.previews.length) {
+ mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
+ }
+
+ mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
+ return mergedOptions;
+}
+
+function addQueryParameters(url, parameters) {
+ const separator = /\?/.test(url) ? "&" : "?";
+ const names = Object.keys(parameters);
+
+ if (names.length === 0) {
+ return url;
+ }
+
+ return url + separator + names.map(name => {
+ if (name === "q") {
+ return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
+ }
+
+ return `${name}=${encodeURIComponent(parameters[name])}`;
+ }).join("&");
+}
+
+const urlVariableRegex = /\{[^}]+\}/g;
+
+function removeNonChars(variableName) {
+ return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
+}
+
+function extractUrlVariableNames(url) {
+ const matches = url.match(urlVariableRegex);
+
+ if (!matches) {
+ return [];
+ }
+
+ return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
+}
+
+function omit(object, keysToOmit) {
+ return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
+ obj[key] = object[key];
+ return obj;
+ }, {});
+}
+
+// Based on https://github.com/bramstein/url-template, licensed under BSD
+// TODO: create separate package.
+//
+// Copyright (c) 2012-2014, Bram Stein
+// All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/* istanbul ignore file */
+function encodeReserved(str) {
+ return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
+ if (!/%[0-9A-Fa-f]/.test(part)) {
+ part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
+ }
+
+ return part;
+ }).join("");
+}
+
+function encodeUnreserved(str) {
+ return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+ });
+}
+
+function encodeValue(operator, value, key) {
+ value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
+
+ if (key) {
+ return encodeUnreserved(key) + "=" + value;
+ } else {
+ return value;
+ }
+}
+
+function isDefined(value) {
+ return value !== undefined && value !== null;
+}
+
+function isKeyOperator(operator) {
+ return operator === ";" || operator === "&" || operator === "?";
+}
+
+function getValues(context, operator, key, modifier) {
+ var value = context[key],
+ result = [];
+
+ if (isDefined(value) && value !== "") {
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ value = value.toString();
+
+ if (modifier && modifier !== "*") {
+ value = value.substring(0, parseInt(modifier, 10));
+ }
+
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
+ } else {
+ if (modifier === "*") {
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ result.push(encodeValue(operator, value[k], k));
+ }
+ });
+ }
+ } else {
+ const tmp = [];
+
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ tmp.push(encodeValue(operator, value));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ tmp.push(encodeUnreserved(k));
+ tmp.push(encodeValue(operator, value[k].toString()));
+ }
+ });
+ }
+
+ if (isKeyOperator(operator)) {
+ result.push(encodeUnreserved(key) + "=" + tmp.join(","));
+ } else if (tmp.length !== 0) {
+ result.push(tmp.join(","));
+ }
+ }
+ }
+ } else {
+ if (operator === ";") {
+ if (isDefined(value)) {
+ result.push(encodeUnreserved(key));
+ }
+ } else if (value === "" && (operator === "&" || operator === "?")) {
+ result.push(encodeUnreserved(key) + "=");
+ } else if (value === "") {
+ result.push("");
+ }
+ }
+
+ return result;
+}
+
+function parseUrl(template) {
+ return {
+ expand: expand.bind(null, template)
+ };
+}
+
+function expand(template, context) {
+ var operators = ["+", "#", ".", "/", ";", "?", "&"];
+ return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
+ if (expression) {
+ let operator = "";
+ const values = [];
+
+ if (operators.indexOf(expression.charAt(0)) !== -1) {
+ operator = expression.charAt(0);
+ expression = expression.substr(1);
+ }
+
+ expression.split(/,/g).forEach(function (variable) {
+ var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
+ values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
+ });
+
+ if (operator && operator !== "+") {
+ var separator = ",";
+
+ if (operator === "?") {
+ separator = "&";
+ } else if (operator !== "#") {
+ separator = operator;
+ }
+
+ return (values.length !== 0 ? operator : "") + values.join(separator);
+ } else {
+ return values.join(",");
+ }
+ } else {
+ return encodeReserved(literal);
+ }
+ });
+}
+
+function parse(options) {
+ // https://fetch.spec.whatwg.org/#methods
+ let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
+
+ let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
+ let headers = Object.assign({}, options.headers);
+ let body;
+ let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
+
+ const urlVariableNames = extractUrlVariableNames(url);
+ url = parseUrl(url).expand(parameters);
+
+ if (!/^http/.test(url)) {
+ url = options.baseUrl + url;
+ }
+
+ const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
+ const remainingParameters = omit(parameters, omittedParameters);
+ const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
+
+ if (!isBinaryRequest) {
+ if (options.mediaType.format) {
+ // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
+ headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
+ }
+
+ if (options.mediaType.previews.length) {
+ const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
+ headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
+ const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
+ return `application/vnd.github.${preview}-preview${format}`;
+ }).join(",");
+ }
+ } // for GET/HEAD requests, set URL query parameters from remaining parameters
+ // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
+
+
+ if (["GET", "HEAD"].includes(method)) {
+ url = addQueryParameters(url, remainingParameters);
+ } else {
+ if ("data" in remainingParameters) {
+ body = remainingParameters.data;
+ } else {
+ if (Object.keys(remainingParameters).length) {
+ body = remainingParameters;
+ } else {
+ headers["content-length"] = 0;
+ }
+ }
+ } // default content-type for JSON if body is set
+
+
+ if (!headers["content-type"] && typeof body !== "undefined") {
+ headers["content-type"] = "application/json; charset=utf-8";
+ } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
+ // fetch does not allow to set `content-length` header, but we can set body to an empty string
+
+
+ if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
+ body = "";
+ } // Only return body/request keys if present
+
+
+ return Object.assign({
+ method,
+ url,
+ headers
+ }, typeof body !== "undefined" ? {
+ body
+ } : null, options.request ? {
+ request: options.request
+ } : null);
+}
+
+function endpointWithDefaults(defaults, route, options) {
+ return parse(merge(defaults, route, options));
+}
+
+function withDefaults(oldDefaults, newDefaults) {
+ const DEFAULTS = merge(oldDefaults, newDefaults);
+ const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
+ return Object.assign(endpoint, {
+ DEFAULTS,
+ defaults: withDefaults.bind(null, DEFAULTS),
+ merge: merge.bind(null, DEFAULTS),
+ parse
+ });
+}
+
+const VERSION = "6.0.12";
+
+const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
+// So we use RequestParameters and add method as additional required property.
+
+const DEFAULTS = {
+ method: "GET",
+ baseUrl: "https://api.github.com",
+ headers: {
+ accept: "application/vnd.github.v3+json",
+ "user-agent": userAgent
+ },
+ mediaType: {
+ format: "",
+ previews: []
+ }
+};
+
+const endpoint = withDefaults(null, DEFAULTS);
+
+exports.endpoint = endpoint;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 6039:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var endpoint = __nccwpck_require__(42040);
+var universalUserAgent = __nccwpck_require__(45030);
+var isPlainObject = __nccwpck_require__(63287);
+var nodeFetch = _interopDefault(__nccwpck_require__(13801));
+var requestError = __nccwpck_require__(10537);
+
+const VERSION = "5.6.3";
+
+function getBufferResponse(response) {
+ return response.arrayBuffer();
+}
+
+function fetchWrapper(requestOptions) {
+ const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
+
+ if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
+ requestOptions.body = JSON.stringify(requestOptions.body);
+ }
+
+ let headers = {};
+ let status;
+ let url;
+ const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;
+ return fetch(requestOptions.url, Object.assign({
+ method: requestOptions.method,
+ body: requestOptions.body,
+ headers: requestOptions.headers,
+ redirect: requestOptions.redirect
+ }, // `requestOptions.request.agent` type is incompatible
+ // see https://github.com/octokit/types.ts/pull/264
+ requestOptions.request)).then(async response => {
+ url = response.url;
+ status = response.status;
+
+ for (const keyAndValue of response.headers) {
+ headers[keyAndValue[0]] = keyAndValue[1];
+ }
+
+ if ("deprecation" in headers) {
+ const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
+ const deprecationLink = matches && matches.pop();
+ log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
+ }
+
+ if (status === 204 || status === 205) {
+ return;
+ } // GitHub API returns 200 for HEAD requests
+
+
+ if (requestOptions.method === "HEAD") {
+ if (status < 400) {
+ return;
+ }
+
+ throw new requestError.RequestError(response.statusText, status, {
+ response: {
+ url,
+ status,
+ headers,
+ data: undefined
+ },
+ request: requestOptions
+ });
+ }
+
+ if (status === 304) {
+ throw new requestError.RequestError("Not modified", status, {
+ response: {
+ url,
+ status,
+ headers,
+ data: await getResponseData(response)
+ },
+ request: requestOptions
+ });
+ }
+
+ if (status >= 400) {
+ const data = await getResponseData(response);
+ const error = new requestError.RequestError(toErrorMessage(data), status, {
+ response: {
+ url,
+ status,
+ headers,
+ data
+ },
+ request: requestOptions
+ });
+ throw error;
+ }
+
+ return getResponseData(response);
+ }).then(data => {
+ return {
+ status,
+ url,
+ headers,
+ data
+ };
+ }).catch(error => {
+ if (error instanceof requestError.RequestError) throw error;
+ throw new requestError.RequestError(error.message, 500, {
+ request: requestOptions
+ });
+ });
+}
+
+async function getResponseData(response) {
+ const contentType = response.headers.get("content-type");
+
+ if (/application\/json/.test(contentType)) {
+ return response.json();
+ }
+
+ if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
+ return response.text();
+ }
+
+ return getBufferResponse(response);
+}
+
+function toErrorMessage(data) {
+ if (typeof data === "string") return data; // istanbul ignore else - just in case
+
+ if ("message" in data) {
+ if (Array.isArray(data.errors)) {
+ return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
+ }
+
+ return data.message;
+ } // istanbul ignore next - just in case
+
+
+ return `Unknown error: ${JSON.stringify(data)}`;
+}
+
+function withDefaults(oldEndpoint, newDefaults) {
+ const endpoint = oldEndpoint.defaults(newDefaults);
+
+ const newApi = function (route, parameters) {
+ const endpointOptions = endpoint.merge(route, parameters);
+
+ if (!endpointOptions.request || !endpointOptions.request.hook) {
+ return fetchWrapper(endpoint.parse(endpointOptions));
+ }
+
+ const request = (route, parameters) => {
+ return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));
+ };
+
+ Object.assign(request, {
+ endpoint,
+ defaults: withDefaults.bind(null, endpoint)
+ });
+ return endpointOptions.request.hook(request, endpointOptions);
+ };
+
+ return Object.assign(newApi, {
+ endpoint,
+ defaults: withDefaults.bind(null, endpoint)
+ });
+}
+
+const request = withDefaults(endpoint.endpoint, {
+ headers: {
+ "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+});
+
+exports.request = request;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 13801:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var Stream = _interopDefault(__nccwpck_require__(12781));
+var http = _interopDefault(__nccwpck_require__(13685));
+var Url = _interopDefault(__nccwpck_require__(57310));
+var whatwgUrl = _interopDefault(__nccwpck_require__(28665));
+var https = _interopDefault(__nccwpck_require__(95687));
+var zlib = _interopDefault(__nccwpck_require__(59796));
+
+// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
+
+// fix for "Readable" isn't a named export issue
+const Readable = Stream.Readable;
+
+const BUFFER = Symbol('buffer');
+const TYPE = Symbol('type');
+
+class Blob {
+ constructor() {
+ this[TYPE] = '';
+
+ const blobParts = arguments[0];
+ const options = arguments[1];
+
+ const buffers = [];
+ let size = 0;
+
+ if (blobParts) {
+ const a = blobParts;
+ const length = Number(a.length);
+ for (let i = 0; i < length; i++) {
+ const element = a[i];
+ let buffer;
+ if (element instanceof Buffer) {
+ buffer = element;
+ } else if (ArrayBuffer.isView(element)) {
+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
+ } else if (element instanceof ArrayBuffer) {
+ buffer = Buffer.from(element);
+ } else if (element instanceof Blob) {
+ buffer = element[BUFFER];
+ } else {
+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));
+ }
+ size += buffer.length;
+ buffers.push(buffer);
+ }
+ }
+
+ this[BUFFER] = Buffer.concat(buffers);
+
+ let type = options && options.type !== undefined && String(options.type).toLowerCase();
+ if (type && !/[^\u0020-\u007E]/.test(type)) {
+ this[TYPE] = type;
+ }
+ }
+ get size() {
+ return this[BUFFER].length;
+ }
+ get type() {
+ return this[TYPE];
+ }
+ text() {
+ return Promise.resolve(this[BUFFER].toString());
+ }
+ arrayBuffer() {
+ const buf = this[BUFFER];
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ return Promise.resolve(ab);
+ }
+ stream() {
+ const readable = new Readable();
+ readable._read = function () {};
+ readable.push(this[BUFFER]);
+ readable.push(null);
+ return readable;
+ }
+ toString() {
+ return '[object Blob]';
+ }
+ slice() {
+ const size = this.size;
+
+ const start = arguments[0];
+ const end = arguments[1];
+ let relativeStart, relativeEnd;
+ if (start === undefined) {
+ relativeStart = 0;
+ } else if (start < 0) {
+ relativeStart = Math.max(size + start, 0);
+ } else {
+ relativeStart = Math.min(start, size);
+ }
+ if (end === undefined) {
+ relativeEnd = size;
+ } else if (end < 0) {
+ relativeEnd = Math.max(size + end, 0);
+ } else {
+ relativeEnd = Math.min(end, size);
+ }
+ const span = Math.max(relativeEnd - relativeStart, 0);
+
+ const buffer = this[BUFFER];
+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
+ const blob = new Blob([], { type: arguments[2] });
+ blob[BUFFER] = slicedBuffer;
+ return blob;
+ }
+}
+
+Object.defineProperties(Blob.prototype, {
+ size: { enumerable: true },
+ type: { enumerable: true },
+ slice: { enumerable: true }
+});
+
+Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
+ value: 'Blob',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * fetch-error.js
+ *
+ * FetchError interface for operational errors
+ */
+
+/**
+ * Create FetchError instance
+ *
+ * @param String message Error message for human
+ * @param String type Error type for machine
+ * @param String systemError For Node.js system error
+ * @return FetchError
+ */
+function FetchError(message, type, systemError) {
+ Error.call(this, message);
+
+ this.message = message;
+ this.type = type;
+
+ // when err.type is `system`, err.code contains system error code
+ if (systemError) {
+ this.code = this.errno = systemError.code;
+ }
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+FetchError.prototype = Object.create(Error.prototype);
+FetchError.prototype.constructor = FetchError;
+FetchError.prototype.name = 'FetchError';
+
+let convert;
+try {
+ convert = (__nccwpck_require__(22877).convert);
+} catch (e) {}
+
+const INTERNALS = Symbol('Body internals');
+
+// fix an issue where "PassThrough" isn't a named export for node <10
+const PassThrough = Stream.PassThrough;
+
+/**
+ * Body mixin
+ *
+ * Ref: https://fetch.spec.whatwg.org/#body
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+function Body(body) {
+ var _this = this;
+
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ _ref$size = _ref.size;
+
+ let size = _ref$size === undefined ? 0 : _ref$size;
+ var _ref$timeout = _ref.timeout;
+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
+
+ if (body == null) {
+ // body is undefined or null
+ body = null;
+ } else if (isURLSearchParams(body)) {
+ // body is a URLSearchParams
+ body = Buffer.from(body.toString());
+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
+ // body is ArrayBuffer
+ body = Buffer.from(body);
+ } else if (ArrayBuffer.isView(body)) {
+ // body is ArrayBufferView
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
+ } else if (body instanceof Stream) ; else {
+ // none of the above
+ // coerce to string then buffer
+ body = Buffer.from(String(body));
+ }
+ this[INTERNALS] = {
+ body,
+ disturbed: false,
+ error: null
+ };
+ this.size = size;
+ this.timeout = timeout;
+
+ if (body instanceof Stream) {
+ body.on('error', function (err) {
+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
+ _this[INTERNALS].error = error;
+ });
+ }
+}
+
+Body.prototype = {
+ get body() {
+ return this[INTERNALS].body;
+ },
+
+ get bodyUsed() {
+ return this[INTERNALS].disturbed;
+ },
+
+ /**
+ * Decode response as ArrayBuffer
+ *
+ * @return Promise
+ */
+ arrayBuffer() {
+ return consumeBody.call(this).then(function (buf) {
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ });
+ },
+
+ /**
+ * Return raw response as Blob
+ *
+ * @return Promise
+ */
+ blob() {
+ let ct = this.headers && this.headers.get('content-type') || '';
+ return consumeBody.call(this).then(function (buf) {
+ return Object.assign(
+ // Prevent copying
+ new Blob([], {
+ type: ct.toLowerCase()
+ }), {
+ [BUFFER]: buf
+ });
+ });
+ },
+
+ /**
+ * Decode response as json
+ *
+ * @return Promise
+ */
+ json() {
+ var _this2 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ try {
+ return JSON.parse(buffer.toString());
+ } catch (err) {
+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
+ }
+ });
+ },
+
+ /**
+ * Decode response as text
+ *
+ * @return Promise
+ */
+ text() {
+ return consumeBody.call(this).then(function (buffer) {
+ return buffer.toString();
+ });
+ },
+
+ /**
+ * Decode response as buffer (non-spec api)
+ *
+ * @return Promise
+ */
+ buffer() {
+ return consumeBody.call(this);
+ },
+
+ /**
+ * Decode response as text, while automatically detecting the encoding and
+ * trying to decode to UTF-8 (non-spec api)
+ *
+ * @return Promise
+ */
+ textConverted() {
+ var _this3 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ return convertBody(buffer, _this3.headers);
+ });
+ }
+};
+
+// In browsers, all properties are enumerable.
+Object.defineProperties(Body.prototype, {
+ body: { enumerable: true },
+ bodyUsed: { enumerable: true },
+ arrayBuffer: { enumerable: true },
+ blob: { enumerable: true },
+ json: { enumerable: true },
+ text: { enumerable: true }
+});
+
+Body.mixIn = function (proto) {
+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {
+ // istanbul ignore else: future proof
+ if (!(name in proto)) {
+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
+ Object.defineProperty(proto, name, desc);
+ }
+ }
+};
+
+/**
+ * Consume and convert an entire Body to a Buffer.
+ *
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
+ *
+ * @return Promise
+ */
+function consumeBody() {
+ var _this4 = this;
+
+ if (this[INTERNALS].disturbed) {
+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
+ }
+
+ this[INTERNALS].disturbed = true;
+
+ if (this[INTERNALS].error) {
+ return Body.Promise.reject(this[INTERNALS].error);
+ }
+
+ let body = this.body;
+
+ // body is null
+ if (body === null) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is blob
+ if (isBlob(body)) {
+ body = body.stream();
+ }
+
+ // body is buffer
+ if (Buffer.isBuffer(body)) {
+ return Body.Promise.resolve(body);
+ }
+
+ // istanbul ignore if: should never happen
+ if (!(body instanceof Stream)) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is stream
+ // get ready to actually consume the body
+ let accum = [];
+ let accumBytes = 0;
+ let abort = false;
+
+ return new Body.Promise(function (resolve, reject) {
+ let resTimeout;
+
+ // allow timeout on slow response body
+ if (_this4.timeout) {
+ resTimeout = setTimeout(function () {
+ abort = true;
+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
+ }, _this4.timeout);
+ }
+
+ // handle stream errors
+ body.on('error', function (err) {
+ if (err.name === 'AbortError') {
+ // if the request was aborted, reject with this Error
+ abort = true;
+ reject(err);
+ } else {
+ // other errors, such as incorrect content-encoding
+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+
+ body.on('data', function (chunk) {
+ if (abort || chunk === null) {
+ return;
+ }
+
+ if (_this4.size && accumBytes + chunk.length > _this4.size) {
+ abort = true;
+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
+ return;
+ }
+
+ accumBytes += chunk.length;
+ accum.push(chunk);
+ });
+
+ body.on('end', function () {
+ if (abort) {
+ return;
+ }
+
+ clearTimeout(resTimeout);
+
+ try {
+ resolve(Buffer.concat(accum, accumBytes));
+ } catch (err) {
+ // handle streams that have accumulated too much data (issue #414)
+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+ });
+}
+
+/**
+ * Detect buffer encoding and convert to target encoding
+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
+ *
+ * @param Buffer buffer Incoming buffer
+ * @param String encoding Target encoding
+ * @return String
+ */
+function convertBody(buffer, headers) {
+ if (typeof convert !== 'function') {
+ throw new Error('The package `encoding` must be installed to use the textConverted() function');
+ }
+
+ const ct = headers.get('content-type');
+ let charset = 'utf-8';
+ let res, str;
+
+ // header
+ if (ct) {
+ res = /charset=([^;]*)/i.exec(ct);
+ }
+
+ // no charset in content type, peek at response body for at most 1024 bytes
+ str = buffer.slice(0, 1024).toString();
+
+ // html5
+ if (!res && str) {
+ res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;
+
+ this[MAP] = Object.create(null);
+
+ if (init instanceof Headers) {
+ const rawHeaders = init.raw();
+ const headerNames = Object.keys(rawHeaders);
+
+ for (const headerName of headerNames) {
+ for (const value of rawHeaders[headerName]) {
+ this.append(headerName, value);
+ }
+ }
+
+ return;
+ }
+
+ // We don't worry about converting prop to ByteString here as append()
+ // will handle it.
+ if (init == null) ; else if (typeof init === 'object') {
+ const method = init[Symbol.iterator];
+ if (method != null) {
+ if (typeof method !== 'function') {
+ throw new TypeError('Header pairs must be iterable');
+ }
+
+ // sequence>
+ // Note: per spec we have to first exhaust the lists then process them
+ const pairs = [];
+ for (const pair of init) {
+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
+ throw new TypeError('Each header pair must be iterable');
+ }
+ pairs.push(Array.from(pair));
+ }
+
+ for (const pair of pairs) {
+ if (pair.length !== 2) {
+ throw new TypeError('Each header pair must be a name/value tuple');
+ }
+ this.append(pair[0], pair[1]);
+ }
+ } else {
+ // record
+ for (const key of Object.keys(init)) {
+ const value = init[key];
+ this.append(key, value);
+ }
+ }
+ } else {
+ throw new TypeError('Provided initializer must be an object');
+ }
+ }
+
+ /**
+ * Return combined header value given name
+ *
+ * @param String name Header name
+ * @return Mixed
+ */
+ get(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key === undefined) {
+ return null;
+ }
+
+ return this[MAP][key].join(', ');
+ }
+
+ /**
+ * Iterate over all headers
+ *
+ * @param Function callback Executed for each item with parameters (value, name, thisArg)
+ * @param Boolean thisArg `this` context for callback function
+ * @return Void
+ */
+ forEach(callback) {
+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
+
+ let pairs = getHeaders(this);
+ let i = 0;
+ while (i < pairs.length) {
+ var _pairs$i = pairs[i];
+ const name = _pairs$i[0],
+ value = _pairs$i[1];
+
+ callback.call(thisArg, value, name, this);
+ pairs = getHeaders(this);
+ i++;
+ }
+ }
+
+ /**
+ * Overwrite header values given name
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ set(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ this[MAP][key !== undefined ? key : name] = [value];
+ }
+
+ /**
+ * Append a value onto existing header
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ append(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ this[MAP][key].push(value);
+ } else {
+ this[MAP][name] = [value];
+ }
+ }
+
+ /**
+ * Check for header name existence
+ *
+ * @param String name Header name
+ * @return Boolean
+ */
+ has(name) {
+ name = `${name}`;
+ validateName(name);
+ return find(this[MAP], name) !== undefined;
+ }
+
+ /**
+ * Delete all header values given name
+ *
+ * @param String name Header name
+ * @return Void
+ */
+ delete(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ delete this[MAP][key];
+ }
+ }
+
+ /**
+ * Return raw headers (non-spec api)
+ *
+ * @return Object
+ */
+ raw() {
+ return this[MAP];
+ }
+
+ /**
+ * Get an iterator on keys.
+ *
+ * @return Iterator
+ */
+ keys() {
+ return createHeadersIterator(this, 'key');
+ }
+
+ /**
+ * Get an iterator on values.
+ *
+ * @return Iterator
+ */
+ values() {
+ return createHeadersIterator(this, 'value');
+ }
+
+ /**
+ * Get an iterator on entries.
+ *
+ * This is the default iterator of the Headers object.
+ *
+ * @return Iterator
+ */
+ [Symbol.iterator]() {
+ return createHeadersIterator(this, 'key+value');
+ }
+}
+Headers.prototype.entries = Headers.prototype[Symbol.iterator];
+
+Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
+ value: 'Headers',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Headers.prototype, {
+ get: { enumerable: true },
+ forEach: { enumerable: true },
+ set: { enumerable: true },
+ append: { enumerable: true },
+ has: { enumerable: true },
+ delete: { enumerable: true },
+ keys: { enumerable: true },
+ values: { enumerable: true },
+ entries: { enumerable: true }
+});
+
+function getHeaders(headers) {
+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
+
+ const keys = Object.keys(headers[MAP]).sort();
+ return keys.map(kind === 'key' ? function (k) {
+ return k.toLowerCase();
+ } : kind === 'value' ? function (k) {
+ return headers[MAP][k].join(', ');
+ } : function (k) {
+ return [k.toLowerCase(), headers[MAP][k].join(', ')];
+ });
+}
+
+const INTERNAL = Symbol('internal');
+
+function createHeadersIterator(target, kind) {
+ const iterator = Object.create(HeadersIteratorPrototype);
+ iterator[INTERNAL] = {
+ target,
+ kind,
+ index: 0
+ };
+ return iterator;
+}
+
+const HeadersIteratorPrototype = Object.setPrototypeOf({
+ next() {
+ // istanbul ignore if
+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
+ throw new TypeError('Value of `this` is not a HeadersIterator');
+ }
+
+ var _INTERNAL = this[INTERNAL];
+ const target = _INTERNAL.target,
+ kind = _INTERNAL.kind,
+ index = _INTERNAL.index;
+
+ const values = getHeaders(target, kind);
+ const len = values.length;
+ if (index >= len) {
+ return {
+ value: undefined,
+ done: true
+ };
+ }
+
+ this[INTERNAL].index = index + 1;
+
+ return {
+ value: values[index],
+ done: false
+ };
+ }
+}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
+
+Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
+ value: 'HeadersIterator',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * Export the Headers object in a form that Node.js can consume.
+ *
+ * @param Headers headers
+ * @return Object
+ */
+function exportNodeCompatibleHeaders(headers) {
+ const obj = Object.assign({ __proto__: null }, headers[MAP]);
+
+ // http.request() only supports string as Host header. This hack makes
+ // specifying custom Host header possible.
+ const hostHeaderKey = find(headers[MAP], 'Host');
+ if (hostHeaderKey !== undefined) {
+ obj[hostHeaderKey] = obj[hostHeaderKey][0];
+ }
+
+ return obj;
+}
+
+/**
+ * Create a Headers object from an object of headers, ignoring those that do
+ * not conform to HTTP grammar productions.
+ *
+ * @param Object obj Object of headers
+ * @return Headers
+ */
+function createHeadersLenient(obj) {
+ const headers = new Headers();
+ for (const name of Object.keys(obj)) {
+ if (invalidTokenRegex.test(name)) {
+ continue;
+ }
+ if (Array.isArray(obj[name])) {
+ for (const val of obj[name]) {
+ if (invalidHeaderCharRegex.test(val)) {
+ continue;
+ }
+ if (headers[MAP][name] === undefined) {
+ headers[MAP][name] = [val];
+ } else {
+ headers[MAP][name].push(val);
+ }
+ }
+ } else if (!invalidHeaderCharRegex.test(obj[name])) {
+ headers[MAP][name] = [obj[name]];
+ }
+ }
+ return headers;
+}
+
+const INTERNALS$1 = Symbol('Response internals');
+
+// fix an issue where "STATUS_CODES" aren't a named export for node <10
+const STATUS_CODES = http.STATUS_CODES;
+
+/**
+ * Response class
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+class Response {
+ constructor() {
+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ Body.call(this, body, opts);
+
+ const status = opts.status || 200;
+ const headers = new Headers(opts.headers);
+
+ if (body != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(body);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ this[INTERNALS$1] = {
+ url: opts.url,
+ status,
+ statusText: opts.statusText || STATUS_CODES[status],
+ headers,
+ counter: opts.counter
+ };
+ }
+
+ get url() {
+ return this[INTERNALS$1].url || '';
+ }
+
+ get status() {
+ return this[INTERNALS$1].status;
+ }
+
+ /**
+ * Convenience property representing if the request ended normally
+ */
+ get ok() {
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
+ }
+
+ get redirected() {
+ return this[INTERNALS$1].counter > 0;
+ }
+
+ get statusText() {
+ return this[INTERNALS$1].statusText;
+ }
+
+ get headers() {
+ return this[INTERNALS$1].headers;
+ }
+
+ /**
+ * Clone this response
+ *
+ * @return Response
+ */
+ clone() {
+ return new Response(clone(this), {
+ url: this.url,
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ ok: this.ok,
+ redirected: this.redirected
+ });
+ }
+}
+
+Body.mixIn(Response.prototype);
+
+Object.defineProperties(Response.prototype, {
+ url: { enumerable: true },
+ status: { enumerable: true },
+ ok: { enumerable: true },
+ redirected: { enumerable: true },
+ statusText: { enumerable: true },
+ headers: { enumerable: true },
+ clone: { enumerable: true }
+});
+
+Object.defineProperty(Response.prototype, Symbol.toStringTag, {
+ value: 'Response',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+const INTERNALS$2 = Symbol('Request internals');
+const URL = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "format", "parse" aren't a named export for node <10
+const parse_url = Url.parse;
+const format_url = Url.format;
+
+/**
+ * Wrapper around `new URL` to handle arbitrary URLs
+ *
+ * @param {string} urlStr
+ * @return {void}
+ */
+function parseURL(urlStr) {
+ /*
+ Check whether the URL is absolute or not
+ Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
+ Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
+ */
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
+ urlStr = new URL(urlStr).toString();
+ }
+
+ // Fallback to old implementation for arbitrary URLs
+ return parse_url(urlStr);
+}
+
+const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
+
+/**
+ * Check if a value is an instance of Request.
+ *
+ * @param Mixed input
+ * @return Boolean
+ */
+function isRequest(input) {
+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
+}
+
+function isAbortSignal(signal) {
+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
+ return !!(proto && proto.constructor.name === 'AbortSignal');
+}
+
+/**
+ * Request class
+ *
+ * @param Mixed input Url or Request instance
+ * @param Object init Custom options
+ * @return Void
+ */
+class Request {
+ constructor(input) {
+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ let parsedURL;
+
+ // normalize input
+ if (!isRequest(input)) {
+ if (input && input.href) {
+ // in order to support Node.js' Url objects; though WHATWG's URL objects
+ // will fall into this branch also (since their `toString()` will return
+ // `href` property anyway)
+ parsedURL = parseURL(input.href);
+ } else {
+ // coerce input to a string before attempting to parse
+ parsedURL = parseURL(`${input}`);
+ }
+ input = {};
+ } else {
+ parsedURL = parseURL(input.url);
+ }
+
+ let method = init.method || input.method || 'GET';
+ method = method.toUpperCase();
+
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
+ throw new TypeError('Request with GET/HEAD method cannot have body');
+ }
+
+ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
+
+ Body.call(this, inputBody, {
+ timeout: init.timeout || input.timeout || 0,
+ size: init.size || input.size || 0
+ });
+
+ const headers = new Headers(init.headers || input.headers || {});
+
+ if (inputBody != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(inputBody);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ let signal = isRequest(input) ? input.signal : null;
+ if ('signal' in init) signal = init.signal;
+
+ if (signal != null && !isAbortSignal(signal)) {
+ throw new TypeError('Expected signal to be an instanceof AbortSignal');
+ }
+
+ this[INTERNALS$2] = {
+ method,
+ redirect: init.redirect || input.redirect || 'follow',
+ headers,
+ parsedURL,
+ signal
+ };
+
+ // node-fetch-only options
+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
+ this.counter = init.counter || input.counter || 0;
+ this.agent = init.agent || input.agent;
+ }
+
+ get method() {
+ return this[INTERNALS$2].method;
+ }
+
+ get url() {
+ return format_url(this[INTERNALS$2].parsedURL);
+ }
+
+ get headers() {
+ return this[INTERNALS$2].headers;
+ }
+
+ get redirect() {
+ return this[INTERNALS$2].redirect;
+ }
+
+ get signal() {
+ return this[INTERNALS$2].signal;
+ }
+
+ /**
+ * Clone this request
+ *
+ * @return Request
+ */
+ clone() {
+ return new Request(this);
+ }
+}
+
+Body.mixIn(Request.prototype);
+
+Object.defineProperty(Request.prototype, Symbol.toStringTag, {
+ value: 'Request',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Request.prototype, {
+ method: { enumerable: true },
+ url: { enumerable: true },
+ headers: { enumerable: true },
+ redirect: { enumerable: true },
+ clone: { enumerable: true },
+ signal: { enumerable: true }
+});
+
+/**
+ * Convert a Request to Node.js http request options.
+ *
+ * @param Request A Request instance
+ * @return Object The options object to be passed to http.request
+ */
+function getNodeRequestOptions(request) {
+ const parsedURL = request[INTERNALS$2].parsedURL;
+ const headers = new Headers(request[INTERNALS$2].headers);
+
+ // fetch step 1.3
+ if (!headers.has('Accept')) {
+ headers.set('Accept', '*/*');
+ }
+
+ // Basic fetch
+ if (!parsedURL.protocol || !parsedURL.hostname) {
+ throw new TypeError('Only absolute URLs are supported');
+ }
+
+ if (!/^https?:$/.test(parsedURL.protocol)) {
+ throw new TypeError('Only HTTP(S) protocols are supported');
+ }
+
+ if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
+ }
+
+ // HTTP-network-or-cache fetch steps 2.4-2.7
+ let contentLengthValue = null;
+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
+ contentLengthValue = '0';
+ }
+ if (request.body != null) {
+ const totalBytes = getTotalBytes(request);
+ if (typeof totalBytes === 'number') {
+ contentLengthValue = String(totalBytes);
+ }
+ }
+ if (contentLengthValue) {
+ headers.set('Content-Length', contentLengthValue);
+ }
+
+ // HTTP-network-or-cache fetch step 2.11
+ if (!headers.has('User-Agent')) {
+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
+ }
+
+ // HTTP-network-or-cache fetch step 2.15
+ if (request.compress && !headers.has('Accept-Encoding')) {
+ headers.set('Accept-Encoding', 'gzip,deflate');
+ }
+
+ let agent = request.agent;
+ if (typeof agent === 'function') {
+ agent = agent(parsedURL);
+ }
+
+ if (!headers.has('Connection') && !agent) {
+ headers.set('Connection', 'close');
+ }
+
+ // HTTP-network fetch step 4.2
+ // chunked encoding is handled by Node.js
+
+ return Object.assign({}, parsedURL, {
+ method: request.method,
+ headers: exportNodeCompatibleHeaders(headers),
+ agent
+ });
+}
+
+/**
+ * abort-error.js
+ *
+ * AbortError interface for cancelled requests
+ */
+
+/**
+ * Create AbortError instance
+ *
+ * @param String message Error message for human
+ * @return AbortError
+ */
+function AbortError(message) {
+ Error.call(this, message);
+
+ this.type = 'aborted';
+ this.message = message;
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+AbortError.prototype = Object.create(Error.prototype);
+AbortError.prototype.constructor = AbortError;
+AbortError.prototype.name = 'AbortError';
+
+const URL$1 = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
+const PassThrough$1 = Stream.PassThrough;
+
+const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
+ const orig = new URL$1(original).hostname;
+ const dest = new URL$1(destination).hostname;
+
+ return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
+};
+
+/**
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isSameProtocol = function isSameProtocol(destination, original) {
+ const orig = new URL$1(original).protocol;
+ const dest = new URL$1(destination).protocol;
+
+ return orig === dest;
+};
+
+/**
+ * Fetch function
+ *
+ * @param Mixed url Absolute url or Request instance
+ * @param Object opts Fetch options
+ * @return Promise
+ */
+function fetch(url, opts) {
+
+ // allow custom promise
+ if (!fetch.Promise) {
+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
+ }
+
+ Body.Promise = fetch.Promise;
+
+ // wrap http.request into fetch
+ return new fetch.Promise(function (resolve, reject) {
+ // build request object
+ const request = new Request(url, opts);
+ const options = getNodeRequestOptions(request);
+
+ const send = (options.protocol === 'https:' ? https : http).request;
+ const signal = request.signal;
+
+ let response = null;
+
+ const abort = function abort() {
+ let error = new AbortError('The user aborted a request.');
+ reject(error);
+ if (request.body && request.body instanceof Stream.Readable) {
+ destroyStream(request.body, error);
+ }
+ if (!response || !response.body) return;
+ response.body.emit('error', error);
+ };
+
+ if (signal && signal.aborted) {
+ abort();
+ return;
+ }
+
+ const abortAndFinalize = function abortAndFinalize() {
+ abort();
+ finalize();
+ };
+
+ // send request
+ const req = send(options);
+ let reqTimeout;
+
+ if (signal) {
+ signal.addEventListener('abort', abortAndFinalize);
+ }
+
+ function finalize() {
+ req.abort();
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ clearTimeout(reqTimeout);
+ }
+
+ if (request.timeout) {
+ req.once('socket', function (socket) {
+ reqTimeout = setTimeout(function () {
+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
+ finalize();
+ }, request.timeout);
+ });
+ }
+
+ req.on('error', function (err) {
+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+
+ finalize();
+ });
+
+ fixResponseChunkedTransferBadEnding(req, function (err) {
+ if (signal && signal.aborted) {
+ return;
+ }
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+ });
+
+ /* c8 ignore next 18 */
+ if (parseInt(process.version.substring(1)) < 14) {
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
+ // properly handle when the socket close/end events are out of order.
+ req.on('socket', function (s) {
+ s.addListener('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = s.listenerCount('data') > 0;
+
+ // if end happened before close but the socket didn't emit an error, do it now
+ if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ response.body.emit('error', err);
+ }
+ });
+ });
+ }
+
+ req.on('response', function (res) {
+ clearTimeout(reqTimeout);
+
+ const headers = createHeadersLenient(res.headers);
+
+ // HTTP fetch step 5
+ if (fetch.isRedirect(res.statusCode)) {
+ // HTTP fetch step 5.2
+ const location = headers.get('Location');
+
+ // HTTP fetch step 5.3
+ let locationURL = null;
+ try {
+ locationURL = location === null ? null : new URL$1(location, request.url).toString();
+ } catch (err) {
+ // error here can only be invalid URL in Location: header
+ // do not throw when options.redirect == manual
+ // let the user extract the errorneous redirect URL
+ if (request.redirect !== 'manual') {
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
+ finalize();
+ return;
+ }
+ }
+
+ // HTTP fetch step 5.5
+ switch (request.redirect) {
+ case 'error':
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
+ finalize();
+ return;
+ case 'manual':
+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
+ if (locationURL !== null) {
+ // handle corrupted header
+ try {
+ headers.set('Location', locationURL);
+ } catch (err) {
+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
+ reject(err);
+ }
+ }
+ break;
+ case 'follow':
+ // HTTP-redirect fetch step 2
+ if (locationURL === null) {
+ break;
+ }
+
+ // HTTP-redirect fetch step 5
+ if (request.counter >= request.follow) {
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 6 (counter increment)
+ // Create a new Request object.
+ const requestOpts = {
+ headers: new Headers(request.headers),
+ follow: request.follow,
+ counter: request.counter + 1,
+ agent: request.agent,
+ compress: request.compress,
+ method: request.method,
+ body: request.body,
+ signal: request.signal,
+ timeout: request.timeout,
+ size: request.size
+ };
+
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
+ requestOpts.headers.delete(name);
+ }
+ }
+
+ // HTTP-redirect fetch step 9
+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 11
+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
+ requestOpts.method = 'GET';
+ requestOpts.body = undefined;
+ requestOpts.headers.delete('content-length');
+ }
+
+ // HTTP-redirect fetch step 15
+ resolve(fetch(new Request(locationURL, requestOpts)));
+ finalize();
+ return;
+ }
+ }
+
+ // prepare response
+ res.once('end', function () {
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ });
+ let body = res.pipe(new PassThrough$1());
+
+ const response_options = {
+ url: request.url,
+ status: res.statusCode,
+ statusText: res.statusMessage,
+ headers: headers,
+ size: request.size,
+ timeout: request.timeout,
+ counter: request.counter
+ };
+
+ // HTTP-network fetch step 12.1.1.3
+ const codings = headers.get('Content-Encoding');
+
+ // HTTP-network fetch step 12.1.1.4: handle content codings
+
+ // in following scenarios we ignore compression support
+ // 1. compression support is disabled
+ // 2. HEAD request
+ // 3. no Content-Encoding header
+ // 4. no content response (204)
+ // 5. content not modified response (304)
+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // For Node v6+
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ const zlibOptions = {
+ flush: zlib.Z_SYNC_FLUSH,
+ finishFlush: zlib.Z_SYNC_FLUSH
+ };
+
+ // for gzip
+ if (codings == 'gzip' || codings == 'x-gzip') {
+ body = body.pipe(zlib.createGunzip(zlibOptions));
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // for deflate
+ if (codings == 'deflate' || codings == 'x-deflate') {
+ // handle the infamous raw deflate response from old servers
+ // a hack for old IIS and Apache servers
+ const raw = res.pipe(new PassThrough$1());
+ raw.once('data', function (chunk) {
+ // see http://stackoverflow.com/questions/37519828
+ if ((chunk[0] & 0x0F) === 0x08) {
+ body = body.pipe(zlib.createInflate());
+ } else {
+ body = body.pipe(zlib.createInflateRaw());
+ }
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+ raw.on('end', function () {
+ // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
+ if (!response) {
+ response = new Response(body, response_options);
+ resolve(response);
+ }
+ });
+ return;
+ }
+
+ // for br
+ if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
+ body = body.pipe(zlib.createBrotliDecompress());
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // otherwise, use response as-is
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+
+ writeToStream(req, request);
+ });
+}
+function fixResponseChunkedTransferBadEnding(request, errorCallback) {
+ let socket;
+
+ request.on('socket', function (s) {
+ socket = s;
+ });
+
+ request.on('response', function (response) {
+ const headers = response.headers;
+
+ if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
+ response.once('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = socket.listenerCount('data') > 0;
+
+ if (hasDataListener && !hadError) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ errorCallback(err);
+ }
+ });
+ }
+ });
+}
+
+function destroyStream(stream, err) {
+ if (stream.destroy) {
+ stream.destroy(err);
+ } else {
+ // node < 8
+ stream.emit('error', err);
+ stream.end();
+ }
+}
+
+/**
+ * Redirect code matching
+ *
+ * @param Number code Status code
+ * @return Boolean
+ */
+fetch.isRedirect = function (code) {
+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
+};
+
+// expose Promise
+fetch.Promise = global.Promise;
+
+module.exports = exports = fetch;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = exports;
+exports.Headers = Headers;
+exports.Request = Request;
+exports.Response = Response;
+exports.FetchError = FetchError;
+
+
+/***/ }),
+
+/***/ 59440:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var isPlainObject = __nccwpck_require__(63287);
+var universalUserAgent = __nccwpck_require__(45030);
+
+function lowercaseKeys(object) {
+ if (!object) {
+ return {};
+ }
+ return Object.keys(object).reduce((newObj, key) => {
+ newObj[key.toLowerCase()] = object[key];
+ return newObj;
+ }, {});
+}
+
+function mergeDeep(defaults, options) {
+ const result = Object.assign({}, defaults);
+ Object.keys(options).forEach(key => {
+ if (isPlainObject.isPlainObject(options[key])) {
+ if (!(key in defaults)) Object.assign(result, {
+ [key]: options[key]
+ });else result[key] = mergeDeep(defaults[key], options[key]);
+ } else {
+ Object.assign(result, {
+ [key]: options[key]
+ });
+ }
+ });
+ return result;
+}
+
+function removeUndefinedProperties(obj) {
+ for (const key in obj) {
+ if (obj[key] === undefined) {
+ delete obj[key];
+ }
+ }
+ return obj;
+}
+
+function merge(defaults, route, options) {
+ if (typeof route === "string") {
+ let [method, url] = route.split(" ");
+ options = Object.assign(url ? {
+ method,
+ url
+ } : {
+ url: method
+ }, options);
+ } else {
+ options = Object.assign({}, route);
+ }
+ // lowercase header names before merging with defaults to avoid duplicates
+ options.headers = lowercaseKeys(options.headers);
+ // remove properties with undefined values before merging
+ removeUndefinedProperties(options);
+ removeUndefinedProperties(options.headers);
+ const mergedOptions = mergeDeep(defaults || {}, options);
+ // mediaType.previews arrays are merged, instead of overwritten
+ if (defaults && defaults.mediaType.previews.length) {
+ mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
+ }
+ mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
+ return mergedOptions;
+}
+
+function addQueryParameters(url, parameters) {
+ const separator = /\?/.test(url) ? "&" : "?";
+ const names = Object.keys(parameters);
+ if (names.length === 0) {
+ return url;
+ }
+ return url + separator + names.map(name => {
+ if (name === "q") {
+ return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
+ }
+ return `${name}=${encodeURIComponent(parameters[name])}`;
+ }).join("&");
+}
+
+const urlVariableRegex = /\{[^}]+\}/g;
+function removeNonChars(variableName) {
+ return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
+}
+function extractUrlVariableNames(url) {
+ const matches = url.match(urlVariableRegex);
+ if (!matches) {
+ return [];
+ }
+ return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
+}
+
+function omit(object, keysToOmit) {
+ return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
+ obj[key] = object[key];
+ return obj;
+ }, {});
+}
+
+// Based on https://github.com/bramstein/url-template, licensed under BSD
+// TODO: create separate package.
+//
+// Copyright (c) 2012-2014, Bram Stein
+// All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+/* istanbul ignore file */
+function encodeReserved(str) {
+ return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
+ if (!/%[0-9A-Fa-f]/.test(part)) {
+ part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
+ }
+ return part;
+ }).join("");
+}
+function encodeUnreserved(str) {
+ return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+ });
+}
+function encodeValue(operator, value, key) {
+ value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
+ if (key) {
+ return encodeUnreserved(key) + "=" + value;
+ } else {
+ return value;
+ }
+}
+function isDefined(value) {
+ return value !== undefined && value !== null;
+}
+function isKeyOperator(operator) {
+ return operator === ";" || operator === "&" || operator === "?";
+}
+function getValues(context, operator, key, modifier) {
+ var value = context[key],
+ result = [];
+ if (isDefined(value) && value !== "") {
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ value = value.toString();
+ if (modifier && modifier !== "*") {
+ value = value.substring(0, parseInt(modifier, 10));
+ }
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
+ } else {
+ if (modifier === "*") {
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ result.push(encodeValue(operator, value[k], k));
+ }
+ });
+ }
+ } else {
+ const tmp = [];
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ tmp.push(encodeValue(operator, value));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ tmp.push(encodeUnreserved(k));
+ tmp.push(encodeValue(operator, value[k].toString()));
+ }
+ });
+ }
+ if (isKeyOperator(operator)) {
+ result.push(encodeUnreserved(key) + "=" + tmp.join(","));
+ } else if (tmp.length !== 0) {
+ result.push(tmp.join(","));
+ }
+ }
+ }
+ } else {
+ if (operator === ";") {
+ if (isDefined(value)) {
+ result.push(encodeUnreserved(key));
+ }
+ } else if (value === "" && (operator === "&" || operator === "?")) {
+ result.push(encodeUnreserved(key) + "=");
+ } else if (value === "") {
+ result.push("");
+ }
+ }
+ return result;
+}
+function parseUrl(template) {
+ return {
+ expand: expand.bind(null, template)
+ };
+}
+function expand(template, context) {
+ var operators = ["+", "#", ".", "/", ";", "?", "&"];
+ return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
+ if (expression) {
+ let operator = "";
+ const values = [];
+ if (operators.indexOf(expression.charAt(0)) !== -1) {
+ operator = expression.charAt(0);
+ expression = expression.substr(1);
+ }
+ expression.split(/,/g).forEach(function (variable) {
+ var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
+ values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
+ });
+ if (operator && operator !== "+") {
+ var separator = ",";
+ if (operator === "?") {
+ separator = "&";
+ } else if (operator !== "#") {
+ separator = operator;
+ }
+ return (values.length !== 0 ? operator : "") + values.join(separator);
+ } else {
+ return values.join(",");
+ }
+ } else {
+ return encodeReserved(literal);
+ }
+ });
+}
+
+function parse(options) {
+ // https://fetch.spec.whatwg.org/#methods
+ let method = options.method.toUpperCase();
+ // replace :varname with {varname} to make it RFC 6570 compatible
+ let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
+ let headers = Object.assign({}, options.headers);
+ let body;
+ let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]);
+ // extract variable names from URL to calculate remaining variables later
+ const urlVariableNames = extractUrlVariableNames(url);
+ url = parseUrl(url).expand(parameters);
+ if (!/^http/.test(url)) {
+ url = options.baseUrl + url;
+ }
+ const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
+ const remainingParameters = omit(parameters, omittedParameters);
+ const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
+ if (!isBinaryRequest) {
+ if (options.mediaType.format) {
+ // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
+ headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
+ }
+ if (options.mediaType.previews.length) {
+ const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
+ headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
+ const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
+ return `application/vnd.github.${preview}-preview${format}`;
+ }).join(",");
+ }
+ }
+ // for GET/HEAD requests, set URL query parameters from remaining parameters
+ // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
+ if (["GET", "HEAD"].includes(method)) {
+ url = addQueryParameters(url, remainingParameters);
+ } else {
+ if ("data" in remainingParameters) {
+ body = remainingParameters.data;
+ } else {
+ if (Object.keys(remainingParameters).length) {
+ body = remainingParameters;
+ }
+ }
+ }
+ // default content-type for JSON if body is set
+ if (!headers["content-type"] && typeof body !== "undefined") {
+ headers["content-type"] = "application/json; charset=utf-8";
+ }
+ // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
+ // fetch does not allow to set `content-length` header, but we can set body to an empty string
+ if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
+ body = "";
+ }
+ // Only return body/request keys if present
+ return Object.assign({
+ method,
+ url,
+ headers
+ }, typeof body !== "undefined" ? {
+ body
+ } : null, options.request ? {
+ request: options.request
+ } : null);
+}
+
+function endpointWithDefaults(defaults, route, options) {
+ return parse(merge(defaults, route, options));
+}
+
+function withDefaults(oldDefaults, newDefaults) {
+ const DEFAULTS = merge(oldDefaults, newDefaults);
+ const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
+ return Object.assign(endpoint, {
+ DEFAULTS,
+ defaults: withDefaults.bind(null, DEFAULTS),
+ merge: merge.bind(null, DEFAULTS),
+ parse
+ });
+}
+
+const VERSION = "7.0.5";
+
+const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`;
+// DEFAULTS has all properties set that EndpointOptions has, except url.
+// So we use RequestParameters and add method as additional required property.
+const DEFAULTS = {
+ method: "GET",
+ baseUrl: "https://api.github.com",
+ headers: {
+ accept: "application/vnd.github.v3+json",
+ "user-agent": userAgent
+ },
+ mediaType: {
+ format: "",
+ previews: []
+ }
+};
+
+const endpoint = withDefaults(null, DEFAULTS);
+
+exports.endpoint = endpoint;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 88467:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var request = __nccwpck_require__(63758);
+var universalUserAgent = __nccwpck_require__(45030);
+
+const VERSION = "4.8.0";
+
+function _buildMessageForResponseErrors(data) {
+ return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n");
+}
+
+class GraphqlResponseError extends Error {
+ constructor(request, headers, response) {
+ super(_buildMessageForResponseErrors(response));
+ this.request = request;
+ this.headers = headers;
+ this.response = response;
+ this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties.
+
+ this.errors = response.errors;
+ this.data = response.data; // Maintains proper stack trace (only available on V8)
+
+ /* istanbul ignore next */
+
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+ }
+
+}
+
+const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"];
+const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
+const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
+function graphql(request, query, options) {
+ if (options) {
+ if (typeof query === "string" && "query" in options) {
+ return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
+ }
+
+ for (const key in options) {
+ if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
+ return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
+ }
+ }
+
+ const parsedOptions = typeof query === "string" ? Object.assign({
+ query
+ }, options) : query;
+ const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
+ if (NON_VARIABLE_OPTIONS.includes(key)) {
+ result[key] = parsedOptions[key];
+ return result;
+ }
+
+ if (!result.variables) {
+ result.variables = {};
+ }
+
+ result.variables[key] = parsedOptions[key];
+ return result;
+ }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
+ // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
+
+ const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
+
+ if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
+ requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
+ }
+
+ return request(requestOptions).then(response => {
+ if (response.data.errors) {
+ const headers = {};
+
+ for (const key of Object.keys(response.headers)) {
+ headers[key] = response.headers[key];
+ }
+
+ throw new GraphqlResponseError(requestOptions, headers, response.data);
+ }
+
+ return response.data.data;
+ });
+}
+
+function withDefaults(request$1, newDefaults) {
+ const newRequest = request$1.defaults(newDefaults);
+
+ const newApi = (query, options) => {
+ return graphql(newRequest, query, options);
+ };
+
+ return Object.assign(newApi, {
+ defaults: withDefaults.bind(null, newRequest),
+ endpoint: request.request.endpoint
+ });
+}
+
+const graphql$1 = withDefaults(request.request, {
+ headers: {
+ "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ },
+ method: "POST",
+ url: "/graphql"
+});
+function withCustomRequest(customRequest) {
+ return withDefaults(customRequest, {
+ method: "POST",
+ url: "/graphql"
+ });
+}
+
+exports.GraphqlResponseError = GraphqlResponseError;
+exports.graphql = graphql$1;
+exports.withCustomRequest = withCustomRequest;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 49723:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var isPlainObject = __nccwpck_require__(63287);
+var universalUserAgent = __nccwpck_require__(45030);
+
+function lowercaseKeys(object) {
+ if (!object) {
+ return {};
+ }
+
+ return Object.keys(object).reduce((newObj, key) => {
+ newObj[key.toLowerCase()] = object[key];
+ return newObj;
+ }, {});
+}
+
+function mergeDeep(defaults, options) {
+ const result = Object.assign({}, defaults);
+ Object.keys(options).forEach(key => {
+ if (isPlainObject.isPlainObject(options[key])) {
+ if (!(key in defaults)) Object.assign(result, {
+ [key]: options[key]
+ });else result[key] = mergeDeep(defaults[key], options[key]);
+ } else {
+ Object.assign(result, {
+ [key]: options[key]
+ });
+ }
+ });
+ return result;
+}
+
+function removeUndefinedProperties(obj) {
+ for (const key in obj) {
+ if (obj[key] === undefined) {
+ delete obj[key];
+ }
+ }
+
+ return obj;
+}
+
+function merge(defaults, route, options) {
+ if (typeof route === "string") {
+ let [method, url] = route.split(" ");
+ options = Object.assign(url ? {
+ method,
+ url
+ } : {
+ url: method
+ }, options);
+ } else {
+ options = Object.assign({}, route);
+ } // lowercase header names before merging with defaults to avoid duplicates
+
+
+ options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging
+
+ removeUndefinedProperties(options);
+ removeUndefinedProperties(options.headers);
+ const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
+
+ if (defaults && defaults.mediaType.previews.length) {
+ mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
+ }
+
+ mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
+ return mergedOptions;
+}
+
+function addQueryParameters(url, parameters) {
+ const separator = /\?/.test(url) ? "&" : "?";
+ const names = Object.keys(parameters);
+
+ if (names.length === 0) {
+ return url;
+ }
+
+ return url + separator + names.map(name => {
+ if (name === "q") {
+ return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
+ }
+
+ return `${name}=${encodeURIComponent(parameters[name])}`;
+ }).join("&");
+}
+
+const urlVariableRegex = /\{[^}]+\}/g;
+
+function removeNonChars(variableName) {
+ return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
+}
+
+function extractUrlVariableNames(url) {
+ const matches = url.match(urlVariableRegex);
+
+ if (!matches) {
+ return [];
+ }
+
+ return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
+}
+
+function omit(object, keysToOmit) {
+ return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
+ obj[key] = object[key];
+ return obj;
+ }, {});
+}
+
+// Based on https://github.com/bramstein/url-template, licensed under BSD
+// TODO: create separate package.
+//
+// Copyright (c) 2012-2014, Bram Stein
+// All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+// 3. The name of the author may not be used to endorse or promote products
+// derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
+// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/* istanbul ignore file */
+function encodeReserved(str) {
+ return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
+ if (!/%[0-9A-Fa-f]/.test(part)) {
+ part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
+ }
+
+ return part;
+ }).join("");
+}
+
+function encodeUnreserved(str) {
+ return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+ });
+}
+
+function encodeValue(operator, value, key) {
+ value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
+
+ if (key) {
+ return encodeUnreserved(key) + "=" + value;
+ } else {
+ return value;
+ }
+}
+
+function isDefined(value) {
+ return value !== undefined && value !== null;
+}
+
+function isKeyOperator(operator) {
+ return operator === ";" || operator === "&" || operator === "?";
+}
+
+function getValues(context, operator, key, modifier) {
+ var value = context[key],
+ result = [];
+
+ if (isDefined(value) && value !== "") {
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ value = value.toString();
+
+ if (modifier && modifier !== "*") {
+ value = value.substring(0, parseInt(modifier, 10));
+ }
+
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
+ } else {
+ if (modifier === "*") {
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ result.push(encodeValue(operator, value[k], k));
+ }
+ });
+ }
+ } else {
+ const tmp = [];
+
+ if (Array.isArray(value)) {
+ value.filter(isDefined).forEach(function (value) {
+ tmp.push(encodeValue(operator, value));
+ });
+ } else {
+ Object.keys(value).forEach(function (k) {
+ if (isDefined(value[k])) {
+ tmp.push(encodeUnreserved(k));
+ tmp.push(encodeValue(operator, value[k].toString()));
+ }
+ });
+ }
+
+ if (isKeyOperator(operator)) {
+ result.push(encodeUnreserved(key) + "=" + tmp.join(","));
+ } else if (tmp.length !== 0) {
+ result.push(tmp.join(","));
+ }
+ }
+ }
+ } else {
+ if (operator === ";") {
+ if (isDefined(value)) {
+ result.push(encodeUnreserved(key));
+ }
+ } else if (value === "" && (operator === "&" || operator === "?")) {
+ result.push(encodeUnreserved(key) + "=");
+ } else if (value === "") {
+ result.push("");
+ }
+ }
+
+ return result;
+}
+
+function parseUrl(template) {
+ return {
+ expand: expand.bind(null, template)
+ };
+}
+
+function expand(template, context) {
+ var operators = ["+", "#", ".", "/", ";", "?", "&"];
+ return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
+ if (expression) {
+ let operator = "";
+ const values = [];
+
+ if (operators.indexOf(expression.charAt(0)) !== -1) {
+ operator = expression.charAt(0);
+ expression = expression.substr(1);
+ }
+
+ expression.split(/,/g).forEach(function (variable) {
+ var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
+ values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
+ });
+
+ if (operator && operator !== "+") {
+ var separator = ",";
+
+ if (operator === "?") {
+ separator = "&";
+ } else if (operator !== "#") {
+ separator = operator;
+ }
+
+ return (values.length !== 0 ? operator : "") + values.join(separator);
+ } else {
+ return values.join(",");
+ }
+ } else {
+ return encodeReserved(literal);
+ }
+ });
+}
+
+function parse(options) {
+ // https://fetch.spec.whatwg.org/#methods
+ let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
+
+ let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
+ let headers = Object.assign({}, options.headers);
+ let body;
+ let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
+
+ const urlVariableNames = extractUrlVariableNames(url);
+ url = parseUrl(url).expand(parameters);
+
+ if (!/^http/.test(url)) {
+ url = options.baseUrl + url;
+ }
+
+ const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
+ const remainingParameters = omit(parameters, omittedParameters);
+ const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
+
+ if (!isBinaryRequest) {
+ if (options.mediaType.format) {
+ // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
+ headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
+ }
+
+ if (options.mediaType.previews.length) {
+ const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
+ headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
+ const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
+ return `application/vnd.github.${preview}-preview${format}`;
+ }).join(",");
+ }
+ } // for GET/HEAD requests, set URL query parameters from remaining parameters
+ // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
+
+
+ if (["GET", "HEAD"].includes(method)) {
+ url = addQueryParameters(url, remainingParameters);
+ } else {
+ if ("data" in remainingParameters) {
+ body = remainingParameters.data;
+ } else {
+ if (Object.keys(remainingParameters).length) {
+ body = remainingParameters;
+ } else {
+ headers["content-length"] = 0;
+ }
+ }
+ } // default content-type for JSON if body is set
+
+
+ if (!headers["content-type"] && typeof body !== "undefined") {
+ headers["content-type"] = "application/json; charset=utf-8";
+ } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
+ // fetch does not allow to set `content-length` header, but we can set body to an empty string
+
+
+ if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
+ body = "";
+ } // Only return body/request keys if present
+
+
+ return Object.assign({
+ method,
+ url,
+ headers
+ }, typeof body !== "undefined" ? {
+ body
+ } : null, options.request ? {
+ request: options.request
+ } : null);
+}
+
+function endpointWithDefaults(defaults, route, options) {
+ return parse(merge(defaults, route, options));
+}
+
+function withDefaults(oldDefaults, newDefaults) {
+ const DEFAULTS = merge(oldDefaults, newDefaults);
+ const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
+ return Object.assign(endpoint, {
+ DEFAULTS,
+ defaults: withDefaults.bind(null, DEFAULTS),
+ merge: merge.bind(null, DEFAULTS),
+ parse
+ });
+}
+
+const VERSION = "6.0.12";
+
+const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
+// So we use RequestParameters and add method as additional required property.
+
+const DEFAULTS = {
+ method: "GET",
+ baseUrl: "https://api.github.com",
+ headers: {
+ accept: "application/vnd.github.v3+json",
+ "user-agent": userAgent
+ },
+ mediaType: {
+ format: "",
+ previews: []
+ }
+};
+
+const endpoint = withDefaults(null, DEFAULTS);
+
+exports.endpoint = endpoint;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 63758:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var endpoint = __nccwpck_require__(49723);
+var universalUserAgent = __nccwpck_require__(45030);
+var isPlainObject = __nccwpck_require__(63287);
+var nodeFetch = _interopDefault(__nccwpck_require__(55655));
+var requestError = __nccwpck_require__(10537);
+
+const VERSION = "5.6.3";
+
+function getBufferResponse(response) {
+ return response.arrayBuffer();
+}
+
+function fetchWrapper(requestOptions) {
+ const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
+
+ if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
+ requestOptions.body = JSON.stringify(requestOptions.body);
+ }
+
+ let headers = {};
+ let status;
+ let url;
+ const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch;
+ return fetch(requestOptions.url, Object.assign({
+ method: requestOptions.method,
+ body: requestOptions.body,
+ headers: requestOptions.headers,
+ redirect: requestOptions.redirect
+ }, // `requestOptions.request.agent` type is incompatible
+ // see https://github.com/octokit/types.ts/pull/264
+ requestOptions.request)).then(async response => {
+ url = response.url;
+ status = response.status;
+
+ for (const keyAndValue of response.headers) {
+ headers[keyAndValue[0]] = keyAndValue[1];
+ }
+
+ if ("deprecation" in headers) {
+ const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
+ const deprecationLink = matches && matches.pop();
+ log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
+ }
+
+ if (status === 204 || status === 205) {
+ return;
+ } // GitHub API returns 200 for HEAD requests
+
+
+ if (requestOptions.method === "HEAD") {
+ if (status < 400) {
+ return;
+ }
+
+ throw new requestError.RequestError(response.statusText, status, {
+ response: {
+ url,
+ status,
+ headers,
+ data: undefined
+ },
+ request: requestOptions
+ });
+ }
+
+ if (status === 304) {
+ throw new requestError.RequestError("Not modified", status, {
+ response: {
+ url,
+ status,
+ headers,
+ data: await getResponseData(response)
+ },
+ request: requestOptions
+ });
+ }
+
+ if (status >= 400) {
+ const data = await getResponseData(response);
+ const error = new requestError.RequestError(toErrorMessage(data), status, {
+ response: {
+ url,
+ status,
+ headers,
+ data
+ },
+ request: requestOptions
+ });
+ throw error;
+ }
+
+ return getResponseData(response);
+ }).then(data => {
+ return {
+ status,
+ url,
+ headers,
+ data
+ };
+ }).catch(error => {
+ if (error instanceof requestError.RequestError) throw error;
+ throw new requestError.RequestError(error.message, 500, {
+ request: requestOptions
+ });
+ });
+}
+
+async function getResponseData(response) {
+ const contentType = response.headers.get("content-type");
+
+ if (/application\/json/.test(contentType)) {
+ return response.json();
+ }
+
+ if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
+ return response.text();
+ }
+
+ return getBufferResponse(response);
+}
+
+function toErrorMessage(data) {
+ if (typeof data === "string") return data; // istanbul ignore else - just in case
+
+ if ("message" in data) {
+ if (Array.isArray(data.errors)) {
+ return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
+ }
+
+ return data.message;
+ } // istanbul ignore next - just in case
+
+
+ return `Unknown error: ${JSON.stringify(data)}`;
+}
+
+function withDefaults(oldEndpoint, newDefaults) {
+ const endpoint = oldEndpoint.defaults(newDefaults);
+
+ const newApi = function (route, parameters) {
+ const endpointOptions = endpoint.merge(route, parameters);
+
+ if (!endpointOptions.request || !endpointOptions.request.hook) {
+ return fetchWrapper(endpoint.parse(endpointOptions));
+ }
+
+ const request = (route, parameters) => {
+ return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));
+ };
+
+ Object.assign(request, {
+ endpoint,
+ defaults: withDefaults.bind(null, endpoint)
+ });
+ return endpointOptions.request.hook(request, endpointOptions);
+ };
+
+ return Object.assign(newApi, {
+ endpoint,
+ defaults: withDefaults.bind(null, endpoint)
+ });
+}
+
+const request = withDefaults(endpoint.endpoint, {
+ headers: {
+ "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+});
+
+exports.request = request;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 55655:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var Stream = _interopDefault(__nccwpck_require__(12781));
+var http = _interopDefault(__nccwpck_require__(13685));
+var Url = _interopDefault(__nccwpck_require__(57310));
+var whatwgUrl = _interopDefault(__nccwpck_require__(28665));
+var https = _interopDefault(__nccwpck_require__(95687));
+var zlib = _interopDefault(__nccwpck_require__(59796));
+
+// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
+
+// fix for "Readable" isn't a named export issue
+const Readable = Stream.Readable;
+
+const BUFFER = Symbol('buffer');
+const TYPE = Symbol('type');
+
+class Blob {
+ constructor() {
+ this[TYPE] = '';
+
+ const blobParts = arguments[0];
+ const options = arguments[1];
+
+ const buffers = [];
+ let size = 0;
+
+ if (blobParts) {
+ const a = blobParts;
+ const length = Number(a.length);
+ for (let i = 0; i < length; i++) {
+ const element = a[i];
+ let buffer;
+ if (element instanceof Buffer) {
+ buffer = element;
+ } else if (ArrayBuffer.isView(element)) {
+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
+ } else if (element instanceof ArrayBuffer) {
+ buffer = Buffer.from(element);
+ } else if (element instanceof Blob) {
+ buffer = element[BUFFER];
+ } else {
+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));
+ }
+ size += buffer.length;
+ buffers.push(buffer);
+ }
+ }
+
+ this[BUFFER] = Buffer.concat(buffers);
+
+ let type = options && options.type !== undefined && String(options.type).toLowerCase();
+ if (type && !/[^\u0020-\u007E]/.test(type)) {
+ this[TYPE] = type;
+ }
+ }
+ get size() {
+ return this[BUFFER].length;
+ }
+ get type() {
+ return this[TYPE];
+ }
+ text() {
+ return Promise.resolve(this[BUFFER].toString());
+ }
+ arrayBuffer() {
+ const buf = this[BUFFER];
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ return Promise.resolve(ab);
+ }
+ stream() {
+ const readable = new Readable();
+ readable._read = function () {};
+ readable.push(this[BUFFER]);
+ readable.push(null);
+ return readable;
+ }
+ toString() {
+ return '[object Blob]';
+ }
+ slice() {
+ const size = this.size;
+
+ const start = arguments[0];
+ const end = arguments[1];
+ let relativeStart, relativeEnd;
+ if (start === undefined) {
+ relativeStart = 0;
+ } else if (start < 0) {
+ relativeStart = Math.max(size + start, 0);
+ } else {
+ relativeStart = Math.min(start, size);
+ }
+ if (end === undefined) {
+ relativeEnd = size;
+ } else if (end < 0) {
+ relativeEnd = Math.max(size + end, 0);
+ } else {
+ relativeEnd = Math.min(end, size);
+ }
+ const span = Math.max(relativeEnd - relativeStart, 0);
+
+ const buffer = this[BUFFER];
+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
+ const blob = new Blob([], { type: arguments[2] });
+ blob[BUFFER] = slicedBuffer;
+ return blob;
+ }
+}
+
+Object.defineProperties(Blob.prototype, {
+ size: { enumerable: true },
+ type: { enumerable: true },
+ slice: { enumerable: true }
+});
+
+Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
+ value: 'Blob',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * fetch-error.js
+ *
+ * FetchError interface for operational errors
+ */
+
+/**
+ * Create FetchError instance
+ *
+ * @param String message Error message for human
+ * @param String type Error type for machine
+ * @param String systemError For Node.js system error
+ * @return FetchError
+ */
+function FetchError(message, type, systemError) {
+ Error.call(this, message);
+
+ this.message = message;
+ this.type = type;
+
+ // when err.type is `system`, err.code contains system error code
+ if (systemError) {
+ this.code = this.errno = systemError.code;
+ }
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+FetchError.prototype = Object.create(Error.prototype);
+FetchError.prototype.constructor = FetchError;
+FetchError.prototype.name = 'FetchError';
+
+let convert;
+try {
+ convert = (__nccwpck_require__(22877).convert);
+} catch (e) {}
+
+const INTERNALS = Symbol('Body internals');
+
+// fix an issue where "PassThrough" isn't a named export for node <10
+const PassThrough = Stream.PassThrough;
+
+/**
+ * Body mixin
+ *
+ * Ref: https://fetch.spec.whatwg.org/#body
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+function Body(body) {
+ var _this = this;
+
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ _ref$size = _ref.size;
+
+ let size = _ref$size === undefined ? 0 : _ref$size;
+ var _ref$timeout = _ref.timeout;
+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
+
+ if (body == null) {
+ // body is undefined or null
+ body = null;
+ } else if (isURLSearchParams(body)) {
+ // body is a URLSearchParams
+ body = Buffer.from(body.toString());
+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
+ // body is ArrayBuffer
+ body = Buffer.from(body);
+ } else if (ArrayBuffer.isView(body)) {
+ // body is ArrayBufferView
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
+ } else if (body instanceof Stream) ; else {
+ // none of the above
+ // coerce to string then buffer
+ body = Buffer.from(String(body));
+ }
+ this[INTERNALS] = {
+ body,
+ disturbed: false,
+ error: null
+ };
+ this.size = size;
+ this.timeout = timeout;
+
+ if (body instanceof Stream) {
+ body.on('error', function (err) {
+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
+ _this[INTERNALS].error = error;
+ });
+ }
+}
+
+Body.prototype = {
+ get body() {
+ return this[INTERNALS].body;
+ },
+
+ get bodyUsed() {
+ return this[INTERNALS].disturbed;
+ },
+
+ /**
+ * Decode response as ArrayBuffer
+ *
+ * @return Promise
+ */
+ arrayBuffer() {
+ return consumeBody.call(this).then(function (buf) {
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ });
+ },
+
+ /**
+ * Return raw response as Blob
+ *
+ * @return Promise
+ */
+ blob() {
+ let ct = this.headers && this.headers.get('content-type') || '';
+ return consumeBody.call(this).then(function (buf) {
+ return Object.assign(
+ // Prevent copying
+ new Blob([], {
+ type: ct.toLowerCase()
+ }), {
+ [BUFFER]: buf
+ });
+ });
+ },
+
+ /**
+ * Decode response as json
+ *
+ * @return Promise
+ */
+ json() {
+ var _this2 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ try {
+ return JSON.parse(buffer.toString());
+ } catch (err) {
+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
+ }
+ });
+ },
+
+ /**
+ * Decode response as text
+ *
+ * @return Promise
+ */
+ text() {
+ return consumeBody.call(this).then(function (buffer) {
+ return buffer.toString();
+ });
+ },
+
+ /**
+ * Decode response as buffer (non-spec api)
+ *
+ * @return Promise
+ */
+ buffer() {
+ return consumeBody.call(this);
+ },
+
+ /**
+ * Decode response as text, while automatically detecting the encoding and
+ * trying to decode to UTF-8 (non-spec api)
+ *
+ * @return Promise
+ */
+ textConverted() {
+ var _this3 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ return convertBody(buffer, _this3.headers);
+ });
+ }
+};
+
+// In browsers, all properties are enumerable.
+Object.defineProperties(Body.prototype, {
+ body: { enumerable: true },
+ bodyUsed: { enumerable: true },
+ arrayBuffer: { enumerable: true },
+ blob: { enumerable: true },
+ json: { enumerable: true },
+ text: { enumerable: true }
+});
+
+Body.mixIn = function (proto) {
+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {
+ // istanbul ignore else: future proof
+ if (!(name in proto)) {
+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
+ Object.defineProperty(proto, name, desc);
+ }
+ }
+};
+
+/**
+ * Consume and convert an entire Body to a Buffer.
+ *
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
+ *
+ * @return Promise
+ */
+function consumeBody() {
+ var _this4 = this;
+
+ if (this[INTERNALS].disturbed) {
+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
+ }
+
+ this[INTERNALS].disturbed = true;
+
+ if (this[INTERNALS].error) {
+ return Body.Promise.reject(this[INTERNALS].error);
+ }
+
+ let body = this.body;
+
+ // body is null
+ if (body === null) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is blob
+ if (isBlob(body)) {
+ body = body.stream();
+ }
+
+ // body is buffer
+ if (Buffer.isBuffer(body)) {
+ return Body.Promise.resolve(body);
+ }
+
+ // istanbul ignore if: should never happen
+ if (!(body instanceof Stream)) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is stream
+ // get ready to actually consume the body
+ let accum = [];
+ let accumBytes = 0;
+ let abort = false;
+
+ return new Body.Promise(function (resolve, reject) {
+ let resTimeout;
+
+ // allow timeout on slow response body
+ if (_this4.timeout) {
+ resTimeout = setTimeout(function () {
+ abort = true;
+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
+ }, _this4.timeout);
+ }
+
+ // handle stream errors
+ body.on('error', function (err) {
+ if (err.name === 'AbortError') {
+ // if the request was aborted, reject with this Error
+ abort = true;
+ reject(err);
+ } else {
+ // other errors, such as incorrect content-encoding
+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+
+ body.on('data', function (chunk) {
+ if (abort || chunk === null) {
+ return;
+ }
+
+ if (_this4.size && accumBytes + chunk.length > _this4.size) {
+ abort = true;
+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
+ return;
+ }
+
+ accumBytes += chunk.length;
+ accum.push(chunk);
+ });
+
+ body.on('end', function () {
+ if (abort) {
+ return;
+ }
+
+ clearTimeout(resTimeout);
+
+ try {
+ resolve(Buffer.concat(accum, accumBytes));
+ } catch (err) {
+ // handle streams that have accumulated too much data (issue #414)
+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+ });
+}
+
+/**
+ * Detect buffer encoding and convert to target encoding
+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
+ *
+ * @param Buffer buffer Incoming buffer
+ * @param String encoding Target encoding
+ * @return String
+ */
+function convertBody(buffer, headers) {
+ if (typeof convert !== 'function') {
+ throw new Error('The package `encoding` must be installed to use the textConverted() function');
+ }
+
+ const ct = headers.get('content-type');
+ let charset = 'utf-8';
+ let res, str;
+
+ // header
+ if (ct) {
+ res = /charset=([^;]*)/i.exec(ct);
+ }
+
+ // no charset in content type, peek at response body for at most 1024 bytes
+ str = buffer.slice(0, 1024).toString();
+
+ // html5
+ if (!res && str) {
+ res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;
+
+ this[MAP] = Object.create(null);
+
+ if (init instanceof Headers) {
+ const rawHeaders = init.raw();
+ const headerNames = Object.keys(rawHeaders);
+
+ for (const headerName of headerNames) {
+ for (const value of rawHeaders[headerName]) {
+ this.append(headerName, value);
+ }
+ }
+
+ return;
+ }
+
+ // We don't worry about converting prop to ByteString here as append()
+ // will handle it.
+ if (init == null) ; else if (typeof init === 'object') {
+ const method = init[Symbol.iterator];
+ if (method != null) {
+ if (typeof method !== 'function') {
+ throw new TypeError('Header pairs must be iterable');
+ }
+
+ // sequence>
+ // Note: per spec we have to first exhaust the lists then process them
+ const pairs = [];
+ for (const pair of init) {
+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
+ throw new TypeError('Each header pair must be iterable');
+ }
+ pairs.push(Array.from(pair));
+ }
+
+ for (const pair of pairs) {
+ if (pair.length !== 2) {
+ throw new TypeError('Each header pair must be a name/value tuple');
+ }
+ this.append(pair[0], pair[1]);
+ }
+ } else {
+ // record
+ for (const key of Object.keys(init)) {
+ const value = init[key];
+ this.append(key, value);
+ }
+ }
+ } else {
+ throw new TypeError('Provided initializer must be an object');
+ }
+ }
+
+ /**
+ * Return combined header value given name
+ *
+ * @param String name Header name
+ * @return Mixed
+ */
+ get(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key === undefined) {
+ return null;
+ }
+
+ return this[MAP][key].join(', ');
+ }
+
+ /**
+ * Iterate over all headers
+ *
+ * @param Function callback Executed for each item with parameters (value, name, thisArg)
+ * @param Boolean thisArg `this` context for callback function
+ * @return Void
+ */
+ forEach(callback) {
+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
+
+ let pairs = getHeaders(this);
+ let i = 0;
+ while (i < pairs.length) {
+ var _pairs$i = pairs[i];
+ const name = _pairs$i[0],
+ value = _pairs$i[1];
+
+ callback.call(thisArg, value, name, this);
+ pairs = getHeaders(this);
+ i++;
+ }
+ }
+
+ /**
+ * Overwrite header values given name
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ set(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ this[MAP][key !== undefined ? key : name] = [value];
+ }
+
+ /**
+ * Append a value onto existing header
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ append(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ this[MAP][key].push(value);
+ } else {
+ this[MAP][name] = [value];
+ }
+ }
+
+ /**
+ * Check for header name existence
+ *
+ * @param String name Header name
+ * @return Boolean
+ */
+ has(name) {
+ name = `${name}`;
+ validateName(name);
+ return find(this[MAP], name) !== undefined;
+ }
+
+ /**
+ * Delete all header values given name
+ *
+ * @param String name Header name
+ * @return Void
+ */
+ delete(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ delete this[MAP][key];
+ }
+ }
+
+ /**
+ * Return raw headers (non-spec api)
+ *
+ * @return Object
+ */
+ raw() {
+ return this[MAP];
+ }
+
+ /**
+ * Get an iterator on keys.
+ *
+ * @return Iterator
+ */
+ keys() {
+ return createHeadersIterator(this, 'key');
+ }
+
+ /**
+ * Get an iterator on values.
+ *
+ * @return Iterator
+ */
+ values() {
+ return createHeadersIterator(this, 'value');
+ }
+
+ /**
+ * Get an iterator on entries.
+ *
+ * This is the default iterator of the Headers object.
+ *
+ * @return Iterator
+ */
+ [Symbol.iterator]() {
+ return createHeadersIterator(this, 'key+value');
+ }
+}
+Headers.prototype.entries = Headers.prototype[Symbol.iterator];
+
+Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
+ value: 'Headers',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Headers.prototype, {
+ get: { enumerable: true },
+ forEach: { enumerable: true },
+ set: { enumerable: true },
+ append: { enumerable: true },
+ has: { enumerable: true },
+ delete: { enumerable: true },
+ keys: { enumerable: true },
+ values: { enumerable: true },
+ entries: { enumerable: true }
+});
+
+function getHeaders(headers) {
+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
+
+ const keys = Object.keys(headers[MAP]).sort();
+ return keys.map(kind === 'key' ? function (k) {
+ return k.toLowerCase();
+ } : kind === 'value' ? function (k) {
+ return headers[MAP][k].join(', ');
+ } : function (k) {
+ return [k.toLowerCase(), headers[MAP][k].join(', ')];
+ });
+}
+
+const INTERNAL = Symbol('internal');
+
+function createHeadersIterator(target, kind) {
+ const iterator = Object.create(HeadersIteratorPrototype);
+ iterator[INTERNAL] = {
+ target,
+ kind,
+ index: 0
+ };
+ return iterator;
+}
+
+const HeadersIteratorPrototype = Object.setPrototypeOf({
+ next() {
+ // istanbul ignore if
+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
+ throw new TypeError('Value of `this` is not a HeadersIterator');
+ }
+
+ var _INTERNAL = this[INTERNAL];
+ const target = _INTERNAL.target,
+ kind = _INTERNAL.kind,
+ index = _INTERNAL.index;
+
+ const values = getHeaders(target, kind);
+ const len = values.length;
+ if (index >= len) {
+ return {
+ value: undefined,
+ done: true
+ };
+ }
+
+ this[INTERNAL].index = index + 1;
+
+ return {
+ value: values[index],
+ done: false
+ };
+ }
+}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
+
+Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
+ value: 'HeadersIterator',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * Export the Headers object in a form that Node.js can consume.
+ *
+ * @param Headers headers
+ * @return Object
+ */
+function exportNodeCompatibleHeaders(headers) {
+ const obj = Object.assign({ __proto__: null }, headers[MAP]);
+
+ // http.request() only supports string as Host header. This hack makes
+ // specifying custom Host header possible.
+ const hostHeaderKey = find(headers[MAP], 'Host');
+ if (hostHeaderKey !== undefined) {
+ obj[hostHeaderKey] = obj[hostHeaderKey][0];
+ }
+
+ return obj;
+}
+
+/**
+ * Create a Headers object from an object of headers, ignoring those that do
+ * not conform to HTTP grammar productions.
+ *
+ * @param Object obj Object of headers
+ * @return Headers
+ */
+function createHeadersLenient(obj) {
+ const headers = new Headers();
+ for (const name of Object.keys(obj)) {
+ if (invalidTokenRegex.test(name)) {
+ continue;
+ }
+ if (Array.isArray(obj[name])) {
+ for (const val of obj[name]) {
+ if (invalidHeaderCharRegex.test(val)) {
+ continue;
+ }
+ if (headers[MAP][name] === undefined) {
+ headers[MAP][name] = [val];
+ } else {
+ headers[MAP][name].push(val);
+ }
+ }
+ } else if (!invalidHeaderCharRegex.test(obj[name])) {
+ headers[MAP][name] = [obj[name]];
+ }
+ }
+ return headers;
+}
+
+const INTERNALS$1 = Symbol('Response internals');
+
+// fix an issue where "STATUS_CODES" aren't a named export for node <10
+const STATUS_CODES = http.STATUS_CODES;
+
+/**
+ * Response class
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+class Response {
+ constructor() {
+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ Body.call(this, body, opts);
+
+ const status = opts.status || 200;
+ const headers = new Headers(opts.headers);
+
+ if (body != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(body);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ this[INTERNALS$1] = {
+ url: opts.url,
+ status,
+ statusText: opts.statusText || STATUS_CODES[status],
+ headers,
+ counter: opts.counter
+ };
+ }
+
+ get url() {
+ return this[INTERNALS$1].url || '';
+ }
+
+ get status() {
+ return this[INTERNALS$1].status;
+ }
+
+ /**
+ * Convenience property representing if the request ended normally
+ */
+ get ok() {
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
+ }
+
+ get redirected() {
+ return this[INTERNALS$1].counter > 0;
+ }
+
+ get statusText() {
+ return this[INTERNALS$1].statusText;
+ }
+
+ get headers() {
+ return this[INTERNALS$1].headers;
+ }
+
+ /**
+ * Clone this response
+ *
+ * @return Response
+ */
+ clone() {
+ return new Response(clone(this), {
+ url: this.url,
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ ok: this.ok,
+ redirected: this.redirected
+ });
+ }
+}
+
+Body.mixIn(Response.prototype);
+
+Object.defineProperties(Response.prototype, {
+ url: { enumerable: true },
+ status: { enumerable: true },
+ ok: { enumerable: true },
+ redirected: { enumerable: true },
+ statusText: { enumerable: true },
+ headers: { enumerable: true },
+ clone: { enumerable: true }
+});
+
+Object.defineProperty(Response.prototype, Symbol.toStringTag, {
+ value: 'Response',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+const INTERNALS$2 = Symbol('Request internals');
+const URL = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "format", "parse" aren't a named export for node <10
+const parse_url = Url.parse;
+const format_url = Url.format;
+
+/**
+ * Wrapper around `new URL` to handle arbitrary URLs
+ *
+ * @param {string} urlStr
+ * @return {void}
+ */
+function parseURL(urlStr) {
+ /*
+ Check whether the URL is absolute or not
+ Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
+ Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
+ */
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
+ urlStr = new URL(urlStr).toString();
+ }
+
+ // Fallback to old implementation for arbitrary URLs
+ return parse_url(urlStr);
+}
+
+const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
+
+/**
+ * Check if a value is an instance of Request.
+ *
+ * @param Mixed input
+ * @return Boolean
+ */
+function isRequest(input) {
+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
+}
+
+function isAbortSignal(signal) {
+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
+ return !!(proto && proto.constructor.name === 'AbortSignal');
+}
+
+/**
+ * Request class
+ *
+ * @param Mixed input Url or Request instance
+ * @param Object init Custom options
+ * @return Void
+ */
+class Request {
+ constructor(input) {
+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ let parsedURL;
+
+ // normalize input
+ if (!isRequest(input)) {
+ if (input && input.href) {
+ // in order to support Node.js' Url objects; though WHATWG's URL objects
+ // will fall into this branch also (since their `toString()` will return
+ // `href` property anyway)
+ parsedURL = parseURL(input.href);
+ } else {
+ // coerce input to a string before attempting to parse
+ parsedURL = parseURL(`${input}`);
+ }
+ input = {};
+ } else {
+ parsedURL = parseURL(input.url);
+ }
+
+ let method = init.method || input.method || 'GET';
+ method = method.toUpperCase();
+
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
+ throw new TypeError('Request with GET/HEAD method cannot have body');
+ }
+
+ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
+
+ Body.call(this, inputBody, {
+ timeout: init.timeout || input.timeout || 0,
+ size: init.size || input.size || 0
+ });
+
+ const headers = new Headers(init.headers || input.headers || {});
+
+ if (inputBody != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(inputBody);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ let signal = isRequest(input) ? input.signal : null;
+ if ('signal' in init) signal = init.signal;
+
+ if (signal != null && !isAbortSignal(signal)) {
+ throw new TypeError('Expected signal to be an instanceof AbortSignal');
+ }
+
+ this[INTERNALS$2] = {
+ method,
+ redirect: init.redirect || input.redirect || 'follow',
+ headers,
+ parsedURL,
+ signal
+ };
+
+ // node-fetch-only options
+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
+ this.counter = init.counter || input.counter || 0;
+ this.agent = init.agent || input.agent;
+ }
+
+ get method() {
+ return this[INTERNALS$2].method;
+ }
+
+ get url() {
+ return format_url(this[INTERNALS$2].parsedURL);
+ }
+
+ get headers() {
+ return this[INTERNALS$2].headers;
+ }
+
+ get redirect() {
+ return this[INTERNALS$2].redirect;
+ }
+
+ get signal() {
+ return this[INTERNALS$2].signal;
+ }
+
+ /**
+ * Clone this request
+ *
+ * @return Request
+ */
+ clone() {
+ return new Request(this);
+ }
+}
+
+Body.mixIn(Request.prototype);
+
+Object.defineProperty(Request.prototype, Symbol.toStringTag, {
+ value: 'Request',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Request.prototype, {
+ method: { enumerable: true },
+ url: { enumerable: true },
+ headers: { enumerable: true },
+ redirect: { enumerable: true },
+ clone: { enumerable: true },
+ signal: { enumerable: true }
+});
+
+/**
+ * Convert a Request to Node.js http request options.
+ *
+ * @param Request A Request instance
+ * @return Object The options object to be passed to http.request
+ */
+function getNodeRequestOptions(request) {
+ const parsedURL = request[INTERNALS$2].parsedURL;
+ const headers = new Headers(request[INTERNALS$2].headers);
+
+ // fetch step 1.3
+ if (!headers.has('Accept')) {
+ headers.set('Accept', '*/*');
+ }
+
+ // Basic fetch
+ if (!parsedURL.protocol || !parsedURL.hostname) {
+ throw new TypeError('Only absolute URLs are supported');
+ }
+
+ if (!/^https?:$/.test(parsedURL.protocol)) {
+ throw new TypeError('Only HTTP(S) protocols are supported');
+ }
+
+ if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
+ }
+
+ // HTTP-network-or-cache fetch steps 2.4-2.7
+ let contentLengthValue = null;
+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
+ contentLengthValue = '0';
+ }
+ if (request.body != null) {
+ const totalBytes = getTotalBytes(request);
+ if (typeof totalBytes === 'number') {
+ contentLengthValue = String(totalBytes);
+ }
+ }
+ if (contentLengthValue) {
+ headers.set('Content-Length', contentLengthValue);
+ }
+
+ // HTTP-network-or-cache fetch step 2.11
+ if (!headers.has('User-Agent')) {
+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
+ }
+
+ // HTTP-network-or-cache fetch step 2.15
+ if (request.compress && !headers.has('Accept-Encoding')) {
+ headers.set('Accept-Encoding', 'gzip,deflate');
+ }
+
+ let agent = request.agent;
+ if (typeof agent === 'function') {
+ agent = agent(parsedURL);
+ }
+
+ if (!headers.has('Connection') && !agent) {
+ headers.set('Connection', 'close');
+ }
+
+ // HTTP-network fetch step 4.2
+ // chunked encoding is handled by Node.js
+
+ return Object.assign({}, parsedURL, {
+ method: request.method,
+ headers: exportNodeCompatibleHeaders(headers),
+ agent
+ });
+}
+
+/**
+ * abort-error.js
+ *
+ * AbortError interface for cancelled requests
+ */
+
+/**
+ * Create AbortError instance
+ *
+ * @param String message Error message for human
+ * @return AbortError
+ */
+function AbortError(message) {
+ Error.call(this, message);
+
+ this.type = 'aborted';
+ this.message = message;
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+AbortError.prototype = Object.create(Error.prototype);
+AbortError.prototype.constructor = AbortError;
+AbortError.prototype.name = 'AbortError';
+
+const URL$1 = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
+const PassThrough$1 = Stream.PassThrough;
+
+const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
+ const orig = new URL$1(original).hostname;
+ const dest = new URL$1(destination).hostname;
+
+ return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
+};
+
+/**
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isSameProtocol = function isSameProtocol(destination, original) {
+ const orig = new URL$1(original).protocol;
+ const dest = new URL$1(destination).protocol;
+
+ return orig === dest;
+};
+
+/**
+ * Fetch function
+ *
+ * @param Mixed url Absolute url or Request instance
+ * @param Object opts Fetch options
+ * @return Promise
+ */
+function fetch(url, opts) {
+
+ // allow custom promise
+ if (!fetch.Promise) {
+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
+ }
+
+ Body.Promise = fetch.Promise;
+
+ // wrap http.request into fetch
+ return new fetch.Promise(function (resolve, reject) {
+ // build request object
+ const request = new Request(url, opts);
+ const options = getNodeRequestOptions(request);
+
+ const send = (options.protocol === 'https:' ? https : http).request;
+ const signal = request.signal;
+
+ let response = null;
+
+ const abort = function abort() {
+ let error = new AbortError('The user aborted a request.');
+ reject(error);
+ if (request.body && request.body instanceof Stream.Readable) {
+ destroyStream(request.body, error);
+ }
+ if (!response || !response.body) return;
+ response.body.emit('error', error);
+ };
+
+ if (signal && signal.aborted) {
+ abort();
+ return;
+ }
+
+ const abortAndFinalize = function abortAndFinalize() {
+ abort();
+ finalize();
+ };
+
+ // send request
+ const req = send(options);
+ let reqTimeout;
+
+ if (signal) {
+ signal.addEventListener('abort', abortAndFinalize);
+ }
+
+ function finalize() {
+ req.abort();
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ clearTimeout(reqTimeout);
+ }
+
+ if (request.timeout) {
+ req.once('socket', function (socket) {
+ reqTimeout = setTimeout(function () {
+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
+ finalize();
+ }, request.timeout);
+ });
+ }
+
+ req.on('error', function (err) {
+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+
+ finalize();
+ });
+
+ fixResponseChunkedTransferBadEnding(req, function (err) {
+ if (signal && signal.aborted) {
+ return;
+ }
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+ });
+
+ /* c8 ignore next 18 */
+ if (parseInt(process.version.substring(1)) < 14) {
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
+ // properly handle when the socket close/end events are out of order.
+ req.on('socket', function (s) {
+ s.addListener('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = s.listenerCount('data') > 0;
+
+ // if end happened before close but the socket didn't emit an error, do it now
+ if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ response.body.emit('error', err);
+ }
+ });
+ });
+ }
+
+ req.on('response', function (res) {
+ clearTimeout(reqTimeout);
+
+ const headers = createHeadersLenient(res.headers);
+
+ // HTTP fetch step 5
+ if (fetch.isRedirect(res.statusCode)) {
+ // HTTP fetch step 5.2
+ const location = headers.get('Location');
+
+ // HTTP fetch step 5.3
+ let locationURL = null;
+ try {
+ locationURL = location === null ? null : new URL$1(location, request.url).toString();
+ } catch (err) {
+ // error here can only be invalid URL in Location: header
+ // do not throw when options.redirect == manual
+ // let the user extract the errorneous redirect URL
+ if (request.redirect !== 'manual') {
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
+ finalize();
+ return;
+ }
+ }
+
+ // HTTP fetch step 5.5
+ switch (request.redirect) {
+ case 'error':
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
+ finalize();
+ return;
+ case 'manual':
+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
+ if (locationURL !== null) {
+ // handle corrupted header
+ try {
+ headers.set('Location', locationURL);
+ } catch (err) {
+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
+ reject(err);
+ }
+ }
+ break;
+ case 'follow':
+ // HTTP-redirect fetch step 2
+ if (locationURL === null) {
+ break;
+ }
+
+ // HTTP-redirect fetch step 5
+ if (request.counter >= request.follow) {
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 6 (counter increment)
+ // Create a new Request object.
+ const requestOpts = {
+ headers: new Headers(request.headers),
+ follow: request.follow,
+ counter: request.counter + 1,
+ agent: request.agent,
+ compress: request.compress,
+ method: request.method,
+ body: request.body,
+ signal: request.signal,
+ timeout: request.timeout,
+ size: request.size
+ };
+
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
+ requestOpts.headers.delete(name);
+ }
+ }
+
+ // HTTP-redirect fetch step 9
+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 11
+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
+ requestOpts.method = 'GET';
+ requestOpts.body = undefined;
+ requestOpts.headers.delete('content-length');
+ }
+
+ // HTTP-redirect fetch step 15
+ resolve(fetch(new Request(locationURL, requestOpts)));
+ finalize();
+ return;
+ }
+ }
+
+ // prepare response
+ res.once('end', function () {
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ });
+ let body = res.pipe(new PassThrough$1());
+
+ const response_options = {
+ url: request.url,
+ status: res.statusCode,
+ statusText: res.statusMessage,
+ headers: headers,
+ size: request.size,
+ timeout: request.timeout,
+ counter: request.counter
+ };
+
+ // HTTP-network fetch step 12.1.1.3
+ const codings = headers.get('Content-Encoding');
+
+ // HTTP-network fetch step 12.1.1.4: handle content codings
+
+ // in following scenarios we ignore compression support
+ // 1. compression support is disabled
+ // 2. HEAD request
+ // 3. no Content-Encoding header
+ // 4. no content response (204)
+ // 5. content not modified response (304)
+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // For Node v6+
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ const zlibOptions = {
+ flush: zlib.Z_SYNC_FLUSH,
+ finishFlush: zlib.Z_SYNC_FLUSH
+ };
+
+ // for gzip
+ if (codings == 'gzip' || codings == 'x-gzip') {
+ body = body.pipe(zlib.createGunzip(zlibOptions));
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // for deflate
+ if (codings == 'deflate' || codings == 'x-deflate') {
+ // handle the infamous raw deflate response from old servers
+ // a hack for old IIS and Apache servers
+ const raw = res.pipe(new PassThrough$1());
+ raw.once('data', function (chunk) {
+ // see http://stackoverflow.com/questions/37519828
+ if ((chunk[0] & 0x0F) === 0x08) {
+ body = body.pipe(zlib.createInflate());
+ } else {
+ body = body.pipe(zlib.createInflateRaw());
+ }
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+ raw.on('end', function () {
+ // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
+ if (!response) {
+ response = new Response(body, response_options);
+ resolve(response);
+ }
+ });
+ return;
+ }
+
+ // for br
+ if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
+ body = body.pipe(zlib.createBrotliDecompress());
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // otherwise, use response as-is
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+
+ writeToStream(req, request);
+ });
+}
+function fixResponseChunkedTransferBadEnding(request, errorCallback) {
+ let socket;
+
+ request.on('socket', function (s) {
+ socket = s;
+ });
+
+ request.on('response', function (response) {
+ const headers = response.headers;
+
+ if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
+ response.once('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = socket.listenerCount('data') > 0;
+
+ if (hasDataListener && !hadError) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ errorCallback(err);
+ }
+ });
+ }
+ });
+}
+
+function destroyStream(stream, err) {
+ if (stream.destroy) {
+ stream.destroy(err);
+ } else {
+ // node < 8
+ stream.emit('error', err);
+ stream.end();
+ }
+}
+
+/**
+ * Redirect code matching
+ *
+ * @param Number code Status code
+ * @return Boolean
+ */
+fetch.isRedirect = function (code) {
+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
+};
+
+// expose Promise
+fetch.Promise = global.Promise;
+
+module.exports = exports = fetch;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = exports;
+exports.Headers = Headers;
+exports.Request = Request;
+exports.Response = Response;
+exports.FetchError = FetchError;
+
+
+/***/ }),
+
+/***/ 51017:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function oauthAuthorizationUrl(options) {
+ const clientType = options.clientType || "oauth-app";
+ const baseUrl = options.baseUrl || "https://github.com";
+ const result = {
+ clientType,
+ allowSignup: options.allowSignup === false ? false : true,
+ clientId: options.clientId,
+ login: options.login || null,
+ redirectUrl: options.redirectUrl || null,
+ state: options.state || Math.random().toString(36).substr(2),
+ url: ""
+ };
+
+ if (clientType === "oauth-app") {
+ const scopes = "scopes" in options ? options.scopes : [];
+ result.scopes = typeof scopes === "string" ? scopes.split(/[,\s]+/).filter(Boolean) : scopes;
+ }
+
+ result.url = urlBuilderAuthorize(`${baseUrl}/login/oauth/authorize`, result);
+ return result;
+}
+
+function urlBuilderAuthorize(base, options) {
+ const map = {
+ allowSignup: "allow_signup",
+ clientId: "client_id",
+ login: "login",
+ redirectUrl: "redirect_uri",
+ scopes: "scope",
+ state: "state"
+ };
+ let url = base;
+ Object.keys(map) // Filter out keys that are null and remove the url key
+ .filter(k => options[k] !== null) // Filter out empty scopes array
+ .filter(k => {
+ if (k !== "scopes") return true;
+ if (options.clientType === "github-app") return false;
+ return !Array.isArray(options[k]) || options[k].length > 0;
+ }) // Map Array with the proper URL parameter names and change the value to a string using template strings
+ // @ts-ignore
+ .map(key => [map[key], `${options[key]}`]) // Finally, build the URL
+ .forEach(([key, value], index) => {
+ url += index === 0 ? `?` : "&";
+ url += `${key}=${encodeURIComponent(value)}`;
+ });
+ return url;
+}
+
+exports.oauthAuthorizationUrl = oauthAuthorizationUrl;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 88445:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var oauthAuthorizationUrl = __nccwpck_require__(51017);
+var request = __nccwpck_require__(36234);
+var requestError = __nccwpck_require__(32434);
+var btoa = _interopDefault(__nccwpck_require__(72358));
+
+const VERSION = "2.0.5";
+
+function requestToOAuthBaseUrl(request) {
+ const endpointDefaults = request.endpoint.DEFAULTS;
+ return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", "");
+}
+async function oauthRequest(request, route, parameters) {
+ const withOAuthParameters = {
+ baseUrl: requestToOAuthBaseUrl(request),
+ headers: {
+ accept: "application/json"
+ },
+ ...parameters
+ };
+ const response = await request(route, withOAuthParameters);
+ if ("error" in response.data) {
+ const error = new requestError.RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, {
+ request: request.endpoint.merge(route, withOAuthParameters),
+ headers: response.headers
+ });
+ // @ts-ignore add custom response property until https://github.com/octokit/request-error.js/issues/169 is resolved
+ error.response = response;
+ throw error;
+ }
+ return response;
+}
+
+function getWebFlowAuthorizationUrl({
+ request: request$1 = request.request,
+ ...options
+}) {
+ const baseUrl = requestToOAuthBaseUrl(request$1);
+ // @ts-expect-error TypeScript wants `clientType` to be set explicitly ¯\_(ツ)_/¯
+ return oauthAuthorizationUrl.oauthAuthorizationUrl({
+ ...options,
+ baseUrl
+ });
+}
+
+async function exchangeWebFlowCode(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const response = await oauthRequest(request$1, "POST /login/oauth/access_token", {
+ client_id: options.clientId,
+ client_secret: options.clientSecret,
+ code: options.code,
+ redirect_uri: options.redirectUrl
+ });
+ const authentication = {
+ clientType: options.clientType,
+ clientId: options.clientId,
+ clientSecret: options.clientSecret,
+ token: response.data.access_token,
+ scopes: response.data.scope.split(/\s+/).filter(Boolean)
+ };
+ if (options.clientType === "github-app") {
+ if ("refresh_token" in response.data) {
+ const apiTimeInMs = new Date(response.headers.date).getTime();
+ authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in);
+ }
+ delete authentication.scopes;
+ }
+ return {
+ ...response,
+ authentication
+ };
+}
+function toTimestamp(apiTimeInMs, expirationInSeconds) {
+ return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString();
+}
+
+async function createDeviceCode(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const parameters = {
+ client_id: options.clientId
+ };
+ if ("scopes" in options && Array.isArray(options.scopes)) {
+ parameters.scope = options.scopes.join(" ");
+ }
+ return oauthRequest(request$1, "POST /login/device/code", parameters);
+}
+
+async function exchangeDeviceCode(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const response = await oauthRequest(request$1, "POST /login/oauth/access_token", {
+ client_id: options.clientId,
+ device_code: options.code,
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
+ });
+ const authentication = {
+ clientType: options.clientType,
+ clientId: options.clientId,
+ token: response.data.access_token,
+ scopes: response.data.scope.split(/\s+/).filter(Boolean)
+ };
+ if ("clientSecret" in options) {
+ authentication.clientSecret = options.clientSecret;
+ }
+ if (options.clientType === "github-app") {
+ if ("refresh_token" in response.data) {
+ const apiTimeInMs = new Date(response.headers.date).getTime();
+ authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp$1(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp$1(apiTimeInMs, response.data.refresh_token_expires_in);
+ }
+ delete authentication.scopes;
+ }
+ return {
+ ...response,
+ authentication
+ };
+}
+function toTimestamp$1(apiTimeInMs, expirationInSeconds) {
+ return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString();
+}
+
+async function checkToken(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const response = await request$1("POST /applications/{client_id}/token", {
+ headers: {
+ authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}`
+ },
+ client_id: options.clientId,
+ access_token: options.token
+ });
+ const authentication = {
+ clientType: options.clientType,
+ clientId: options.clientId,
+ clientSecret: options.clientSecret,
+ token: options.token,
+ scopes: response.data.scopes
+ };
+ if (response.data.expires_at) authentication.expiresAt = response.data.expires_at;
+ if (options.clientType === "github-app") {
+ delete authentication.scopes;
+ }
+ return {
+ ...response,
+ authentication
+ };
+}
+
+async function refreshToken(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const response = await oauthRequest(request$1, "POST /login/oauth/access_token", {
+ client_id: options.clientId,
+ client_secret: options.clientSecret,
+ grant_type: "refresh_token",
+ refresh_token: options.refreshToken
+ });
+ const apiTimeInMs = new Date(response.headers.date).getTime();
+ const authentication = {
+ clientType: "github-app",
+ clientId: options.clientId,
+ clientSecret: options.clientSecret,
+ token: response.data.access_token,
+ refreshToken: response.data.refresh_token,
+ expiresAt: toTimestamp$2(apiTimeInMs, response.data.expires_in),
+ refreshTokenExpiresAt: toTimestamp$2(apiTimeInMs, response.data.refresh_token_expires_in)
+ };
+ return {
+ ...response,
+ authentication
+ };
+}
+function toTimestamp$2(apiTimeInMs, expirationInSeconds) {
+ return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString();
+}
+
+async function scopeToken(options) {
+ const {
+ request: optionsRequest,
+ clientType,
+ clientId,
+ clientSecret,
+ token,
+ ...requestOptions
+ } = options;
+ const request$1 = optionsRequest || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const response = await request$1("POST /applications/{client_id}/token/scoped", {
+ headers: {
+ authorization: `basic ${btoa(`${clientId}:${clientSecret}`)}`
+ },
+ client_id: clientId,
+ access_token: token,
+ ...requestOptions
+ });
+ const authentication = Object.assign({
+ clientType,
+ clientId,
+ clientSecret,
+ token: response.data.token
+ }, response.data.expires_at ? {
+ expiresAt: response.data.expires_at
+ } : {});
+ return {
+ ...response,
+ authentication
+ };
+}
+
+async function resetToken(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const auth = btoa(`${options.clientId}:${options.clientSecret}`);
+ const response = await request$1("PATCH /applications/{client_id}/token", {
+ headers: {
+ authorization: `basic ${auth}`
+ },
+ client_id: options.clientId,
+ access_token: options.token
+ });
+ const authentication = {
+ clientType: options.clientType,
+ clientId: options.clientId,
+ clientSecret: options.clientSecret,
+ token: response.data.token,
+ scopes: response.data.scopes
+ };
+ if (response.data.expires_at) authentication.expiresAt = response.data.expires_at;
+ if (options.clientType === "github-app") {
+ delete authentication.scopes;
+ }
+ return {
+ ...response,
+ authentication
+ };
+}
+
+async function deleteToken(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const auth = btoa(`${options.clientId}:${options.clientSecret}`);
+ return request$1("DELETE /applications/{client_id}/token", {
+ headers: {
+ authorization: `basic ${auth}`
+ },
+ client_id: options.clientId,
+ access_token: options.token
+ });
+}
+
+async function deleteAuthorization(options) {
+ const request$1 = options.request || /* istanbul ignore next: we always pass a custom request in tests */
+ request.request;
+ const auth = btoa(`${options.clientId}:${options.clientSecret}`);
+ return request$1("DELETE /applications/{client_id}/grant", {
+ headers: {
+ authorization: `basic ${auth}`
+ },
+ client_id: options.clientId,
+ access_token: options.token
+ });
+}
+
+exports.VERSION = VERSION;
+exports.checkToken = checkToken;
+exports.createDeviceCode = createDeviceCode;
+exports.deleteAuthorization = deleteAuthorization;
+exports.deleteToken = deleteToken;
+exports.exchangeDeviceCode = exchangeDeviceCode;
+exports.exchangeWebFlowCode = exchangeWebFlowCode;
+exports.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrl;
+exports.refreshToken = refreshToken;
+exports.resetToken = resetToken;
+exports.scopeToken = scopeToken;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 32434:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var deprecation = __nccwpck_require__(58932);
+var once = _interopDefault(__nccwpck_require__(1223));
+
+const logOnceCode = once(deprecation => console.warn(deprecation));
+const logOnceHeaders = once(deprecation => console.warn(deprecation));
+/**
+ * Error with extra properties to help with debugging
+ */
+class RequestError extends Error {
+ constructor(message, statusCode, options) {
+ super(message);
+ // Maintains proper stack trace (only available on V8)
+ /* istanbul ignore next */
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+ this.name = "HttpError";
+ this.status = statusCode;
+ let headers;
+ if ("headers" in options && typeof options.headers !== "undefined") {
+ headers = options.headers;
+ }
+ if ("response" in options) {
+ this.response = options.response;
+ headers = options.response.headers;
+ }
+ // redact request credentials without mutating original request options
+ const requestCopy = Object.assign({}, options.request);
+ if (options.request.headers.authorization) {
+ requestCopy.headers = Object.assign({}, options.request.headers, {
+ authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
+ });
+ }
+ requestCopy.url = requestCopy.url
+ // client_id & client_secret can be passed as URL query parameters to increase rate limit
+ // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
+ .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]")
+ // OAuth tokens can be passed as URL query parameters, although it is not recommended
+ // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
+ .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
+ this.request = requestCopy;
+ // deprecations
+ Object.defineProperty(this, "code", {
+ get() {
+ logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
+ return statusCode;
+ }
+ });
+ Object.defineProperty(this, "headers", {
+ get() {
+ logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
+ return headers || {};
+ }
+ });
+ }
+}
+
+exports.RequestError = RequestError;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 25823:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var requestError = __nccwpck_require__(10537);
+
+const VERSION = "1.3.0";
+
+function enterpriseCompatibility(octokit) {
+ octokit.hook.wrap("request", async (request, options) => {
+ // TODO: implement fix for #62 here
+ // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60
+ if (/\/orgs\/[^/]+\/teams/.test(options.url)) {
+ try {
+ return await request(options);
+ } catch (error) {
+ if (error.status !== 404) {
+ throw error;
+ }
+
+ if (!error.response || !error.response.headers["x-github-enterprise-version"]) {
+ throw error;
+ }
+
+ const deprecatedUrl = options.url.replace(/\/orgs\/[^/]+\/teams\/[^/]+/, "/teams/{team_id}");
+ throw new requestError.RequestError(`"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, 404, {
+ request: options
+ });
+ }
+ }
+
+ return request(options);
+ });
+}
+enterpriseCompatibility.VERSION = VERSION;
+
+exports.enterpriseCompatibility = enterpriseCompatibility;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 64193:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+const VERSION = "2.21.3";
+
+function ownKeys(object, enumerableOnly) {
+ var keys = Object.keys(object);
+
+ if (Object.getOwnPropertySymbols) {
+ var symbols = Object.getOwnPropertySymbols(object);
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
+ })), keys.push.apply(keys, symbols);
+ }
+
+ return keys;
+}
+
+function _objectSpread2(target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = null != arguments[i] ? arguments[i] : {};
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
+ _defineProperty(target, key, source[key]);
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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;
+}
+
+/**
+ * Some “list” response that can be paginated have a different response structure
+ *
+ * They have a `total_count` key in the response (search also has `incomplete_results`,
+ * /installation/repositories also has `repository_selection`), as well as a key with
+ * the list of the items which name varies from endpoint to endpoint.
+ *
+ * Octokit normalizes these responses so that paginated results are always returned following
+ * the same structure. One challenge is that if the list response has only one page, no Link
+ * header is provided, so this header alone is not sufficient to check wether a response is
+ * paginated or not.
+ *
+ * We check if a "total_count" key is present in the response data, but also make sure that
+ * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would
+ * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
+ */
+function normalizePaginatedListResponse(response) {
+ // endpoints can respond with 204 if repository is empty
+ if (!response.data) {
+ return _objectSpread2(_objectSpread2({}, response), {}, {
+ data: []
+ });
+ }
+
+ const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
+ if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way
+ // to retrieve the same information.
+
+ const incompleteResults = response.data.incomplete_results;
+ const repositorySelection = response.data.repository_selection;
+ const totalCount = response.data.total_count;
+ delete response.data.incomplete_results;
+ delete response.data.repository_selection;
+ delete response.data.total_count;
+ const namespaceKey = Object.keys(response.data)[0];
+ const data = response.data[namespaceKey];
+ response.data = data;
+
+ if (typeof incompleteResults !== "undefined") {
+ response.data.incomplete_results = incompleteResults;
+ }
+
+ if (typeof repositorySelection !== "undefined") {
+ response.data.repository_selection = repositorySelection;
+ }
+
+ response.data.total_count = totalCount;
+ return response;
+}
+
+function iterator(octokit, route, parameters) {
+ const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
+ const requestMethod = typeof route === "function" ? route : octokit.request;
+ const method = options.method;
+ const headers = options.headers;
+ let url = options.url;
+ return {
+ [Symbol.asyncIterator]: () => ({
+ async next() {
+ if (!url) return {
+ done: true
+ };
+
+ try {
+ const response = await requestMethod({
+ method,
+ url,
+ headers
+ });
+ const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format:
+ // '; rel="next", ; rel="last"'
+ // sets `url` to undefined if "next" URL is not present or `link` header is not set
+
+ url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
+ return {
+ value: normalizedResponse
+ };
+ } catch (error) {
+ if (error.status !== 409) throw error;
+ url = "";
+ return {
+ value: {
+ status: 200,
+ headers: {},
+ data: []
+ }
+ };
+ }
+ }
+
+ })
+ };
+}
+
+function paginate(octokit, route, parameters, mapFn) {
+ if (typeof parameters === "function") {
+ mapFn = parameters;
+ parameters = undefined;
+ }
+
+ return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn);
+}
+
+function gather(octokit, results, iterator, mapFn) {
+ return iterator.next().then(result => {
+ if (result.done) {
+ return results;
+ }
+
+ let earlyExit = false;
+
+ function done() {
+ earlyExit = true;
+ }
+
+ results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data);
+
+ if (earlyExit) {
+ return results;
+ }
+
+ return gather(octokit, results, iterator, mapFn);
+ });
+}
+
+const composePaginateRest = Object.assign(paginate, {
+ iterator
+});
+
+const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/audit-log", "GET /enterprises/{enterprise}/secret-scanning/alerts", "GET /enterprises/{enterprise}/settings/billing/advanced-security", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /licenses", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/cache/usage-by-repository", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/audit-log", "GET /orgs/{org}/blocks", "GET /orgs/{org}/code-scanning/alerts", "GET /orgs/{org}/codespaces", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/dependabot/secrets", "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", "GET /orgs/{org}/events", "GET /orgs/{org}/external-groups", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/settings/billing/advanced-security", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/caches", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/codespaces", "GET /repos/{owner}/{repo}/codespaces/devcontainers", "GET /repos/{owner}/{repo}/codespaces/secrets", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/status", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/dependabot/secrets", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/environments", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repos/{owner}/{repo}/topics", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/codespaces", "GET /user/codespaces/secrets", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/packages/{package_type}/{package_name}/versions", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/packages", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"];
+
+function isPaginatingEndpoint(arg) {
+ if (typeof arg === "string") {
+ return paginatingEndpoints.includes(arg);
+ } else {
+ return false;
+ }
+}
+
+/**
+ * @param octokit Octokit instance
+ * @param options Options passed to Octokit constructor
+ */
+
+function paginateRest(octokit) {
+ return {
+ paginate: Object.assign(paginate.bind(null, octokit), {
+ iterator: iterator.bind(null, octokit)
+ })
+ };
+}
+paginateRest.VERSION = VERSION;
+
+exports.composePaginateRest = composePaginateRest;
+exports.isPaginatingEndpoint = isPaginatingEndpoint;
+exports.paginateRest = paginateRest;
+exports.paginatingEndpoints = paginatingEndpoints;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 83044:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+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 _objectSpread2(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;
+}
+
+const Endpoints = {
+ actions: {
+ addCustomLabelsToSelfHostedRunnerForOrg: ["POST /orgs/{org}/actions/runners/{runner_id}/labels"],
+ addCustomLabelsToSelfHostedRunnerForRepo: ["POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
+ addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
+ approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"],
+ cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"],
+ createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
+ createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
+ createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
+ createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"],
+ createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"],
+ createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
+ createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"],
+ createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"],
+ deleteActionsCacheById: ["DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"],
+ deleteActionsCacheByKey: ["DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"],
+ deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
+ deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
+ deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
+ deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
+ deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"],
+ deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"],
+ deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
+ deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
+ disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"],
+ disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"],
+ downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"],
+ downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"],
+ downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"],
+ downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"],
+ enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"],
+ enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"],
+ getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"],
+ getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"],
+ getActionsCacheUsageByRepoForOrg: ["GET /orgs/{org}/actions/cache/usage-by-repository"],
+ getActionsCacheUsageForEnterprise: ["GET /enterprises/{enterprise}/actions/cache/usage"],
+ getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"],
+ getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"],
+ getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"],
+ getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
+ getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"],
+ getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"],
+ getGithubActionsDefaultWorkflowPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/workflow"],
+ getGithubActionsDefaultWorkflowPermissionsOrganization: ["GET /orgs/{org}/actions/permissions/workflow"],
+ getGithubActionsDefaultWorkflowPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/workflow"],
+ getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"],
+ getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"],
+ getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
+ getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
+ getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
+ getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
+ getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, {
+ renamed: ["actions", "getGithubActionsPermissionsRepository"]
+ }],
+ getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
+ getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
+ getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"],
+ getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
+ getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"],
+ getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
+ getWorkflowAccessToRepository: ["GET /repos/{owner}/{repo}/actions/permissions/access"],
+ getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
+ getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"],
+ getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"],
+ getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"],
+ listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
+ listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"],
+ listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"],
+ listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"],
+ listLabelsForSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}/labels"],
+ listLabelsForSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
+ listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
+ listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
+ listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
+ listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
+ listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"],
+ listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"],
+ listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"],
+ listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
+ listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
+ listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"],
+ listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"],
+ listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
+ reRunJobForWorkflowRun: ["POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"],
+ reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
+ reRunWorkflowFailedJobs: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"],
+ removeAllCustomLabelsFromSelfHostedRunnerForOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}/labels"],
+ removeAllCustomLabelsFromSelfHostedRunnerForRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
+ removeCustomLabelFromSelfHostedRunnerForOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"],
+ removeCustomLabelFromSelfHostedRunnerForRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"],
+ removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"],
+ reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"],
+ setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"],
+ setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"],
+ setCustomLabelsForSelfHostedRunnerForOrg: ["PUT /orgs/{org}/actions/runners/{runner_id}/labels"],
+ setCustomLabelsForSelfHostedRunnerForRepo: ["PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"],
+ setGithubActionsDefaultWorkflowPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/workflow"],
+ setGithubActionsDefaultWorkflowPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions/workflow"],
+ setGithubActionsDefaultWorkflowPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/workflow"],
+ setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"],
+ setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"],
+ setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"],
+ setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"],
+ setWorkflowAccessToRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/access"]
+ },
+ activity: {
+ checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
+ deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
+ deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"],
+ getFeeds: ["GET /feeds"],
+ getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
+ getThread: ["GET /notifications/threads/{thread_id}"],
+ getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"],
+ listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
+ listNotificationsForAuthenticatedUser: ["GET /notifications"],
+ listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"],
+ listPublicEvents: ["GET /events"],
+ listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
+ listPublicEventsForUser: ["GET /users/{username}/events/public"],
+ listPublicOrgEvents: ["GET /orgs/{org}/events"],
+ listReceivedEventsForUser: ["GET /users/{username}/received_events"],
+ listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"],
+ listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
+ listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"],
+ listReposStarredByAuthenticatedUser: ["GET /user/starred"],
+ listReposStarredByUser: ["GET /users/{username}/starred"],
+ listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
+ listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
+ listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
+ listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
+ markNotificationsAsRead: ["PUT /notifications"],
+ markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
+ markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
+ setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
+ setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"],
+ starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
+ unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
+ },
+ apps: {
+ addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, {
+ renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"]
+ }],
+ addRepoToInstallationForAuthenticatedUser: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"],
+ checkToken: ["POST /applications/{client_id}/token"],
+ createFromManifest: ["POST /app-manifests/{code}/conversions"],
+ createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"],
+ deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
+ deleteInstallation: ["DELETE /app/installations/{installation_id}"],
+ deleteToken: ["DELETE /applications/{client_id}/token"],
+ getAuthenticated: ["GET /app"],
+ getBySlug: ["GET /apps/{app_slug}"],
+ getInstallation: ["GET /app/installations/{installation_id}"],
+ getOrgInstallation: ["GET /orgs/{org}/installation"],
+ getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"],
+ getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"],
+ getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"],
+ getUserInstallation: ["GET /users/{username}/installation"],
+ getWebhookConfigForApp: ["GET /app/hook/config"],
+ getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"],
+ listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
+ listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"],
+ listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"],
+ listInstallations: ["GET /app/installations"],
+ listInstallationsForAuthenticatedUser: ["GET /user/installations"],
+ listPlans: ["GET /marketplace_listing/plans"],
+ listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
+ listReposAccessibleToInstallation: ["GET /installation/repositories"],
+ listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
+ listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"],
+ listWebhookDeliveries: ["GET /app/hook/deliveries"],
+ redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"],
+ removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, {
+ renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"]
+ }],
+ removeRepoFromInstallationForAuthenticatedUser: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"],
+ resetToken: ["PATCH /applications/{client_id}/token"],
+ revokeInstallationAccessToken: ["DELETE /installation/token"],
+ scopeToken: ["POST /applications/{client_id}/token/scoped"],
+ suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
+ unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"],
+ updateWebhookConfigForApp: ["PATCH /app/hook/config"]
+ },
+ billing: {
+ getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
+ getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"],
+ getGithubAdvancedSecurityBillingGhe: ["GET /enterprises/{enterprise}/settings/billing/advanced-security"],
+ getGithubAdvancedSecurityBillingOrg: ["GET /orgs/{org}/settings/billing/advanced-security"],
+ getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
+ getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"],
+ getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"],
+ getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"]
+ },
+ checks: {
+ create: ["POST /repos/{owner}/{repo}/check-runs"],
+ createSuite: ["POST /repos/{owner}/{repo}/check-suites"],
+ get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],
+ getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],
+ listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"],
+ listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],
+ listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"],
+ listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],
+ rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"],
+ rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"],
+ setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"],
+ update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
+ },
+ codeScanning: {
+ deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"],
+ getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, {
+ renamedParameters: {
+ alert_id: "alert_number"
+ }
+ }],
+ getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"],
+ getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
+ listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"],
+ listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"],
+ listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
+ listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, {
+ renamed: ["codeScanning", "listAlertInstances"]
+ }],
+ listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
+ updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"],
+ uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
+ },
+ codesOfConduct: {
+ getAllCodesOfConduct: ["GET /codes_of_conduct"],
+ getConductCode: ["GET /codes_of_conduct/{key}"]
+ },
+ codespaces: {
+ addRepositoryForSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],
+ codespaceMachinesForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}/machines"],
+ createForAuthenticatedUser: ["POST /user/codespaces"],
+ createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
+ createOrUpdateSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}"],
+ createWithPrForAuthenticatedUser: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"],
+ createWithRepoForAuthenticatedUser: ["POST /repos/{owner}/{repo}/codespaces"],
+ deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"],
+ deleteFromOrganization: ["DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"],
+ deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
+ deleteSecretForAuthenticatedUser: ["DELETE /user/codespaces/secrets/{secret_name}"],
+ exportForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/exports"],
+ getExportDetailsForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}/exports/{export_id}"],
+ getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"],
+ getPublicKeyForAuthenticatedUser: ["GET /user/codespaces/secrets/public-key"],
+ getRepoPublicKey: ["GET /repos/{owner}/{repo}/codespaces/secrets/public-key"],
+ getRepoSecret: ["GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"],
+ getSecretForAuthenticatedUser: ["GET /user/codespaces/secrets/{secret_name}"],
+ listDevcontainersInRepositoryForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces/devcontainers"],
+ listForAuthenticatedUser: ["GET /user/codespaces"],
+ listInOrganization: ["GET /orgs/{org}/codespaces", {}, {
+ renamedParameters: {
+ org_id: "org"
+ }
+ }],
+ listInRepositoryForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces"],
+ listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"],
+ listRepositoriesForSecretForAuthenticatedUser: ["GET /user/codespaces/secrets/{secret_name}/repositories"],
+ listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"],
+ removeRepositoryForSecretForAuthenticatedUser: ["DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"],
+ repoMachinesForAuthenticatedUser: ["GET /repos/{owner}/{repo}/codespaces/machines"],
+ setRepositoriesForSecretForAuthenticatedUser: ["PUT /user/codespaces/secrets/{secret_name}/repositories"],
+ startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"],
+ stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"],
+ stopInOrganization: ["POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"],
+ updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"]
+ },
+ dependabot: {
+ addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],
+ createOrUpdateOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}"],
+ createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
+ deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],
+ deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
+ getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"],
+ getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"],
+ getRepoPublicKey: ["GET /repos/{owner}/{repo}/dependabot/secrets/public-key"],
+ getRepoSecret: ["GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"],
+ listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"],
+ listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"],
+ listSelectedReposForOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"],
+ removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"],
+ setSelectedReposForOrgSecret: ["PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"]
+ },
+ dependencyGraph: {
+ createRepositorySnapshot: ["POST /repos/{owner}/{repo}/dependency-graph/snapshots"],
+ diffRange: ["GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"]
+ },
+ emojis: {
+ get: ["GET /emojis"]
+ },
+ enterpriseAdmin: {
+ addCustomLabelsToSelfHostedRunnerForEnterprise: ["POST /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
+ disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
+ enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"],
+ getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"],
+ getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"],
+ getServerStatistics: ["GET /enterprise-installation/{enterprise_or_org}/server-statistics"],
+ listLabelsForSelfHostedRunnerForEnterprise: ["GET /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
+ listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"],
+ removeAllCustomLabelsFromSelfHostedRunnerForEnterprise: ["DELETE /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
+ removeCustomLabelFromSelfHostedRunnerForEnterprise: ["DELETE /enterprises/{enterprise}/actions/runners/{runner_id}/labels/{name}"],
+ setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"],
+ setCustomLabelsForSelfHostedRunnerForEnterprise: ["PUT /enterprises/{enterprise}/actions/runners/{runner_id}/labels"],
+ setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"],
+ setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"]
+ },
+ gists: {
+ checkIsStarred: ["GET /gists/{gist_id}/star"],
+ create: ["POST /gists"],
+ createComment: ["POST /gists/{gist_id}/comments"],
+ delete: ["DELETE /gists/{gist_id}"],
+ deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
+ fork: ["POST /gists/{gist_id}/forks"],
+ get: ["GET /gists/{gist_id}"],
+ getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
+ getRevision: ["GET /gists/{gist_id}/{sha}"],
+ list: ["GET /gists"],
+ listComments: ["GET /gists/{gist_id}/comments"],
+ listCommits: ["GET /gists/{gist_id}/commits"],
+ listForUser: ["GET /users/{username}/gists"],
+ listForks: ["GET /gists/{gist_id}/forks"],
+ listPublic: ["GET /gists/public"],
+ listStarred: ["GET /gists/starred"],
+ star: ["PUT /gists/{gist_id}/star"],
+ unstar: ["DELETE /gists/{gist_id}/star"],
+ update: ["PATCH /gists/{gist_id}"],
+ updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
+ },
+ git: {
+ createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
+ createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
+ createRef: ["POST /repos/{owner}/{repo}/git/refs"],
+ createTag: ["POST /repos/{owner}/{repo}/git/tags"],
+ createTree: ["POST /repos/{owner}/{repo}/git/trees"],
+ deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
+ getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
+ getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
+ getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
+ getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
+ getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
+ listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
+ updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
+ },
+ gitignore: {
+ getAllTemplates: ["GET /gitignore/templates"],
+ getTemplate: ["GET /gitignore/templates/{name}"]
+ },
+ interactions: {
+ getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
+ getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
+ getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
+ getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, {
+ renamed: ["interactions", "getRestrictionsForAuthenticatedUser"]
+ }],
+ removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
+ removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
+ removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"],
+ removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, {
+ renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"]
+ }],
+ setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
+ setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
+ setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
+ setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, {
+ renamed: ["interactions", "setRestrictionsForAuthenticatedUser"]
+ }]
+ },
+ issues: {
+ addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
+ addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
+ checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
+ create: ["POST /repos/{owner}/{repo}/issues"],
+ createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"],
+ createLabel: ["POST /repos/{owner}/{repo}/labels"],
+ createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
+ deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"],
+ deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
+ deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"],
+ get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
+ getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
+ getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
+ getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
+ getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
+ list: ["GET /issues"],
+ listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
+ listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
+ listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
+ listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
+ listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
+ listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"],
+ listForAuthenticatedUser: ["GET /user/issues"],
+ listForOrg: ["GET /orgs/{org}/issues"],
+ listForRepo: ["GET /repos/{owner}/{repo}/issues"],
+ listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"],
+ listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
+ listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"],
+ listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
+ lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
+ removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"],
+ removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"],
+ removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"],
+ setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
+ unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
+ update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
+ updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
+ updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
+ updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"]
+ },
+ licenses: {
+ get: ["GET /licenses/{license}"],
+ getAllCommonlyUsed: ["GET /licenses"],
+ getForRepo: ["GET /repos/{owner}/{repo}/license"]
+ },
+ markdown: {
+ render: ["POST /markdown"],
+ renderRaw: ["POST /markdown/raw", {
+ headers: {
+ "content-type": "text/plain; charset=utf-8"
+ }
+ }]
+ },
+ meta: {
+ get: ["GET /meta"],
+ getOctocat: ["GET /octocat"],
+ getZen: ["GET /zen"],
+ root: ["GET /"]
+ },
+ migrations: {
+ cancelImport: ["DELETE /repos/{owner}/{repo}/import"],
+ deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"],
+ deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"],
+ downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"],
+ getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"],
+ getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"],
+ getImportStatus: ["GET /repos/{owner}/{repo}/import"],
+ getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"],
+ getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"],
+ getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"],
+ listForAuthenticatedUser: ["GET /user/migrations"],
+ listForOrg: ["GET /orgs/{org}/migrations"],
+ listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"],
+ listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"],
+ listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, {
+ renamed: ["migrations", "listReposForAuthenticatedUser"]
+ }],
+ mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"],
+ setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"],
+ startForAuthenticatedUser: ["POST /user/migrations"],
+ startForOrg: ["POST /orgs/{org}/migrations"],
+ startImport: ["PUT /repos/{owner}/{repo}/import"],
+ unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"],
+ unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"],
+ updateImport: ["PATCH /repos/{owner}/{repo}/import"]
+ },
+ orgs: {
+ blockUser: ["PUT /orgs/{org}/blocks/{username}"],
+ cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
+ checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
+ checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
+ checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
+ convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"],
+ createInvitation: ["POST /orgs/{org}/invitations"],
+ createWebhook: ["POST /orgs/{org}/hooks"],
+ deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
+ get: ["GET /orgs/{org}"],
+ getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
+ getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
+ getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
+ getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"],
+ getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"],
+ list: ["GET /organizations"],
+ listAppInstallations: ["GET /orgs/{org}/installations"],
+ listBlockedUsers: ["GET /orgs/{org}/blocks"],
+ listCustomRoles: ["GET /organizations/{organization_id}/custom_roles"],
+ listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
+ listForAuthenticatedUser: ["GET /user/orgs"],
+ listForUser: ["GET /users/{username}/orgs"],
+ listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
+ listMembers: ["GET /orgs/{org}/members"],
+ listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
+ listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
+ listPendingInvitations: ["GET /orgs/{org}/invitations"],
+ listPublicMembers: ["GET /orgs/{org}/public_members"],
+ listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"],
+ listWebhooks: ["GET /orgs/{org}/hooks"],
+ pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
+ redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
+ removeMember: ["DELETE /orgs/{org}/members/{username}"],
+ removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
+ removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"],
+ removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"],
+ setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
+ setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"],
+ unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
+ update: ["PATCH /orgs/{org}"],
+ updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"],
+ updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
+ updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
+ },
+ packages: {
+ deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"],
+ deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"],
+ deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"],
+ deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
+ deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
+ deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
+ getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, {
+ renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"]
+ }],
+ getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, {
+ renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"]
+ }],
+ getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"],
+ getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"],
+ getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"],
+ getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"],
+ getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"],
+ getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"],
+ getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"],
+ getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
+ getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"],
+ listPackagesForAuthenticatedUser: ["GET /user/packages"],
+ listPackagesForOrganization: ["GET /orgs/{org}/packages"],
+ listPackagesForUser: ["GET /users/{username}/packages"],
+ restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"],
+ restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"],
+ restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"],
+ restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
+ restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"],
+ restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"]
+ },
+ projects: {
+ addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"],
+ createCard: ["POST /projects/columns/{column_id}/cards"],
+ createColumn: ["POST /projects/{project_id}/columns"],
+ createForAuthenticatedUser: ["POST /user/projects"],
+ createForOrg: ["POST /orgs/{org}/projects"],
+ createForRepo: ["POST /repos/{owner}/{repo}/projects"],
+ delete: ["DELETE /projects/{project_id}"],
+ deleteCard: ["DELETE /projects/columns/cards/{card_id}"],
+ deleteColumn: ["DELETE /projects/columns/{column_id}"],
+ get: ["GET /projects/{project_id}"],
+ getCard: ["GET /projects/columns/cards/{card_id}"],
+ getColumn: ["GET /projects/columns/{column_id}"],
+ getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"],
+ listCards: ["GET /projects/columns/{column_id}/cards"],
+ listCollaborators: ["GET /projects/{project_id}/collaborators"],
+ listColumns: ["GET /projects/{project_id}/columns"],
+ listForOrg: ["GET /orgs/{org}/projects"],
+ listForRepo: ["GET /repos/{owner}/{repo}/projects"],
+ listForUser: ["GET /users/{username}/projects"],
+ moveCard: ["POST /projects/columns/cards/{card_id}/moves"],
+ moveColumn: ["POST /projects/columns/{column_id}/moves"],
+ removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"],
+ update: ["PATCH /projects/{project_id}"],
+ updateCard: ["PATCH /projects/columns/cards/{card_id}"],
+ updateColumn: ["PATCH /projects/columns/{column_id}"]
+ },
+ pulls: {
+ checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
+ create: ["POST /repos/{owner}/{repo}/pulls"],
+ createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"],
+ createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
+ createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
+ deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
+ deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
+ dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"],
+ get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
+ getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
+ getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
+ list: ["GET /repos/{owner}/{repo}/pulls"],
+ listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"],
+ listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
+ listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
+ listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
+ listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"],
+ listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
+ listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
+ merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
+ removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
+ requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"],
+ submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"],
+ update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
+ updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"],
+ updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"],
+ updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"]
+ },
+ rateLimit: {
+ get: ["GET /rate_limit"]
+ },
+ reactions: {
+ createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"],
+ createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
+ createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],
+ createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],
+ createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"],
+ createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],
+ createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"],
+ deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"],
+ deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"],
+ deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"],
+ deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"],
+ deleteForRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"],
+ deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"],
+ deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"],
+ listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"],
+ listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
+ listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"],
+ listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"],
+ listForRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}/reactions"],
+ listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"],
+ listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"]
+ },
+ repos: {
+ acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, {
+ renamed: ["repos", "acceptInvitationForAuthenticatedUser"]
+ }],
+ acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"],
+ addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
+ mapToData: "apps"
+ }],
+ addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
+ addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
+ mapToData: "contexts"
+ }],
+ addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
+ mapToData: "teams"
+ }],
+ addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
+ mapToData: "users"
+ }],
+ checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
+ checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"],
+ codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"],
+ compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
+ compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"],
+ createAutolink: ["POST /repos/{owner}/{repo}/autolinks"],
+ createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
+ createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
+ createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
+ createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
+ createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
+ createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
+ createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
+ createForAuthenticatedUser: ["POST /user/repos"],
+ createFork: ["POST /repos/{owner}/{repo}/forks"],
+ createInOrg: ["POST /orgs/{org}/repos"],
+ createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"],
+ createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
+ createPagesSite: ["POST /repos/{owner}/{repo}/pages"],
+ createRelease: ["POST /repos/{owner}/{repo}/releases"],
+ createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"],
+ createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"],
+ createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
+ declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, {
+ renamed: ["repos", "declineInvitationForAuthenticatedUser"]
+ }],
+ declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"],
+ delete: ["DELETE /repos/{owner}/{repo}"],
+ deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
+ deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
+ deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"],
+ deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],
+ deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"],
+ deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
+ deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
+ deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
+ deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"],
+ deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
+ deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"],
+ deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"],
+ deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
+ deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
+ deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"],
+ deleteTagProtection: ["DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}"],
+ deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
+ disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"],
+ disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"],
+ disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"],
+ downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, {
+ renamed: ["repos", "downloadZipballArchive"]
+ }],
+ downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"],
+ downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"],
+ enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"],
+ enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"],
+ enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"],
+ generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"],
+ get: ["GET /repos/{owner}/{repo}"],
+ getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"],
+ getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
+ getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
+ getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"],
+ getAllTopics: ["GET /repos/{owner}/{repo}/topics"],
+ getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"],
+ getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],
+ getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
+ getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"],
+ getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
+ getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
+ getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"],
+ getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
+ getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
+ getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
+ getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
+ getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"],
+ getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"],
+ getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
+ getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
+ getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
+ getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
+ getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"],
+ getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"],
+ getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
+ getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
+ getPages: ["GET /repos/{owner}/{repo}/pages"],
+ getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
+ getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"],
+ getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
+ getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
+ getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
+ getReadme: ["GET /repos/{owner}/{repo}/readme"],
+ getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
+ getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
+ getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
+ getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
+ getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
+ getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"],
+ getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
+ getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
+ getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"],
+ getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
+ getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
+ getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"],
+ getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"],
+ listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"],
+ listBranches: ["GET /repos/{owner}/{repo}/branches"],
+ listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"],
+ listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
+ listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"],
+ listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
+ listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"],
+ listCommits: ["GET /repos/{owner}/{repo}/commits"],
+ listContributors: ["GET /repos/{owner}/{repo}/contributors"],
+ listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
+ listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"],
+ listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
+ listForAuthenticatedUser: ["GET /user/repos"],
+ listForOrg: ["GET /orgs/{org}/repos"],
+ listForUser: ["GET /users/{username}/repos"],
+ listForks: ["GET /repos/{owner}/{repo}/forks"],
+ listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
+ listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
+ listLanguages: ["GET /repos/{owner}/{repo}/languages"],
+ listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
+ listPublic: ["GET /repositories"],
+ listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"],
+ listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"],
+ listReleases: ["GET /repos/{owner}/{repo}/releases"],
+ listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"],
+ listTags: ["GET /repos/{owner}/{repo}/tags"],
+ listTeams: ["GET /repos/{owner}/{repo}/teams"],
+ listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"],
+ listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
+ merge: ["POST /repos/{owner}/{repo}/merges"],
+ mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"],
+ pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
+ redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"],
+ removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
+ mapToData: "apps"
+ }],
+ removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"],
+ removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
+ mapToData: "contexts"
+ }],
+ removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
+ removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
+ mapToData: "teams"
+ }],
+ removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
+ mapToData: "users"
+ }],
+ renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
+ replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"],
+ requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
+ setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"],
+ setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, {
+ mapToData: "apps"
+ }],
+ setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, {
+ mapToData: "contexts"
+ }],
+ setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, {
+ mapToData: "teams"
+ }],
+ setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, {
+ mapToData: "users"
+ }],
+ testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
+ transfer: ["POST /repos/{owner}/{repo}/transfer"],
+ update: ["PATCH /repos/{owner}/{repo}"],
+ updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"],
+ updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
+ updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
+ updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"],
+ updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"],
+ updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
+ updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"],
+ updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, {
+ renamed: ["repos", "updateStatusCheckProtection"]
+ }],
+ updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"],
+ updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
+ updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"],
+ uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", {
+ baseUrl: "https://uploads.github.com"
+ }]
+ },
+ search: {
+ code: ["GET /search/code"],
+ commits: ["GET /search/commits"],
+ issuesAndPullRequests: ["GET /search/issues"],
+ labels: ["GET /search/labels"],
+ repos: ["GET /search/repositories"],
+ topics: ["GET /search/topics"],
+ users: ["GET /search/users"]
+ },
+ secretScanning: {
+ getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"],
+ listAlertsForEnterprise: ["GET /enterprises/{enterprise}/secret-scanning/alerts"],
+ listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"],
+ listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"],
+ listLocationsForAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"],
+ updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"]
+ },
+ teams: {
+ addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"],
+ addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
+ addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
+ checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
+ checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
+ create: ["POST /orgs/{org}/teams"],
+ createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
+ createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
+ deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
+ deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
+ deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
+ getByName: ["GET /orgs/{org}/teams/{team_slug}"],
+ getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
+ getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
+ getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"],
+ list: ["GET /orgs/{org}/teams"],
+ listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
+ listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"],
+ listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
+ listForAuthenticatedUser: ["GET /user/teams"],
+ listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
+ listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"],
+ listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"],
+ listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
+ removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"],
+ removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"],
+ removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"],
+ updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"],
+ updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"],
+ updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
+ },
+ users: {
+ addEmailForAuthenticated: ["POST /user/emails", {}, {
+ renamed: ["users", "addEmailForAuthenticatedUser"]
+ }],
+ addEmailForAuthenticatedUser: ["POST /user/emails"],
+ block: ["PUT /user/blocks/{username}"],
+ checkBlocked: ["GET /user/blocks/{username}"],
+ checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
+ checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
+ createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, {
+ renamed: ["users", "createGpgKeyForAuthenticatedUser"]
+ }],
+ createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"],
+ createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, {
+ renamed: ["users", "createPublicSshKeyForAuthenticatedUser"]
+ }],
+ createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"],
+ deleteEmailForAuthenticated: ["DELETE /user/emails", {}, {
+ renamed: ["users", "deleteEmailForAuthenticatedUser"]
+ }],
+ deleteEmailForAuthenticatedUser: ["DELETE /user/emails"],
+ deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, {
+ renamed: ["users", "deleteGpgKeyForAuthenticatedUser"]
+ }],
+ deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"],
+ deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, {
+ renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"]
+ }],
+ deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"],
+ follow: ["PUT /user/following/{username}"],
+ getAuthenticated: ["GET /user"],
+ getByUsername: ["GET /users/{username}"],
+ getContextForUser: ["GET /users/{username}/hovercard"],
+ getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, {
+ renamed: ["users", "getGpgKeyForAuthenticatedUser"]
+ }],
+ getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"],
+ getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, {
+ renamed: ["users", "getPublicSshKeyForAuthenticatedUser"]
+ }],
+ getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"],
+ list: ["GET /users"],
+ listBlockedByAuthenticated: ["GET /user/blocks", {}, {
+ renamed: ["users", "listBlockedByAuthenticatedUser"]
+ }],
+ listBlockedByAuthenticatedUser: ["GET /user/blocks"],
+ listEmailsForAuthenticated: ["GET /user/emails", {}, {
+ renamed: ["users", "listEmailsForAuthenticatedUser"]
+ }],
+ listEmailsForAuthenticatedUser: ["GET /user/emails"],
+ listFollowedByAuthenticated: ["GET /user/following", {}, {
+ renamed: ["users", "listFollowedByAuthenticatedUser"]
+ }],
+ listFollowedByAuthenticatedUser: ["GET /user/following"],
+ listFollowersForAuthenticatedUser: ["GET /user/followers"],
+ listFollowersForUser: ["GET /users/{username}/followers"],
+ listFollowingForUser: ["GET /users/{username}/following"],
+ listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, {
+ renamed: ["users", "listGpgKeysForAuthenticatedUser"]
+ }],
+ listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"],
+ listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
+ listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, {
+ renamed: ["users", "listPublicEmailsForAuthenticatedUser"]
+ }],
+ listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"],
+ listPublicKeysForUser: ["GET /users/{username}/keys"],
+ listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, {
+ renamed: ["users", "listPublicSshKeysForAuthenticatedUser"]
+ }],
+ listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
+ setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, {
+ renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"]
+ }],
+ setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"],
+ unblock: ["DELETE /user/blocks/{username}"],
+ unfollow: ["DELETE /user/following/{username}"],
+ updateAuthenticated: ["PATCH /user"]
+ }
+};
+
+const VERSION = "5.16.2";
+
+function endpointsToMethods(octokit, endpointsMap) {
+ const newMethods = {};
+
+ for (const [scope, endpoints] of Object.entries(endpointsMap)) {
+ for (const [methodName, endpoint] of Object.entries(endpoints)) {
+ const [route, defaults, decorations] = endpoint;
+ const [method, url] = route.split(/ /);
+ const endpointDefaults = Object.assign({
+ method,
+ url
+ }, defaults);
+
+ if (!newMethods[scope]) {
+ newMethods[scope] = {};
+ }
+
+ const scopeMethods = newMethods[scope];
+
+ if (decorations) {
+ scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations);
+ continue;
+ }
+
+ scopeMethods[methodName] = octokit.request.defaults(endpointDefaults);
+ }
+ }
+
+ return newMethods;
+}
+
+function decorate(octokit, scope, methodName, defaults, decorations) {
+ const requestWithDefaults = octokit.request.defaults(defaults);
+ /* istanbul ignore next */
+
+ function withDecorations(...args) {
+ // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
+ let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData`
+
+ if (decorations.mapToData) {
+ options = Object.assign({}, options, {
+ data: options[decorations.mapToData],
+ [decorations.mapToData]: undefined
+ });
+ return requestWithDefaults(options);
+ }
+
+ if (decorations.renamed) {
+ const [newScope, newMethodName] = decorations.renamed;
+ octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`);
+ }
+
+ if (decorations.deprecated) {
+ octokit.log.warn(decorations.deprecated);
+ }
+
+ if (decorations.renamedParameters) {
+ // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
+ const options = requestWithDefaults.endpoint.merge(...args);
+
+ for (const [name, alias] of Object.entries(decorations.renamedParameters)) {
+ if (name in options) {
+ octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`);
+
+ if (!(alias in options)) {
+ options[alias] = options[name];
+ }
+
+ delete options[name];
+ }
+ }
+
+ return requestWithDefaults(options);
+ } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488
+
+
+ return requestWithDefaults(...args);
+ }
+
+ return Object.assign(withDecorations, requestWithDefaults);
+}
+
+function restEndpointMethods(octokit) {
+ const api = endpointsToMethods(octokit, Endpoints);
+ return {
+ rest: api
+ };
+}
+restEndpointMethods.VERSION = VERSION;
+function legacyRestEndpointMethods(octokit) {
+ const api = endpointsToMethods(octokit, Endpoints);
+ return _objectSpread2(_objectSpread2({}, api), {}, {
+ rest: api
+ });
+}
+legacyRestEndpointMethods.VERSION = VERSION;
+
+exports.legacyRestEndpointMethods = legacyRestEndpointMethods;
+exports.restEndpointMethods = restEndpointMethods;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 86298:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var Bottleneck = _interopDefault(__nccwpck_require__(11174));
+
+// @ts-ignore
+async function errorRequest(octokit, state, error, options) {
+ if (!error.request || !error.request.request) {
+ // address https://github.com/octokit/plugin-retry.js/issues/8
+ throw error;
+ } // retry all >= 400 && not doNotRetry
+
+
+ if (error.status >= 400 && !state.doNotRetry.includes(error.status)) {
+ const retries = options.request.retries != null ? options.request.retries : state.retries;
+ const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2);
+ throw octokit.retry.retryRequest(error, retries, retryAfter);
+ } // Maybe eventually there will be more cases here
+
+
+ throw error;
+}
+
+// @ts-ignore
+
+async function wrapRequest(state, request, options) {
+ const limiter = new Bottleneck(); // @ts-ignore
+
+ limiter.on("failed", function (error, info) {
+ const maxRetries = ~~error.request.request.retries;
+ const after = ~~error.request.request.retryAfter;
+ options.request.retryCount = info.retryCount + 1;
+
+ if (maxRetries > info.retryCount) {
+ // Returning a number instructs the limiter to retry
+ // the request after that number of milliseconds have passed
+ return after * state.retryAfterBaseValue;
+ }
+ });
+ return limiter.schedule(request, options);
+}
+
+const VERSION = "3.0.9";
+function retry(octokit, octokitOptions) {
+ const state = Object.assign({
+ enabled: true,
+ retryAfterBaseValue: 1000,
+ doNotRetry: [400, 401, 403, 404, 422],
+ retries: 3
+ }, octokitOptions.retry);
+
+ if (state.enabled) {
+ octokit.hook.error("request", errorRequest.bind(null, octokit, state));
+ octokit.hook.wrap("request", wrapRequest.bind(null, state));
+ }
+
+ return {
+ retry: {
+ retryRequest: (error, retries, retryAfter) => {
+ error.request.request = Object.assign({}, error.request.request, {
+ retries: retries,
+ retryAfter: retryAfter
+ });
+ return error;
+ }
+ }
+ };
+}
+retry.VERSION = VERSION;
+
+exports.VERSION = VERSION;
+exports.retry = retry;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 9968:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var BottleneckLight = _interopDefault(__nccwpck_require__(11174));
+
+function ownKeys(object, enumerableOnly) {
+ var keys = Object.keys(object);
+
+ if (Object.getOwnPropertySymbols) {
+ var symbols = Object.getOwnPropertySymbols(object);
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
+ })), keys.push.apply(keys, symbols);
+ }
+
+ return keys;
+}
+
+function _objectSpread2(target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = null != arguments[i] ? arguments[i] : {};
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
+ _defineProperty(target, key, source[key]);
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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;
+}
+
+const VERSION = "3.7.0";
+
+const noop = () => Promise.resolve(); // @ts-expect-error
+
+
+function wrapRequest(state, request, options) {
+ return state.retryLimiter.schedule(doRequest, state, request, options);
+} // @ts-expect-error
+
+async function doRequest(state, request, options) {
+ const isWrite = options.method !== "GET" && options.method !== "HEAD";
+ const {
+ pathname
+ } = new URL(options.url, "http://github.test");
+ const isSearch = options.method === "GET" && pathname.startsWith("/search/");
+ const isGraphQL = pathname.startsWith("/graphql");
+ const retryCount = ~~options.request.retryCount;
+ const jobOptions = retryCount > 0 ? {
+ priority: 0,
+ weight: 0
+ } : {};
+
+ if (state.clustering) {
+ // Remove a job from Redis if it has not completed or failed within 60s
+ // Examples: Node process terminated, client disconnected, etc.
+ // @ts-expect-error
+ jobOptions.expiration = 1000 * 60;
+ } // Guarantee at least 1000ms between writes
+ // GraphQL can also trigger writes
+
+
+ if (isWrite || isGraphQL) {
+ await state.write.key(state.id).schedule(jobOptions, noop);
+ } // Guarantee at least 3000ms between requests that trigger notifications
+
+
+ if (isWrite && state.triggersNotification(pathname)) {
+ await state.notifications.key(state.id).schedule(jobOptions, noop);
+ } // Guarantee at least 2000ms between search requests
+
+
+ if (isSearch) {
+ await state.search.key(state.id).schedule(jobOptions, noop);
+ }
+
+ const req = state.global.key(state.id).schedule(jobOptions, request, options);
+
+ if (isGraphQL) {
+ const res = await req;
+
+ if (res.data.errors != null && // @ts-expect-error
+ res.data.errors.some(error => error.type === "RATE_LIMITED")) {
+ const error = Object.assign(new Error("GraphQL Rate Limit Exceeded"), {
+ response: res,
+ data: res.data
+ });
+ throw error;
+ }
+ }
+
+ return req;
+}
+
+var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/invitations/{invitation_id}", "/orgs/{org}/teams/{team_slug}/discussions", "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "/repos/{owner}/{repo}/collaborators/{username}", "/repos/{owner}/{repo}/commits/{commit_sha}/comments", "/repos/{owner}/{repo}/issues", "/repos/{owner}/{repo}/issues/{issue_number}/comments", "/repos/{owner}/{repo}/pulls", "/repos/{owner}/{repo}/pulls/{pull_number}/comments", "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", "/repos/{owner}/{repo}/pulls/{pull_number}/merge", "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", "/repos/{owner}/{repo}/releases", "/teams/{team_id}/discussions", "/teams/{team_id}/discussions/{discussion_number}/comments"];
+
+function routeMatcher(paths) {
+ // EXAMPLE. For the following paths:
+
+ /* [
+ "/orgs/{org}/invitations",
+ "/repos/{owner}/{repo}/collaborators/{username}"
+ ] */
+ const regexes = paths.map(path => path.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain:
+
+ /* [
+ '/orgs/(?:.+?)/invitations',
+ '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)'
+ ] */
+
+ const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain:
+
+ /*
+ ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$
+ It may look scary, but paste it into https://www.debuggex.com/
+ and it will make a lot more sense!
+ */
+
+ return new RegExp(regex, "i");
+}
+
+const regex = routeMatcher(triggersNotificationPaths);
+const triggersNotification = regex.test.bind(regex);
+const groups = {}; // @ts-expect-error
+
+const createGroups = function (Bottleneck, common) {
+ groups.global = new Bottleneck.Group(_objectSpread2({
+ id: "octokit-global",
+ maxConcurrent: 10
+ }, common));
+ groups.search = new Bottleneck.Group(_objectSpread2({
+ id: "octokit-search",
+ maxConcurrent: 1,
+ minTime: 2000
+ }, common));
+ groups.write = new Bottleneck.Group(_objectSpread2({
+ id: "octokit-write",
+ maxConcurrent: 1,
+ minTime: 1000
+ }, common));
+ groups.notifications = new Bottleneck.Group(_objectSpread2({
+ id: "octokit-notifications",
+ maxConcurrent: 1,
+ minTime: 3000
+ }, common));
+};
+
+function throttling(octokit, octokitOptions) {
+ const {
+ enabled = true,
+ Bottleneck = BottleneckLight,
+ id = "no-id",
+ timeout = 1000 * 60 * 2,
+ // Redis TTL: 2 minutes
+ connection
+ } = octokitOptions.throttle || {};
+
+ if (!enabled) {
+ return {};
+ }
+
+ const common = {
+ connection,
+ timeout
+ };
+
+ if (groups.global == null) {
+ createGroups(Bottleneck, common);
+ }
+
+ const state = Object.assign(_objectSpread2({
+ clustering: connection != null,
+ triggersNotification,
+ minimumSecondaryRateRetryAfter: 5,
+ retryAfterBaseValue: 1000,
+ retryLimiter: new Bottleneck(),
+ id
+ }, groups), octokitOptions.throttle);
+ const isUsingDeprecatedOnAbuseLimitHandler = typeof state.onAbuseLimit === "function" && state.onAbuseLimit;
+
+ if (typeof (isUsingDeprecatedOnAbuseLimitHandler ? state.onAbuseLimit : state.onSecondaryRateLimit) !== "function" || typeof state.onRateLimit !== "function") {
+ throw new Error(`octokit/plugin-throttling error:
+ You must pass the onSecondaryRateLimit and onRateLimit error handlers.
+ See https://github.com/octokit/rest.js#throttling
+
+ const octokit = new Octokit({
+ throttle: {
+ onSecondaryRateLimit: (retryAfter, options) => {/* ... */},
+ onRateLimit: (retryAfter, options) => {/* ... */}
+ }
+ })
+ `);
+ }
+
+ const events = {};
+ const emitter = new Bottleneck.Events(events); // @ts-expect-error
+
+ events.on("secondary-limit", isUsingDeprecatedOnAbuseLimitHandler ? function (...args) {
+ octokit.log.warn("[@octokit/plugin-throttling] `onAbuseLimit()` is deprecated and will be removed in a future release of `@octokit/plugin-throttling`, please use the `onSecondaryRateLimit` handler instead");
+ return state.onAbuseLimit(...args);
+ } : state.onSecondaryRateLimit); // @ts-expect-error
+
+ events.on("rate-limit", state.onRateLimit); // @ts-expect-error
+
+ events.on("error", e => octokit.log.warn("Error in throttling-plugin limit handler", e)); // @ts-expect-error
+
+ state.retryLimiter.on("failed", async function (error, info) {
+ const options = info.args[info.args.length - 1];
+ const {
+ pathname
+ } = new URL(options.url, "http://github.test");
+ const shouldRetryGraphQL = pathname.startsWith("/graphql") && error.status !== 401;
+
+ if (!(shouldRetryGraphQL || error.status === 403)) {
+ return;
+ }
+
+ const retryCount = ~~options.request.retryCount;
+ options.request.retryCount = retryCount;
+ const {
+ wantRetry,
+ retryAfter = 0
+ } = await async function () {
+ if (/\bsecondary rate\b/i.test(error.message)) {
+ // The user has hit the secondary rate limit. (REST and GraphQL)
+ // https://docs.github.com/en/rest/overview/resources-in-the-rest-api#secondary-rate-limits
+ // The Retry-After header can sometimes be blank when hitting a secondary rate limit,
+ // but is always present after 2-3s, so make sure to set `retryAfter` to at least 5s by default.
+ const retryAfter = Math.max(~~error.response.headers["retry-after"], state.minimumSecondaryRateRetryAfter);
+ const wantRetry = await emitter.trigger("secondary-limit", retryAfter, options, octokit);
+ return {
+ wantRetry,
+ retryAfter
+ };
+ }
+
+ if (error.response.headers != null && error.response.headers["x-ratelimit-remaining"] === "0") {
+ // The user has used all their allowed calls for the current time period (REST and GraphQL)
+ // https://docs.github.com/en/rest/reference/rate-limit (REST)
+ // https://docs.github.com/en/graphql/overview/resource-limitations#rate-limit (GraphQL)
+ const rateLimitReset = new Date(~~error.response.headers["x-ratelimit-reset"] * 1000).getTime();
+ const retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0);
+ const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit);
+ return {
+ wantRetry,
+ retryAfter
+ };
+ }
+
+ return {};
+ }();
+
+ if (wantRetry) {
+ options.request.retryCount++;
+ return retryAfter * state.retryAfterBaseValue;
+ }
+ });
+ octokit.hook.wrap("request", wrapRequest.bind(null, state));
+ return {};
+}
+throttling.VERSION = VERSION;
+throttling.triggersNotification = triggersNotification;
+
+exports.throttling = throttling;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 10537:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var deprecation = __nccwpck_require__(58932);
+var once = _interopDefault(__nccwpck_require__(1223));
+
+const logOnceCode = once(deprecation => console.warn(deprecation));
+const logOnceHeaders = once(deprecation => console.warn(deprecation));
+/**
+ * Error with extra properties to help with debugging
+ */
+
+class RequestError extends Error {
+ constructor(message, statusCode, options) {
+ super(message); // Maintains proper stack trace (only available on V8)
+
+ /* istanbul ignore next */
+
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "HttpError";
+ this.status = statusCode;
+ let headers;
+
+ if ("headers" in options && typeof options.headers !== "undefined") {
+ headers = options.headers;
+ }
+
+ if ("response" in options) {
+ this.response = options.response;
+ headers = options.response.headers;
+ } // redact request credentials without mutating original request options
+
+
+ const requestCopy = Object.assign({}, options.request);
+
+ if (options.request.headers.authorization) {
+ requestCopy.headers = Object.assign({}, options.request.headers, {
+ authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
+ });
+ }
+
+ requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
+ // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
+ .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
+ // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
+ .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
+ this.request = requestCopy; // deprecations
+
+ Object.defineProperty(this, "code", {
+ get() {
+ logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
+ return statusCode;
+ }
+
+ });
+ Object.defineProperty(this, "headers", {
+ get() {
+ logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
+ return headers || {};
+ }
+
+ });
+ }
+
+}
+
+exports.RequestError = RequestError;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 36234:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var endpoint = __nccwpck_require__(59440);
+var universalUserAgent = __nccwpck_require__(45030);
+var isPlainObject = __nccwpck_require__(63287);
+var nodeFetch = _interopDefault(__nccwpck_require__(81768));
+var requestError = __nccwpck_require__(30013);
+
+const VERSION = "6.2.3";
+
+function getBufferResponse(response) {
+ return response.arrayBuffer();
+}
+
+function fetchWrapper(requestOptions) {
+ const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
+ if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
+ requestOptions.body = JSON.stringify(requestOptions.body);
+ }
+ let headers = {};
+ let status;
+ let url;
+ const fetch = requestOptions.request && requestOptions.request.fetch || globalThis.fetch || /* istanbul ignore next */nodeFetch;
+ return fetch(requestOptions.url, Object.assign({
+ method: requestOptions.method,
+ body: requestOptions.body,
+ headers: requestOptions.headers,
+ redirect: requestOptions.redirect
+ },
+ // `requestOptions.request.agent` type is incompatible
+ // see https://github.com/octokit/types.ts/pull/264
+ requestOptions.request)).then(async response => {
+ url = response.url;
+ status = response.status;
+ for (const keyAndValue of response.headers) {
+ headers[keyAndValue[0]] = keyAndValue[1];
+ }
+ if ("deprecation" in headers) {
+ const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
+ const deprecationLink = matches && matches.pop();
+ log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`);
+ }
+ if (status === 204 || status === 205) {
+ return;
+ }
+ // GitHub API returns 200 for HEAD requests
+ if (requestOptions.method === "HEAD") {
+ if (status < 400) {
+ return;
+ }
+ throw new requestError.RequestError(response.statusText, status, {
+ response: {
+ url,
+ status,
+ headers,
+ data: undefined
+ },
+ request: requestOptions
+ });
+ }
+ if (status === 304) {
+ throw new requestError.RequestError("Not modified", status, {
+ response: {
+ url,
+ status,
+ headers,
+ data: await getResponseData(response)
+ },
+ request: requestOptions
+ });
+ }
+ if (status >= 400) {
+ const data = await getResponseData(response);
+ const error = new requestError.RequestError(toErrorMessage(data), status, {
+ response: {
+ url,
+ status,
+ headers,
+ data
+ },
+ request: requestOptions
+ });
+ throw error;
+ }
+ return getResponseData(response);
+ }).then(data => {
+ return {
+ status,
+ url,
+ headers,
+ data
+ };
+ }).catch(error => {
+ if (error instanceof requestError.RequestError) throw error;else if (error.name === "AbortError") throw error;
+ throw new requestError.RequestError(error.message, 500, {
+ request: requestOptions
+ });
+ });
+}
+async function getResponseData(response) {
+ const contentType = response.headers.get("content-type");
+ if (/application\/json/.test(contentType)) {
+ return response.json();
+ }
+ if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
+ return response.text();
+ }
+ return getBufferResponse(response);
+}
+function toErrorMessage(data) {
+ if (typeof data === "string") return data;
+ // istanbul ignore else - just in case
+ if ("message" in data) {
+ if (Array.isArray(data.errors)) {
+ return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`;
+ }
+ return data.message;
+ }
+ // istanbul ignore next - just in case
+ return `Unknown error: ${JSON.stringify(data)}`;
+}
+
+function withDefaults(oldEndpoint, newDefaults) {
+ const endpoint = oldEndpoint.defaults(newDefaults);
+ const newApi = function (route, parameters) {
+ const endpointOptions = endpoint.merge(route, parameters);
+ if (!endpointOptions.request || !endpointOptions.request.hook) {
+ return fetchWrapper(endpoint.parse(endpointOptions));
+ }
+ const request = (route, parameters) => {
+ return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters)));
+ };
+ Object.assign(request, {
+ endpoint,
+ defaults: withDefaults.bind(null, endpoint)
+ });
+ return endpointOptions.request.hook(request, endpointOptions);
+ };
+ return Object.assign(newApi, {
+ endpoint,
+ defaults: withDefaults.bind(null, endpoint)
+ });
+}
+
+const request = withDefaults(endpoint.endpoint, {
+ headers: {
+ "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}`
+ }
+});
+
+exports.request = request;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 30013:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var deprecation = __nccwpck_require__(58932);
+var once = _interopDefault(__nccwpck_require__(1223));
+
+const logOnceCode = once(deprecation => console.warn(deprecation));
+const logOnceHeaders = once(deprecation => console.warn(deprecation));
+/**
+ * Error with extra properties to help with debugging
+ */
+class RequestError extends Error {
+ constructor(message, statusCode, options) {
+ super(message);
+ // Maintains proper stack trace (only available on V8)
+ /* istanbul ignore next */
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+ this.name = "HttpError";
+ this.status = statusCode;
+ let headers;
+ if ("headers" in options && typeof options.headers !== "undefined") {
+ headers = options.headers;
+ }
+ if ("response" in options) {
+ this.response = options.response;
+ headers = options.response.headers;
+ }
+ // redact request credentials without mutating original request options
+ const requestCopy = Object.assign({}, options.request);
+ if (options.request.headers.authorization) {
+ requestCopy.headers = Object.assign({}, options.request.headers, {
+ authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
+ });
+ }
+ requestCopy.url = requestCopy.url
+ // client_id & client_secret can be passed as URL query parameters to increase rate limit
+ // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
+ .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]")
+ // OAuth tokens can be passed as URL query parameters, although it is not recommended
+ // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
+ .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
+ this.request = requestCopy;
+ // deprecations
+ Object.defineProperty(this, "code", {
+ get() {
+ logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
+ return statusCode;
+ }
+ });
+ Object.defineProperty(this, "headers", {
+ get() {
+ logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
+ return headers || {};
+ }
+ });
+ }
+}
+
+exports.RequestError = RequestError;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 81768:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var Stream = _interopDefault(__nccwpck_require__(12781));
+var http = _interopDefault(__nccwpck_require__(13685));
+var Url = _interopDefault(__nccwpck_require__(57310));
+var whatwgUrl = _interopDefault(__nccwpck_require__(28665));
+var https = _interopDefault(__nccwpck_require__(95687));
+var zlib = _interopDefault(__nccwpck_require__(59796));
+
+// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
+
+// fix for "Readable" isn't a named export issue
+const Readable = Stream.Readable;
+
+const BUFFER = Symbol('buffer');
+const TYPE = Symbol('type');
+
+class Blob {
+ constructor() {
+ this[TYPE] = '';
+
+ const blobParts = arguments[0];
+ const options = arguments[1];
+
+ const buffers = [];
+ let size = 0;
+
+ if (blobParts) {
+ const a = blobParts;
+ const length = Number(a.length);
+ for (let i = 0; i < length; i++) {
+ const element = a[i];
+ let buffer;
+ if (element instanceof Buffer) {
+ buffer = element;
+ } else if (ArrayBuffer.isView(element)) {
+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
+ } else if (element instanceof ArrayBuffer) {
+ buffer = Buffer.from(element);
+ } else if (element instanceof Blob) {
+ buffer = element[BUFFER];
+ } else {
+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));
+ }
+ size += buffer.length;
+ buffers.push(buffer);
+ }
+ }
+
+ this[BUFFER] = Buffer.concat(buffers);
+
+ let type = options && options.type !== undefined && String(options.type).toLowerCase();
+ if (type && !/[^\u0020-\u007E]/.test(type)) {
+ this[TYPE] = type;
+ }
+ }
+ get size() {
+ return this[BUFFER].length;
+ }
+ get type() {
+ return this[TYPE];
+ }
+ text() {
+ return Promise.resolve(this[BUFFER].toString());
+ }
+ arrayBuffer() {
+ const buf = this[BUFFER];
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ return Promise.resolve(ab);
+ }
+ stream() {
+ const readable = new Readable();
+ readable._read = function () {};
+ readable.push(this[BUFFER]);
+ readable.push(null);
+ return readable;
+ }
+ toString() {
+ return '[object Blob]';
+ }
+ slice() {
+ const size = this.size;
+
+ const start = arguments[0];
+ const end = arguments[1];
+ let relativeStart, relativeEnd;
+ if (start === undefined) {
+ relativeStart = 0;
+ } else if (start < 0) {
+ relativeStart = Math.max(size + start, 0);
+ } else {
+ relativeStart = Math.min(start, size);
+ }
+ if (end === undefined) {
+ relativeEnd = size;
+ } else if (end < 0) {
+ relativeEnd = Math.max(size + end, 0);
+ } else {
+ relativeEnd = Math.min(end, size);
+ }
+ const span = Math.max(relativeEnd - relativeStart, 0);
+
+ const buffer = this[BUFFER];
+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
+ const blob = new Blob([], { type: arguments[2] });
+ blob[BUFFER] = slicedBuffer;
+ return blob;
+ }
+}
+
+Object.defineProperties(Blob.prototype, {
+ size: { enumerable: true },
+ type: { enumerable: true },
+ slice: { enumerable: true }
+});
+
+Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
+ value: 'Blob',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * fetch-error.js
+ *
+ * FetchError interface for operational errors
+ */
+
+/**
+ * Create FetchError instance
+ *
+ * @param String message Error message for human
+ * @param String type Error type for machine
+ * @param String systemError For Node.js system error
+ * @return FetchError
+ */
+function FetchError(message, type, systemError) {
+ Error.call(this, message);
+
+ this.message = message;
+ this.type = type;
+
+ // when err.type is `system`, err.code contains system error code
+ if (systemError) {
+ this.code = this.errno = systemError.code;
+ }
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+FetchError.prototype = Object.create(Error.prototype);
+FetchError.prototype.constructor = FetchError;
+FetchError.prototype.name = 'FetchError';
+
+let convert;
+try {
+ convert = (__nccwpck_require__(22877).convert);
+} catch (e) {}
+
+const INTERNALS = Symbol('Body internals');
+
+// fix an issue where "PassThrough" isn't a named export for node <10
+const PassThrough = Stream.PassThrough;
+
+/**
+ * Body mixin
+ *
+ * Ref: https://fetch.spec.whatwg.org/#body
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+function Body(body) {
+ var _this = this;
+
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ _ref$size = _ref.size;
+
+ let size = _ref$size === undefined ? 0 : _ref$size;
+ var _ref$timeout = _ref.timeout;
+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
+
+ if (body == null) {
+ // body is undefined or null
+ body = null;
+ } else if (isURLSearchParams(body)) {
+ // body is a URLSearchParams
+ body = Buffer.from(body.toString());
+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
+ // body is ArrayBuffer
+ body = Buffer.from(body);
+ } else if (ArrayBuffer.isView(body)) {
+ // body is ArrayBufferView
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
+ } else if (body instanceof Stream) ; else {
+ // none of the above
+ // coerce to string then buffer
+ body = Buffer.from(String(body));
+ }
+ this[INTERNALS] = {
+ body,
+ disturbed: false,
+ error: null
+ };
+ this.size = size;
+ this.timeout = timeout;
+
+ if (body instanceof Stream) {
+ body.on('error', function (err) {
+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
+ _this[INTERNALS].error = error;
+ });
+ }
+}
+
+Body.prototype = {
+ get body() {
+ return this[INTERNALS].body;
+ },
+
+ get bodyUsed() {
+ return this[INTERNALS].disturbed;
+ },
+
+ /**
+ * Decode response as ArrayBuffer
+ *
+ * @return Promise
+ */
+ arrayBuffer() {
+ return consumeBody.call(this).then(function (buf) {
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ });
+ },
+
+ /**
+ * Return raw response as Blob
+ *
+ * @return Promise
+ */
+ blob() {
+ let ct = this.headers && this.headers.get('content-type') || '';
+ return consumeBody.call(this).then(function (buf) {
+ return Object.assign(
+ // Prevent copying
+ new Blob([], {
+ type: ct.toLowerCase()
+ }), {
+ [BUFFER]: buf
+ });
+ });
+ },
+
+ /**
+ * Decode response as json
+ *
+ * @return Promise
+ */
+ json() {
+ var _this2 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ try {
+ return JSON.parse(buffer.toString());
+ } catch (err) {
+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
+ }
+ });
+ },
+
+ /**
+ * Decode response as text
+ *
+ * @return Promise
+ */
+ text() {
+ return consumeBody.call(this).then(function (buffer) {
+ return buffer.toString();
+ });
+ },
+
+ /**
+ * Decode response as buffer (non-spec api)
+ *
+ * @return Promise
+ */
+ buffer() {
+ return consumeBody.call(this);
+ },
+
+ /**
+ * Decode response as text, while automatically detecting the encoding and
+ * trying to decode to UTF-8 (non-spec api)
+ *
+ * @return Promise
+ */
+ textConverted() {
+ var _this3 = this;
+
+ return consumeBody.call(this).then(function (buffer) {
+ return convertBody(buffer, _this3.headers);
+ });
+ }
+};
+
+// In browsers, all properties are enumerable.
+Object.defineProperties(Body.prototype, {
+ body: { enumerable: true },
+ bodyUsed: { enumerable: true },
+ arrayBuffer: { enumerable: true },
+ blob: { enumerable: true },
+ json: { enumerable: true },
+ text: { enumerable: true }
+});
+
+Body.mixIn = function (proto) {
+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {
+ // istanbul ignore else: future proof
+ if (!(name in proto)) {
+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
+ Object.defineProperty(proto, name, desc);
+ }
+ }
+};
+
+/**
+ * Consume and convert an entire Body to a Buffer.
+ *
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
+ *
+ * @return Promise
+ */
+function consumeBody() {
+ var _this4 = this;
+
+ if (this[INTERNALS].disturbed) {
+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
+ }
+
+ this[INTERNALS].disturbed = true;
+
+ if (this[INTERNALS].error) {
+ return Body.Promise.reject(this[INTERNALS].error);
+ }
+
+ let body = this.body;
+
+ // body is null
+ if (body === null) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is blob
+ if (isBlob(body)) {
+ body = body.stream();
+ }
+
+ // body is buffer
+ if (Buffer.isBuffer(body)) {
+ return Body.Promise.resolve(body);
+ }
+
+ // istanbul ignore if: should never happen
+ if (!(body instanceof Stream)) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
+
+ // body is stream
+ // get ready to actually consume the body
+ let accum = [];
+ let accumBytes = 0;
+ let abort = false;
+
+ return new Body.Promise(function (resolve, reject) {
+ let resTimeout;
+
+ // allow timeout on slow response body
+ if (_this4.timeout) {
+ resTimeout = setTimeout(function () {
+ abort = true;
+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
+ }, _this4.timeout);
+ }
+
+ // handle stream errors
+ body.on('error', function (err) {
+ if (err.name === 'AbortError') {
+ // if the request was aborted, reject with this Error
+ abort = true;
+ reject(err);
+ } else {
+ // other errors, such as incorrect content-encoding
+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+
+ body.on('data', function (chunk) {
+ if (abort || chunk === null) {
+ return;
+ }
+
+ if (_this4.size && accumBytes + chunk.length > _this4.size) {
+ abort = true;
+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
+ return;
+ }
+
+ accumBytes += chunk.length;
+ accum.push(chunk);
+ });
+
+ body.on('end', function () {
+ if (abort) {
+ return;
+ }
+
+ clearTimeout(resTimeout);
+
+ try {
+ resolve(Buffer.concat(accum, accumBytes));
+ } catch (err) {
+ // handle streams that have accumulated too much data (issue #414)
+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+ });
+}
+
+/**
+ * Detect buffer encoding and convert to target encoding
+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
+ *
+ * @param Buffer buffer Incoming buffer
+ * @param String encoding Target encoding
+ * @return String
+ */
+function convertBody(buffer, headers) {
+ if (typeof convert !== 'function') {
+ throw new Error('The package `encoding` must be installed to use the textConverted() function');
+ }
+
+ const ct = headers.get('content-type');
+ let charset = 'utf-8';
+ let res, str;
+
+ // header
+ if (ct) {
+ res = /charset=([^;]*)/i.exec(ct);
+ }
+
+ // no charset in content type, peek at response body for at most 1024 bytes
+ str = buffer.slice(0, 1024).toString();
+
+ // html5
+ if (!res && str) {
+ res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;
+
+ this[MAP] = Object.create(null);
+
+ if (init instanceof Headers) {
+ const rawHeaders = init.raw();
+ const headerNames = Object.keys(rawHeaders);
+
+ for (const headerName of headerNames) {
+ for (const value of rawHeaders[headerName]) {
+ this.append(headerName, value);
+ }
+ }
+
+ return;
+ }
+
+ // We don't worry about converting prop to ByteString here as append()
+ // will handle it.
+ if (init == null) ; else if (typeof init === 'object') {
+ const method = init[Symbol.iterator];
+ if (method != null) {
+ if (typeof method !== 'function') {
+ throw new TypeError('Header pairs must be iterable');
+ }
+
+ // sequence>
+ // Note: per spec we have to first exhaust the lists then process them
+ const pairs = [];
+ for (const pair of init) {
+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
+ throw new TypeError('Each header pair must be iterable');
+ }
+ pairs.push(Array.from(pair));
+ }
+
+ for (const pair of pairs) {
+ if (pair.length !== 2) {
+ throw new TypeError('Each header pair must be a name/value tuple');
+ }
+ this.append(pair[0], pair[1]);
+ }
+ } else {
+ // record
+ for (const key of Object.keys(init)) {
+ const value = init[key];
+ this.append(key, value);
+ }
+ }
+ } else {
+ throw new TypeError('Provided initializer must be an object');
+ }
+ }
+
+ /**
+ * Return combined header value given name
+ *
+ * @param String name Header name
+ * @return Mixed
+ */
+ get(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key === undefined) {
+ return null;
+ }
+
+ return this[MAP][key].join(', ');
+ }
+
+ /**
+ * Iterate over all headers
+ *
+ * @param Function callback Executed for each item with parameters (value, name, thisArg)
+ * @param Boolean thisArg `this` context for callback function
+ * @return Void
+ */
+ forEach(callback) {
+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
+
+ let pairs = getHeaders(this);
+ let i = 0;
+ while (i < pairs.length) {
+ var _pairs$i = pairs[i];
+ const name = _pairs$i[0],
+ value = _pairs$i[1];
+
+ callback.call(thisArg, value, name, this);
+ pairs = getHeaders(this);
+ i++;
+ }
+ }
+
+ /**
+ * Overwrite header values given name
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ set(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ this[MAP][key !== undefined ? key : name] = [value];
+ }
+
+ /**
+ * Append a value onto existing header
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ append(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ this[MAP][key].push(value);
+ } else {
+ this[MAP][name] = [value];
+ }
+ }
+
+ /**
+ * Check for header name existence
+ *
+ * @param String name Header name
+ * @return Boolean
+ */
+ has(name) {
+ name = `${name}`;
+ validateName(name);
+ return find(this[MAP], name) !== undefined;
+ }
+
+ /**
+ * Delete all header values given name
+ *
+ * @param String name Header name
+ * @return Void
+ */
+ delete(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ delete this[MAP][key];
+ }
+ }
+
+ /**
+ * Return raw headers (non-spec api)
+ *
+ * @return Object
+ */
+ raw() {
+ return this[MAP];
+ }
+
+ /**
+ * Get an iterator on keys.
+ *
+ * @return Iterator
+ */
+ keys() {
+ return createHeadersIterator(this, 'key');
+ }
+
+ /**
+ * Get an iterator on values.
+ *
+ * @return Iterator
+ */
+ values() {
+ return createHeadersIterator(this, 'value');
+ }
+
+ /**
+ * Get an iterator on entries.
+ *
+ * This is the default iterator of the Headers object.
+ *
+ * @return Iterator
+ */
+ [Symbol.iterator]() {
+ return createHeadersIterator(this, 'key+value');
+ }
+}
+Headers.prototype.entries = Headers.prototype[Symbol.iterator];
+
+Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
+ value: 'Headers',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Headers.prototype, {
+ get: { enumerable: true },
+ forEach: { enumerable: true },
+ set: { enumerable: true },
+ append: { enumerable: true },
+ has: { enumerable: true },
+ delete: { enumerable: true },
+ keys: { enumerable: true },
+ values: { enumerable: true },
+ entries: { enumerable: true }
+});
+
+function getHeaders(headers) {
+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
+
+ const keys = Object.keys(headers[MAP]).sort();
+ return keys.map(kind === 'key' ? function (k) {
+ return k.toLowerCase();
+ } : kind === 'value' ? function (k) {
+ return headers[MAP][k].join(', ');
+ } : function (k) {
+ return [k.toLowerCase(), headers[MAP][k].join(', ')];
+ });
+}
+
+const INTERNAL = Symbol('internal');
+
+function createHeadersIterator(target, kind) {
+ const iterator = Object.create(HeadersIteratorPrototype);
+ iterator[INTERNAL] = {
+ target,
+ kind,
+ index: 0
+ };
+ return iterator;
+}
+
+const HeadersIteratorPrototype = Object.setPrototypeOf({
+ next() {
+ // istanbul ignore if
+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
+ throw new TypeError('Value of `this` is not a HeadersIterator');
+ }
+
+ var _INTERNAL = this[INTERNAL];
+ const target = _INTERNAL.target,
+ kind = _INTERNAL.kind,
+ index = _INTERNAL.index;
+
+ const values = getHeaders(target, kind);
+ const len = values.length;
+ if (index >= len) {
+ return {
+ value: undefined,
+ done: true
+ };
+ }
+
+ this[INTERNAL].index = index + 1;
+
+ return {
+ value: values[index],
+ done: false
+ };
+ }
+}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
+
+Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
+ value: 'HeadersIterator',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+/**
+ * Export the Headers object in a form that Node.js can consume.
+ *
+ * @param Headers headers
+ * @return Object
+ */
+function exportNodeCompatibleHeaders(headers) {
+ const obj = Object.assign({ __proto__: null }, headers[MAP]);
+
+ // http.request() only supports string as Host header. This hack makes
+ // specifying custom Host header possible.
+ const hostHeaderKey = find(headers[MAP], 'Host');
+ if (hostHeaderKey !== undefined) {
+ obj[hostHeaderKey] = obj[hostHeaderKey][0];
+ }
+
+ return obj;
+}
+
+/**
+ * Create a Headers object from an object of headers, ignoring those that do
+ * not conform to HTTP grammar productions.
+ *
+ * @param Object obj Object of headers
+ * @return Headers
+ */
+function createHeadersLenient(obj) {
+ const headers = new Headers();
+ for (const name of Object.keys(obj)) {
+ if (invalidTokenRegex.test(name)) {
+ continue;
+ }
+ if (Array.isArray(obj[name])) {
+ for (const val of obj[name]) {
+ if (invalidHeaderCharRegex.test(val)) {
+ continue;
+ }
+ if (headers[MAP][name] === undefined) {
+ headers[MAP][name] = [val];
+ } else {
+ headers[MAP][name].push(val);
+ }
+ }
+ } else if (!invalidHeaderCharRegex.test(obj[name])) {
+ headers[MAP][name] = [obj[name]];
+ }
+ }
+ return headers;
+}
+
+const INTERNALS$1 = Symbol('Response internals');
+
+// fix an issue where "STATUS_CODES" aren't a named export for node <10
+const STATUS_CODES = http.STATUS_CODES;
+
+/**
+ * Response class
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+class Response {
+ constructor() {
+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ Body.call(this, body, opts);
+
+ const status = opts.status || 200;
+ const headers = new Headers(opts.headers);
+
+ if (body != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(body);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ this[INTERNALS$1] = {
+ url: opts.url,
+ status,
+ statusText: opts.statusText || STATUS_CODES[status],
+ headers,
+ counter: opts.counter
+ };
+ }
+
+ get url() {
+ return this[INTERNALS$1].url || '';
+ }
+
+ get status() {
+ return this[INTERNALS$1].status;
+ }
+
+ /**
+ * Convenience property representing if the request ended normally
+ */
+ get ok() {
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
+ }
+
+ get redirected() {
+ return this[INTERNALS$1].counter > 0;
+ }
+
+ get statusText() {
+ return this[INTERNALS$1].statusText;
+ }
+
+ get headers() {
+ return this[INTERNALS$1].headers;
+ }
+
+ /**
+ * Clone this response
+ *
+ * @return Response
+ */
+ clone() {
+ return new Response(clone(this), {
+ url: this.url,
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ ok: this.ok,
+ redirected: this.redirected
+ });
+ }
+}
+
+Body.mixIn(Response.prototype);
+
+Object.defineProperties(Response.prototype, {
+ url: { enumerable: true },
+ status: { enumerable: true },
+ ok: { enumerable: true },
+ redirected: { enumerable: true },
+ statusText: { enumerable: true },
+ headers: { enumerable: true },
+ clone: { enumerable: true }
+});
+
+Object.defineProperty(Response.prototype, Symbol.toStringTag, {
+ value: 'Response',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+const INTERNALS$2 = Symbol('Request internals');
+const URL = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "format", "parse" aren't a named export for node <10
+const parse_url = Url.parse;
+const format_url = Url.format;
+
+/**
+ * Wrapper around `new URL` to handle arbitrary URLs
+ *
+ * @param {string} urlStr
+ * @return {void}
+ */
+function parseURL(urlStr) {
+ /*
+ Check whether the URL is absolute or not
+ Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
+ Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
+ */
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
+ urlStr = new URL(urlStr).toString();
+ }
+
+ // Fallback to old implementation for arbitrary URLs
+ return parse_url(urlStr);
+}
+
+const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
+
+/**
+ * Check if a value is an instance of Request.
+ *
+ * @param Mixed input
+ * @return Boolean
+ */
+function isRequest(input) {
+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
+}
+
+function isAbortSignal(signal) {
+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
+ return !!(proto && proto.constructor.name === 'AbortSignal');
+}
+
+/**
+ * Request class
+ *
+ * @param Mixed input Url or Request instance
+ * @param Object init Custom options
+ * @return Void
+ */
+class Request {
+ constructor(input) {
+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+
+ let parsedURL;
+
+ // normalize input
+ if (!isRequest(input)) {
+ if (input && input.href) {
+ // in order to support Node.js' Url objects; though WHATWG's URL objects
+ // will fall into this branch also (since their `toString()` will return
+ // `href` property anyway)
+ parsedURL = parseURL(input.href);
+ } else {
+ // coerce input to a string before attempting to parse
+ parsedURL = parseURL(`${input}`);
+ }
+ input = {};
+ } else {
+ parsedURL = parseURL(input.url);
+ }
+
+ let method = init.method || input.method || 'GET';
+ method = method.toUpperCase();
+
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
+ throw new TypeError('Request with GET/HEAD method cannot have body');
+ }
+
+ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
+
+ Body.call(this, inputBody, {
+ timeout: init.timeout || input.timeout || 0,
+ size: init.size || input.size || 0
+ });
+
+ const headers = new Headers(init.headers || input.headers || {});
+
+ if (inputBody != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(inputBody);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
+
+ let signal = isRequest(input) ? input.signal : null;
+ if ('signal' in init) signal = init.signal;
+
+ if (signal != null && !isAbortSignal(signal)) {
+ throw new TypeError('Expected signal to be an instanceof AbortSignal');
+ }
+
+ this[INTERNALS$2] = {
+ method,
+ redirect: init.redirect || input.redirect || 'follow',
+ headers,
+ parsedURL,
+ signal
+ };
+
+ // node-fetch-only options
+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
+ this.counter = init.counter || input.counter || 0;
+ this.agent = init.agent || input.agent;
+ }
+
+ get method() {
+ return this[INTERNALS$2].method;
+ }
+
+ get url() {
+ return format_url(this[INTERNALS$2].parsedURL);
+ }
+
+ get headers() {
+ return this[INTERNALS$2].headers;
+ }
+
+ get redirect() {
+ return this[INTERNALS$2].redirect;
+ }
+
+ get signal() {
+ return this[INTERNALS$2].signal;
+ }
+
+ /**
+ * Clone this request
+ *
+ * @return Request
+ */
+ clone() {
+ return new Request(this);
+ }
+}
+
+Body.mixIn(Request.prototype);
+
+Object.defineProperty(Request.prototype, Symbol.toStringTag, {
+ value: 'Request',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
+
+Object.defineProperties(Request.prototype, {
+ method: { enumerable: true },
+ url: { enumerable: true },
+ headers: { enumerable: true },
+ redirect: { enumerable: true },
+ clone: { enumerable: true },
+ signal: { enumerable: true }
+});
+
+/**
+ * Convert a Request to Node.js http request options.
+ *
+ * @param Request A Request instance
+ * @return Object The options object to be passed to http.request
+ */
+function getNodeRequestOptions(request) {
+ const parsedURL = request[INTERNALS$2].parsedURL;
+ const headers = new Headers(request[INTERNALS$2].headers);
+
+ // fetch step 1.3
+ if (!headers.has('Accept')) {
+ headers.set('Accept', '*/*');
+ }
+
+ // Basic fetch
+ if (!parsedURL.protocol || !parsedURL.hostname) {
+ throw new TypeError('Only absolute URLs are supported');
+ }
+
+ if (!/^https?:$/.test(parsedURL.protocol)) {
+ throw new TypeError('Only HTTP(S) protocols are supported');
+ }
+
+ if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
+ }
+
+ // HTTP-network-or-cache fetch steps 2.4-2.7
+ let contentLengthValue = null;
+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
+ contentLengthValue = '0';
+ }
+ if (request.body != null) {
+ const totalBytes = getTotalBytes(request);
+ if (typeof totalBytes === 'number') {
+ contentLengthValue = String(totalBytes);
+ }
+ }
+ if (contentLengthValue) {
+ headers.set('Content-Length', contentLengthValue);
+ }
+
+ // HTTP-network-or-cache fetch step 2.11
+ if (!headers.has('User-Agent')) {
+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
+ }
+
+ // HTTP-network-or-cache fetch step 2.15
+ if (request.compress && !headers.has('Accept-Encoding')) {
+ headers.set('Accept-Encoding', 'gzip,deflate');
+ }
+
+ let agent = request.agent;
+ if (typeof agent === 'function') {
+ agent = agent(parsedURL);
+ }
+
+ if (!headers.has('Connection') && !agent) {
+ headers.set('Connection', 'close');
+ }
+
+ // HTTP-network fetch step 4.2
+ // chunked encoding is handled by Node.js
+
+ return Object.assign({}, parsedURL, {
+ method: request.method,
+ headers: exportNodeCompatibleHeaders(headers),
+ agent
+ });
+}
+
+/**
+ * abort-error.js
+ *
+ * AbortError interface for cancelled requests
+ */
+
+/**
+ * Create AbortError instance
+ *
+ * @param String message Error message for human
+ * @return AbortError
+ */
+function AbortError(message) {
+ Error.call(this, message);
+
+ this.type = 'aborted';
+ this.message = message;
+
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
+
+AbortError.prototype = Object.create(Error.prototype);
+AbortError.prototype.constructor = AbortError;
+AbortError.prototype.name = 'AbortError';
+
+const URL$1 = Url.URL || whatwgUrl.URL;
+
+// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
+const PassThrough$1 = Stream.PassThrough;
+
+const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
+ const orig = new URL$1(original).hostname;
+ const dest = new URL$1(destination).hostname;
+
+ return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
+};
+
+/**
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isSameProtocol = function isSameProtocol(destination, original) {
+ const orig = new URL$1(original).protocol;
+ const dest = new URL$1(destination).protocol;
+
+ return orig === dest;
+};
+
+/**
+ * Fetch function
+ *
+ * @param Mixed url Absolute url or Request instance
+ * @param Object opts Fetch options
+ * @return Promise
+ */
+function fetch(url, opts) {
+
+ // allow custom promise
+ if (!fetch.Promise) {
+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
+ }
+
+ Body.Promise = fetch.Promise;
+
+ // wrap http.request into fetch
+ return new fetch.Promise(function (resolve, reject) {
+ // build request object
+ const request = new Request(url, opts);
+ const options = getNodeRequestOptions(request);
+
+ const send = (options.protocol === 'https:' ? https : http).request;
+ const signal = request.signal;
+
+ let response = null;
+
+ const abort = function abort() {
+ let error = new AbortError('The user aborted a request.');
+ reject(error);
+ if (request.body && request.body instanceof Stream.Readable) {
+ destroyStream(request.body, error);
+ }
+ if (!response || !response.body) return;
+ response.body.emit('error', error);
+ };
+
+ if (signal && signal.aborted) {
+ abort();
+ return;
+ }
+
+ const abortAndFinalize = function abortAndFinalize() {
+ abort();
+ finalize();
+ };
+
+ // send request
+ const req = send(options);
+ let reqTimeout;
+
+ if (signal) {
+ signal.addEventListener('abort', abortAndFinalize);
+ }
+
+ function finalize() {
+ req.abort();
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ clearTimeout(reqTimeout);
+ }
+
+ if (request.timeout) {
+ req.once('socket', function (socket) {
+ reqTimeout = setTimeout(function () {
+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
+ finalize();
+ }, request.timeout);
+ });
+ }
+
+ req.on('error', function (err) {
+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+
+ finalize();
+ });
+
+ fixResponseChunkedTransferBadEnding(req, function (err) {
+ if (signal && signal.aborted) {
+ return;
+ }
+
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+ });
+
+ /* c8 ignore next 18 */
+ if (parseInt(process.version.substring(1)) < 14) {
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
+ // properly handle when the socket close/end events are out of order.
+ req.on('socket', function (s) {
+ s.addListener('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = s.listenerCount('data') > 0;
+
+ // if end happened before close but the socket didn't emit an error, do it now
+ if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ response.body.emit('error', err);
+ }
+ });
+ });
+ }
+
+ req.on('response', function (res) {
+ clearTimeout(reqTimeout);
+
+ const headers = createHeadersLenient(res.headers);
+
+ // HTTP fetch step 5
+ if (fetch.isRedirect(res.statusCode)) {
+ // HTTP fetch step 5.2
+ const location = headers.get('Location');
+
+ // HTTP fetch step 5.3
+ let locationURL = null;
+ try {
+ locationURL = location === null ? null : new URL$1(location, request.url).toString();
+ } catch (err) {
+ // error here can only be invalid URL in Location: header
+ // do not throw when options.redirect == manual
+ // let the user extract the errorneous redirect URL
+ if (request.redirect !== 'manual') {
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
+ finalize();
+ return;
+ }
+ }
+
+ // HTTP fetch step 5.5
+ switch (request.redirect) {
+ case 'error':
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
+ finalize();
+ return;
+ case 'manual':
+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
+ if (locationURL !== null) {
+ // handle corrupted header
+ try {
+ headers.set('Location', locationURL);
+ } catch (err) {
+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
+ reject(err);
+ }
+ }
+ break;
+ case 'follow':
+ // HTTP-redirect fetch step 2
+ if (locationURL === null) {
+ break;
+ }
+
+ // HTTP-redirect fetch step 5
+ if (request.counter >= request.follow) {
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 6 (counter increment)
+ // Create a new Request object.
+ const requestOpts = {
+ headers: new Headers(request.headers),
+ follow: request.follow,
+ counter: request.counter + 1,
+ agent: request.agent,
+ compress: request.compress,
+ method: request.method,
+ body: request.body,
+ signal: request.signal,
+ timeout: request.timeout,
+ size: request.size
+ };
+
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
+ requestOpts.headers.delete(name);
+ }
+ }
+
+ // HTTP-redirect fetch step 9
+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 11
+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
+ requestOpts.method = 'GET';
+ requestOpts.body = undefined;
+ requestOpts.headers.delete('content-length');
+ }
+
+ // HTTP-redirect fetch step 15
+ resolve(fetch(new Request(locationURL, requestOpts)));
+ finalize();
+ return;
+ }
+ }
+
+ // prepare response
+ res.once('end', function () {
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ });
+ let body = res.pipe(new PassThrough$1());
+
+ const response_options = {
+ url: request.url,
+ status: res.statusCode,
+ statusText: res.statusMessage,
+ headers: headers,
+ size: request.size,
+ timeout: request.timeout,
+ counter: request.counter
+ };
+
+ // HTTP-network fetch step 12.1.1.3
+ const codings = headers.get('Content-Encoding');
+
+ // HTTP-network fetch step 12.1.1.4: handle content codings
+
+ // in following scenarios we ignore compression support
+ // 1. compression support is disabled
+ // 2. HEAD request
+ // 3. no Content-Encoding header
+ // 4. no content response (204)
+ // 5. content not modified response (304)
+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // For Node v6+
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ const zlibOptions = {
+ flush: zlib.Z_SYNC_FLUSH,
+ finishFlush: zlib.Z_SYNC_FLUSH
+ };
+
+ // for gzip
+ if (codings == 'gzip' || codings == 'x-gzip') {
+ body = body.pipe(zlib.createGunzip(zlibOptions));
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // for deflate
+ if (codings == 'deflate' || codings == 'x-deflate') {
+ // handle the infamous raw deflate response from old servers
+ // a hack for old IIS and Apache servers
+ const raw = res.pipe(new PassThrough$1());
+ raw.once('data', function (chunk) {
+ // see http://stackoverflow.com/questions/37519828
+ if ((chunk[0] & 0x0F) === 0x08) {
+ body = body.pipe(zlib.createInflate());
+ } else {
+ body = body.pipe(zlib.createInflateRaw());
+ }
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+ raw.on('end', function () {
+ // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
+ if (!response) {
+ response = new Response(body, response_options);
+ resolve(response);
+ }
+ });
+ return;
+ }
+
+ // for br
+ if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
+ body = body.pipe(zlib.createBrotliDecompress());
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
+
+ // otherwise, use response as-is
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+
+ writeToStream(req, request);
+ });
+}
+function fixResponseChunkedTransferBadEnding(request, errorCallback) {
+ let socket;
+
+ request.on('socket', function (s) {
+ socket = s;
+ });
+
+ request.on('response', function (response) {
+ const headers = response.headers;
+
+ if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
+ response.once('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = socket.listenerCount('data') > 0;
+
+ if (hasDataListener && !hadError) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ errorCallback(err);
+ }
+ });
+ }
+ });
+}
+
+function destroyStream(stream, err) {
+ if (stream.destroy) {
+ stream.destroy(err);
+ } else {
+ // node < 8
+ stream.emit('error', err);
+ stream.end();
+ }
+}
+
+/**
+ * Redirect code matching
+ *
+ * @param Number code Status code
+ * @return Boolean
+ */
+fetch.isRedirect = function (code) {
+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
+};
+
+// expose Promise
+fetch.Promise = global.Promise;
+
+module.exports = exports = fetch;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = exports;
+exports.Headers = Headers;
+exports.Request = Request;
+exports.Response = Response;
+exports.FetchError = FetchError;
+
+
+/***/ }),
+
+/***/ 49768:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+var crypto = __nccwpck_require__(6113);
+var buffer = __nccwpck_require__(14300);
+
+const VERSION = "2.0.0";
+
+var Algorithm;
+
+(function (Algorithm) {
+ Algorithm["SHA1"] = "sha1";
+ Algorithm["SHA256"] = "sha256";
+})(Algorithm || (Algorithm = {}));
+
+async function sign(options, payload) {
+ const {
+ secret,
+ algorithm
+ } = typeof options === "object" ? {
+ secret: options.secret,
+ algorithm: options.algorithm || Algorithm.SHA256
+ } : {
+ secret: options,
+ algorithm: Algorithm.SHA256
+ };
+
+ if (!secret || !payload) {
+ throw new TypeError("[@octokit/webhooks-methods] secret & payload required for sign()");
+ }
+
+ if (!Object.values(Algorithm).includes(algorithm)) {
+ throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`);
+ }
+
+ return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`;
+}
+sign.VERSION = VERSION;
+
+const getAlgorithm = signature => {
+ return signature.startsWith("sha256=") ? "sha256" : "sha1";
+};
+
+async function verify(secret, eventPayload, signature) {
+ if (!secret || !eventPayload || !signature) {
+ throw new TypeError("[@octokit/webhooks-methods] secret, eventPayload & signature required");
+ }
+
+ const signatureBuffer = buffer.Buffer.from(signature);
+ const algorithm = getAlgorithm(signature);
+ const verificationBuffer = buffer.Buffer.from(await sign({
+ secret,
+ algorithm
+ }, eventPayload));
+
+ if (signatureBuffer.length !== verificationBuffer.length) {
+ return false;
+ } // constant time comparison to prevent timing attachs
+ // https://stackoverflow.com/a/31096242/206879
+ // https://en.wikipedia.org/wiki/Timing_attack
+
+
+ return crypto.timingSafeEqual(signatureBuffer, verificationBuffer);
+}
+verify.VERSION = VERSION;
+
+exports.sign = sign;
+exports.verify = verify;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 18513:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var AggregateError = _interopDefault(__nccwpck_require__(61231));
+var webhooksMethods = __nccwpck_require__(49768);
+
+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 _objectSpread2(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;
+}
+
+const createLogger = logger => _objectSpread2({
+ debug: () => {},
+ info: () => {},
+ warn: console.warn.bind(console),
+ error: console.error.bind(console)
+}, logger);
+
+// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY
+// make edits in scripts/generate-types.ts
+const emitterEventNames = ["branch_protection_rule", "branch_protection_rule.created", "branch_protection_rule.deleted", "branch_protection_rule.edited", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "discussion", "discussion.answered", "discussion.category_changed", "discussion.created", "discussion.deleted", "discussion.edited", "discussion.labeled", "discussion.locked", "discussion.pinned", "discussion.transferred", "discussion.unanswered", "discussion.unlabeled", "discussion.unlocked", "discussion.unpinned", "discussion_comment", "discussion_comment.created", "discussion_comment.deleted", "discussion_comment.edited", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "projects_v2_item", "projects_v2_item.archived", "projects_v2_item.converted", "projects_v2_item.created", "projects_v2_item.deleted", "projects_v2_item.edited", "projects_v2_item.reordered", "projects_v2_item.restored", "public", "pull_request", "pull_request.assigned", "pull_request.auto_merge_disabled", "pull_request.auto_merge_enabled", "pull_request.closed", "pull_request.converted_to_draft", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "pull_request_review_thread", "pull_request_review_thread.resolved", "pull_request_review_thread.unresolved", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.reopen", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "security_advisory.withdrawn", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_job", "workflow_job.completed", "workflow_job.in_progress", "workflow_job.queued", "workflow_run", "workflow_run.completed", "workflow_run.requested"];
+
+function handleEventHandlers(state, webhookName, handler) {
+ if (!state.hooks[webhookName]) {
+ state.hooks[webhookName] = [];
+ }
+
+ state.hooks[webhookName].push(handler);
+}
+
+function receiverOn(state, webhookNameOrNames, handler) {
+ if (Array.isArray(webhookNameOrNames)) {
+ webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler));
+ return;
+ }
+
+ if (["*", "error"].includes(webhookNameOrNames)) {
+ const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames;
+ const message = `Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`;
+ throw new Error(message);
+ }
+
+ if (!emitterEventNames.includes(webhookNameOrNames)) {
+ state.log.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`);
+ }
+
+ handleEventHandlers(state, webhookNameOrNames, handler);
+}
+function receiverOnAny(state, handler) {
+ handleEventHandlers(state, "*", handler);
+}
+function receiverOnError(state, handler) {
+ handleEventHandlers(state, "error", handler);
+}
+
+// Errors thrown or rejected Promises in "error" event handlers are not handled
+// as they are in the webhook event handlers. If errors occur, we log a
+// "Fatal: Error occurred" message to stdout
+function wrapErrorHandler(handler, error) {
+ let returnValue;
+
+ try {
+ returnValue = handler(error);
+ } catch (error) {
+ console.log('FATAL: Error occurred in "error" event handler');
+ console.log(error);
+ }
+
+ if (returnValue && returnValue.catch) {
+ returnValue.catch(error => {
+ console.log('FATAL: Error occurred in "error" event handler');
+ console.log(error);
+ });
+ }
+}
+
+// @ts-ignore to address #245
+
+function getHooks(state, eventPayloadAction, eventName) {
+ const hooks = [state.hooks[eventName], state.hooks["*"]];
+
+ if (eventPayloadAction) {
+ hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]);
+ }
+
+ return [].concat(...hooks.filter(Boolean));
+} // main handler function
+
+
+function receiverHandle(state, event) {
+ const errorHandlers = state.hooks.error || [];
+
+ if (event instanceof Error) {
+ const error = Object.assign(new AggregateError([event]), {
+ event,
+ errors: [event]
+ });
+ errorHandlers.forEach(handler => wrapErrorHandler(handler, error));
+ return Promise.reject(error);
+ }
+
+ if (!event || !event.name) {
+ throw new AggregateError(["Event name not passed"]);
+ }
+
+ if (!event.payload) {
+ throw new AggregateError(["Event payload not passed"]);
+ } // flatten arrays of event listeners and remove undefined values
+
+
+ const hooks = getHooks(state, "action" in event.payload ? event.payload.action : null, event.name);
+
+ if (hooks.length === 0) {
+ return Promise.resolve();
+ }
+
+ const errors = [];
+ const promises = hooks.map(handler => {
+ let promise = Promise.resolve(event);
+
+ if (state.transform) {
+ promise = promise.then(state.transform);
+ }
+
+ return promise.then(event => {
+ return handler(event);
+ }).catch(error => errors.push(Object.assign(error, {
+ event
+ })));
+ });
+ return Promise.all(promises).then(() => {
+ if (errors.length === 0) {
+ return;
+ }
+
+ const error = new AggregateError(errors);
+ Object.assign(error, {
+ event,
+ errors
+ });
+ errorHandlers.forEach(handler => wrapErrorHandler(handler, error));
+ throw error;
+ });
+}
+
+function removeListener(state, webhookNameOrNames, handler) {
+ if (Array.isArray(webhookNameOrNames)) {
+ webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler));
+ return;
+ }
+
+ if (!state.hooks[webhookNameOrNames]) {
+ return;
+ } // remove last hook that has been added, that way
+ // it behaves the same as removeListener
+
+
+ for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) {
+ if (state.hooks[webhookNameOrNames][i] === handler) {
+ state.hooks[webhookNameOrNames].splice(i, 1);
+ return;
+ }
+ }
+}
+
+function createEventHandler(options) {
+ const state = {
+ hooks: {},
+ log: createLogger(options && options.log)
+ };
+
+ if (options && options.transform) {
+ state.transform = options.transform;
+ }
+
+ return {
+ on: receiverOn.bind(null, state),
+ onAny: receiverOnAny.bind(null, state),
+ onError: receiverOnError.bind(null, state),
+ removeListener: removeListener.bind(null, state),
+ receive: receiverHandle.bind(null, state)
+ };
+}
+
+/**
+ * GitHub sends its JSON with an indentation of 2 spaces and a line break at the end
+ */
+function toNormalizedJsonString(payload) {
+ const payloadString = JSON.stringify(payload);
+ return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, s => {
+ return s.substr(0, 3) + s.substr(3).toUpperCase();
+ });
+}
+
+async function sign(secret, payload) {
+ return webhooksMethods.sign(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload));
+}
+
+async function verify(secret, payload, signature) {
+ return webhooksMethods.verify(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature);
+}
+
+async function verifyAndReceive(state, event) {
+ // verify will validate that the secret is not undefined
+ const matchesSignature = await webhooksMethods.verify(state.secret, typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload, event.signature);
+
+ if (!matchesSignature) {
+ const error = new Error("[@octokit/webhooks] signature does not match event payload and secret");
+ return state.eventHandler.receive(Object.assign(error, {
+ event,
+ status: 400
+ }));
+ }
+
+ return state.eventHandler.receive({
+ id: event.id,
+ name: event.name,
+ payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload
+ });
+}
+
+const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature-256", "x-github-delivery"]; // https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers
+
+function getMissingHeaders(request) {
+ return WEBHOOK_HEADERS.filter(header => !(header in request.headers));
+}
+
+// @ts-ignore to address #245
+function getPayload(request) {
+ // If request.body already exists we can stop here
+ // See https://github.com/octokit/webhooks.js/pull/23
+ if (request.body) return Promise.resolve(request.body);
+ return new Promise((resolve, reject) => {
+ let data = "";
+ request.setEncoding("utf8"); // istanbul ignore next
+
+ request.on("error", error => reject(new AggregateError([error])));
+ request.on("data", chunk => data += chunk);
+ request.on("end", () => {
+ try {
+ resolve(JSON.parse(data));
+ } catch (error) {
+ error.message = "Invalid JSON";
+ error.status = 400;
+ reject(new AggregateError([error]));
+ }
+ });
+ });
+}
+
+async function middleware(webhooks, options, request, response, next) {
+ let pathname;
+
+ try {
+ pathname = new URL(request.url, "http://localhost").pathname;
+ } catch (error) {
+ response.writeHead(422, {
+ "content-type": "application/json"
+ });
+ response.end(JSON.stringify({
+ error: `Request URL could not be parsed: ${request.url}`
+ }));
+ return;
+ }
+
+ const isUnknownRoute = request.method !== "POST" || pathname !== options.path;
+ const isExpressMiddleware = typeof next === "function";
+
+ if (isUnknownRoute) {
+ if (isExpressMiddleware) {
+ return next();
+ } else {
+ return options.onUnhandledRequest(request, response);
+ }
+ }
+
+ const missingHeaders = getMissingHeaders(request).join(", ");
+
+ if (missingHeaders) {
+ response.writeHead(400, {
+ "content-type": "application/json"
+ });
+ response.end(JSON.stringify({
+ error: `Required headers missing: ${missingHeaders}`
+ }));
+ return;
+ }
+
+ const eventName = request.headers["x-github-event"];
+ const signatureSHA256 = request.headers["x-hub-signature-256"];
+ const id = request.headers["x-github-delivery"];
+ options.log.debug(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s
+ // See https://github.com/octokit/webhooks.js/issues/185
+
+ let didTimeout = false;
+ const timeout = setTimeout(() => {
+ didTimeout = true;
+ response.statusCode = 202;
+ response.end("still processing\n");
+ }, 9000).unref();
+
+ try {
+ const payload = await getPayload(request);
+ await webhooks.verifyAndReceive({
+ id: id,
+ name: eventName,
+ payload: payload,
+ signature: signatureSHA256
+ });
+ clearTimeout(timeout);
+ if (didTimeout) return;
+ response.end("ok\n");
+ } catch (error) {
+ clearTimeout(timeout);
+ if (didTimeout) return;
+ const statusCode = Array.from(error)[0].status;
+ response.statusCode = typeof statusCode !== "undefined" ? statusCode : 500;
+ response.end(String(error));
+ }
+}
+
+function onUnhandledRequestDefault(request, response) {
+ response.writeHead(404, {
+ "content-type": "application/json"
+ });
+ response.end(JSON.stringify({
+ error: `Unknown route: ${request.method} ${request.url}`
+ }));
+}
+
+function createNodeMiddleware(webhooks, {
+ path = "/api/github/webhooks",
+ onUnhandledRequest = onUnhandledRequestDefault,
+ log = createLogger()
+} = {}) {
+ return middleware.bind(null, webhooks, {
+ path,
+ onUnhandledRequest,
+ log
+ });
+}
+
+class Webhooks {
+ constructor(options) {
+ if (!options || !options.secret) {
+ throw new Error("[@octokit/webhooks] options.secret required");
+ }
+
+ const state = {
+ eventHandler: createEventHandler(options),
+ secret: options.secret,
+ hooks: {},
+ log: createLogger(options.log)
+ };
+ this.sign = sign.bind(null, options.secret);
+ this.verify = verify.bind(null, options.secret);
+ this.on = state.eventHandler.on;
+ this.onAny = state.eventHandler.onAny;
+ this.onError = state.eventHandler.onError;
+ this.removeListener = state.eventHandler.removeListener;
+ this.receive = state.eventHandler.receive;
+ this.verifyAndReceive = verifyAndReceive.bind(null, state);
+ }
+
+}
+
+exports.Webhooks = Webhooks;
+exports.createEventHandler = createEventHandler;
+exports.createNodeMiddleware = createNodeMiddleware;
+exports.emitterEventNames = emitterEventNames;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 93159:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const ProbotExports = __nccwpck_require__(58930);
+const pino = __nccwpck_require__(77708);
+
+const { transport } = __nccwpck_require__(96645);
+
+module.exports = { ...ProbotExports, run };
+
+async function run(app) {
+ const log = pino({}, transport);
+
+ const githubToken =
+ process.env.GITHUB_TOKEN ||
+ process.env.INPUT_GITHUB_TOKEN ||
+ process.env.INPUT_TOKEN;
+
+ if (!githubToken) {
+ log.error(
+ "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage"
+ );
+ return;
+ }
+
+ const envVariablesMissing = [
+ "GITHUB_RUN_ID",
+ "GITHUB_EVENT_NAME",
+ "GITHUB_EVENT_PATH",
+ ].filter((name) => !process.env[name]);
+
+ if (envVariablesMissing.length) {
+ log.error(
+ `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join(
+ ", "
+ )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables`
+ );
+ return;
+ }
+
+ const probot = ProbotExports.createProbot({
+ overrides: {
+ githubToken,
+ log,
+ },
+ });
+
+ await probot.load(app);
+
+ return probot
+ .receive({
+ id: process.env.GITHUB_RUN_ID,
+ name: process.env.GITHUB_EVENT_NAME,
+ payload: require(process.env.GITHUB_EVENT_PATH),
+ })
+ .catch((error) => {
+ probot.log.error(error);
+ });
+}
+
+
+/***/ }),
+
+/***/ 96645:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const { inspect } = __nccwpck_require__(73837);
+
+const through = __nccwpck_require__(18180);
+const core = __nccwpck_require__(42186);
+const pino = __nccwpck_require__(77708);
+
+const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = {
+ trace: "debug",
+ debug: "debug",
+ info: "info",
+ warn: "warning",
+ error: "error",
+ fatal: "error",
+};
+
+const transport = through.obj(function (chunk, enc, cb) {
+ const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk);
+ const levelLabel = pino.levels.labels[level] || level;
+ const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel];
+
+ const output = [
+ msg,
+ Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "",
+ ]
+ .join("\n")
+ .trim();
+
+ if (logMethodName in core) {
+ core[logMethodName](output);
+ } else {
+ core.error(`"${level}" is not a known log level - ${output}`);
+ }
+
+ cb();
+});
+
+module.exports = { transport };
+
+
+/***/ }),
+
+/***/ 97743:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var path = __nccwpck_require__(71017);
+var fs = __nccwpck_require__(57147);
+var isBase64 = _interopDefault(__nccwpck_require__(31310));
+
+const VERSION = "0.0.0-development";
+
+const begin = "-----BEGIN RSA PRIVATE KEY-----";
+const end = "-----END RSA PRIVATE KEY-----";
+function getPrivateKey(options = {}) {
+ const env = options.env || process.env;
+ const cwd = options.cwd || process.cwd();
+
+ if (options.filepath) {
+ return fs.readFileSync(path.resolve(cwd, options.filepath), "utf-8");
+ }
+
+ if (env.PRIVATE_KEY) {
+ let privateKey = env.PRIVATE_KEY;
+
+ if (isBase64(privateKey)) {
+ // Decode base64-encoded certificate
+ privateKey = Buffer.from(privateKey, "base64").toString();
+ }
+
+ if (privateKey.includes(begin) && privateKey.includes(end)) {
+ // newlines are escaped
+ if (privateKey.indexOf("\\n") !== -1) {
+ privateKey = privateKey.replace(/\\n/g, "\n");
+ } // newlines are missing
+
+
+ if (privateKey.indexOf("\n") === -1) {
+ privateKey = addNewlines(privateKey);
+ }
+
+ return privateKey;
+ }
+
+ throw new Error(`[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.`);
+ }
+
+ if (env.PRIVATE_KEY_PATH) {
+ const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH);
+
+ if (fs.existsSync(filepath)) {
+ return fs.readFileSync(filepath, "utf-8");
+ } else {
+ throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`);
+ }
+ }
+
+ const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem"));
+
+ if (pemFiles.length > 1) {
+ const paths = pemFiles.join(", ");
+ throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`);
+ } else if (pemFiles[0]) {
+ return getPrivateKey({
+ filepath: pemFiles[0],
+ cwd
+ });
+ }
+
+ return null;
+}
+
+function addNewlines(privateKey) {
+ const middleLength = privateKey.length - begin.length - end.length - 2;
+ const middle = privateKey.substr(begin.length + 1, middleLength);
+ return `${begin}\n${middle.trim().replace(/\s+/g, "\n")}\n${end}`;
+}
+
+getPrivateKey.VERSION = VERSION;
+
+exports.getPrivateKey = getPrivateKey;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 59326:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var yaml = _interopDefault(__nccwpck_require__(80557));
+
+const VERSION = "1.1.6";
+
+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 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 _objectSpread2(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;
+}
+
+const SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"];
+/**
+ * Load configuration from a given repository and path.
+ *
+ * @param octokit Octokit instance
+ * @param options
+ */
+
+async function getConfigFile(octokit, {
+ owner,
+ repo,
+ path,
+ ref
+}) {
+ const fileExtension = path.split(".").pop().toLowerCase();
+
+ if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) {
+ throw new Error(`[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")`);
+ } // https://docs.github.com/en/rest/reference/repos#get-repository-content
+
+
+ const endpoint = _objectSpread2({
+ method: "GET",
+ url: "/repos/{owner}/{repo}/contents/{path}",
+ owner,
+ repo,
+ path,
+ mediaType: {
+ format: "raw"
+ }
+ }, ref ? {
+ ref
+ } : {});
+
+ const {
+ url
+ } = await octokit.request.endpoint(endpoint);
+ const emptyConfigResult = {
+ owner,
+ repo,
+ path,
+ url,
+ config: null
+ };
+
+ try {
+ const {
+ data,
+ headers
+ } = await octokit.request(endpoint); // If path is a submodule, or a folder, then a JSON string is returned with
+ // the "Content-Type" header set to "application/json; charset=utf-8".
+ //
+ // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-submodule
+ // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-directory
+ //
+ // symlinks just return the content of the linked file when requesting the raw formt,
+ // so we are fine
+
+ if (headers["content-type"] === "application/json; charset=utf-8") {
+ throw new Error(`[@probot/octokit-plugin-config] ${url} exists, but is either a directory or a submodule. Ignoring.`);
+ }
+
+ if (fileExtension === "json") {
+ if (typeof data === "string") {
+ throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (invalid JSON)`);
+ }
+
+ return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, {
+ config: data
+ });
+ }
+
+ const config = yaml.load(data) || {};
+
+ if (typeof config === "string") {
+ throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (YAML is not an object)`);
+ }
+
+ return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, {
+ config
+ });
+ } catch (error) {
+ if (error.status === 404) {
+ return emptyConfigResult;
+ }
+
+ if (error.name === "YAMLException") {
+ const reason = /unknown tag/.test(error.message) ? "unsafe YAML" : "invalid YAML";
+ throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (${reason})`);
+ }
+
+ throw error;
+ }
+}
+
+const EXTENDS_REGEX = new RegExp("^" + "(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?" + // org
+"([-_.\\w\\d]+)" + // project
+"(?::([-_./\\w\\d]+\\.ya?ml))?" + // filename
+"$", "i");
+/**
+ * Computes parameters to retrieve the configuration file specified in _extends
+ *
+ * Base can either be the name of a repository in the same organization or
+ * a full slug "organization/repo".
+ *
+ * @param options
+ * @return The params needed to retrieve a configuration file
+ */
+
+function extendsToGetContentParams({
+ owner,
+ path,
+ url,
+ extendsValue
+}) {
+ if (typeof extendsValue !== "string") {
+ throw new Error(`[@probot/octokit-plugin-config] Invalid value ${JSON.stringify(extendsValue)} for _extends in ${url}`);
+ }
+
+ const match = extendsValue.match(EXTENDS_REGEX);
+
+ if (match === null) {
+ throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`);
+ }
+
+ return {
+ owner: match[1] || owner,
+ repo: match[2],
+ path: match[3] || path
+ };
+}
+
+/**
+ * Load configuration from selected repository file. If the file does not exist
+ * it loads configuration from the owners `.github` repository.
+ *
+ * If the repository file configuration includes an `_extends` key, that file
+ * is loaded. Same with the target file until no `_extends` key is present.
+ *
+ * @param octokit Octokit instance
+ * @param options
+ */
+
+async function getConfigFiles(octokit, {
+ owner,
+ repo,
+ path,
+ branch
+}) {
+ const requestedRepoFile = await getConfigFile(octokit, {
+ owner,
+ repo,
+ path,
+ ref: branch
+ });
+ const files = [requestedRepoFile]; // if no configuration file present in selected repository,
+ // try to load it from the `.github` repository
+
+ if (!requestedRepoFile.config) {
+ if (repo === ".github") {
+ return files;
+ }
+
+ const defaultRepoConfig = await getConfigFile(octokit, {
+ owner,
+ repo: ".github",
+ path
+ });
+ files.push(defaultRepoConfig);
+ }
+
+ const file = files[files.length - 1]; // if the configuration has no `_extends` key, we are done here.
+
+ if (!file.config || !file.config._extends) {
+ return files;
+ } // parse the value of `_extends` into request parameters to
+ // retrieve the new configuration file
+
+
+ let extendConfigOptions = extendsToGetContentParams({
+ owner,
+ path,
+ url: file.url,
+ extendsValue: file.config._extends
+ }); // remove the `_extends` key from the configuration that is returned
+
+ delete file.config._extends; // now load the configuration linked from the `_extends` key. If that
+ // configuration also includes an `_extends` key, then load that configuration
+ // as well, until the target configuration has no `_extends` key
+
+ do {
+ const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions);
+ files.push(extendRepoConfig);
+
+ if (!extendRepoConfig.config || !extendRepoConfig.config._extends) {
+ return files;
+ }
+
+ extendConfigOptions = extendsToGetContentParams({
+ owner,
+ path,
+ url: extendRepoConfig.url,
+ extendsValue: extendRepoConfig.config._extends
+ });
+ delete extendRepoConfig.config._extends; // Avoid loops
+
+ const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path);
+
+ if (alreadyLoaded) {
+ throw new Error(`[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.`);
+ }
+ } while (true);
+}
+
+/**
+ * Loads configuration from one or multiple files and resolves with
+ * the combined configuration as well as the list of files the configuration
+ * was loaded from
+ *
+ * @param octokit Octokit instance
+ * @param options
+ */
+
+async function composeConfigGet(octokit, {
+ owner,
+ repo,
+ defaults,
+ path,
+ branch
+}) {
+ const files = await getConfigFiles(octokit, {
+ owner,
+ repo,
+ path,
+ branch
+ });
+ const configs = files.map(file => file.config).reverse().filter(Boolean);
+ return {
+ files,
+ config: typeof defaults === "function" ? defaults(configs) : Object.assign({}, defaults, ...configs)
+ };
+}
+
+/**
+ * @param octokit Octokit instance
+ */
+
+function config(octokit) {
+ return {
+ config: {
+ async get(options) {
+ return composeConfigGet(octokit, options);
+ }
+
+ }
+ };
+}
+config.VERSION = VERSION;
+
+exports.composeConfigGet = composeConfigGet;
+exports.config = config;
+//# sourceMappingURL=index.js.map
+
+
+/***/ }),
+
+/***/ 80557:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+
+var loader = __nccwpck_require__(26106);
+var dumper = __nccwpck_require__(73811);
+
+
+function renamed(from, to) {
+ return function () {
+ throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
+ 'Use yaml.' + to + ' instead, which is now safe by default.');
+ };
+}
+
+
+module.exports.Type = __nccwpck_require__(57480);
+module.exports.Schema = __nccwpck_require__(22258);
+module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(54323);
+module.exports.JSON_SCHEMA = __nccwpck_require__(70265);
+module.exports.CORE_SCHEMA = __nccwpck_require__(90085);
+module.exports.DEFAULT_SCHEMA = __nccwpck_require__(77599);
+module.exports.load = loader.load;
+module.exports.loadAll = loader.loadAll;
+module.exports.dump = dumper.dump;
+module.exports.YAMLException = __nccwpck_require__(30780);
+
+// Re-export all types in case user wants to create custom schema
+module.exports.types = {
+ binary: __nccwpck_require__(56942),
+ float: __nccwpck_require__(56128),
+ map: __nccwpck_require__(74352),
+ null: __nccwpck_require__(61002),
+ pairs: __nccwpck_require__(18978),
+ set: __nccwpck_require__(87424),
+ timestamp: __nccwpck_require__(9561),
+ bool: __nccwpck_require__(85327),
+ int: __nccwpck_require__(2848),
+ merge: __nccwpck_require__(70884),
+ omap: __nccwpck_require__(65894),
+ seq: __nccwpck_require__(89695),
+ str: __nccwpck_require__(32568)
+};
+
+// Removed functions from JS-YAML 3.0.x
+module.exports.safeLoad = renamed('safeLoad', 'load');
+module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll');
+module.exports.safeDump = renamed('safeDump', 'dump');
+
+
+/***/ }),
+
+/***/ 44828:
+/***/ ((module) => {
+
+"use strict";
+
+
+
+function isNothing(subject) {
+ return (typeof subject === 'undefined') || (subject === null);
+}
+
+
+function isObject(subject) {
+ return (typeof subject === 'object') && (subject !== null);
+}
+
+
+function toArray(sequence) {
+ if (Array.isArray(sequence)) return sequence;
+ else if (isNothing(sequence)) return [];
+
+ return [ sequence ];
+}
+
+
+function extend(target, source) {
+ var index, length, key, sourceKeys;
+
+ if (source) {
+ sourceKeys = Object.keys(source);
+
+ for (index = 0, length = sourceKeys.length; index < length; index += 1) {
+ key = sourceKeys[index];
+ target[key] = source[key];
+ }
+ }
+
+ return target;
+}
+
+
+function repeat(string, count) {
+ var result = '', cycle;
+
+ for (cycle = 0; cycle < count; cycle += 1) {
+ result += string;
+ }
+
+ return result;
+}
+
+
+function isNegativeZero(number) {
+ return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
+}
+
+
+module.exports.isNothing = isNothing;
+module.exports.isObject = isObject;
+module.exports.toArray = toArray;
+module.exports.repeat = repeat;
+module.exports.isNegativeZero = isNegativeZero;
+module.exports.extend = extend;
+
+
+/***/ }),
+
+/***/ 73811:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+/*eslint-disable no-use-before-define*/
+
+var common = __nccwpck_require__(44828);
+var YAMLException = __nccwpck_require__(30780);
+var DEFAULT_SCHEMA = __nccwpck_require__(77599);
+
+var _toString = Object.prototype.toString;
+var _hasOwnProperty = Object.prototype.hasOwnProperty;
+
+var CHAR_BOM = 0xFEFF;
+var CHAR_TAB = 0x09; /* Tab */
+var CHAR_LINE_FEED = 0x0A; /* LF */
+var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
+var CHAR_SPACE = 0x20; /* Space */
+var CHAR_EXCLAMATION = 0x21; /* ! */
+var CHAR_DOUBLE_QUOTE = 0x22; /* " */
+var CHAR_SHARP = 0x23; /* # */
+var CHAR_PERCENT = 0x25; /* % */
+var CHAR_AMPERSAND = 0x26; /* & */
+var CHAR_SINGLE_QUOTE = 0x27; /* ' */
+var CHAR_ASTERISK = 0x2A; /* * */
+var CHAR_COMMA = 0x2C; /* , */
+var CHAR_MINUS = 0x2D; /* - */
+var CHAR_COLON = 0x3A; /* : */
+var CHAR_EQUALS = 0x3D; /* = */
+var CHAR_GREATER_THAN = 0x3E; /* > */
+var CHAR_QUESTION = 0x3F; /* ? */
+var CHAR_COMMERCIAL_AT = 0x40; /* @ */
+var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
+var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
+var CHAR_GRAVE_ACCENT = 0x60; /* ` */
+var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
+var CHAR_VERTICAL_LINE = 0x7C; /* | */
+var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
+
+var ESCAPE_SEQUENCES = {};
+
+ESCAPE_SEQUENCES[0x00] = '\\0';
+ESCAPE_SEQUENCES[0x07] = '\\a';
+ESCAPE_SEQUENCES[0x08] = '\\b';
+ESCAPE_SEQUENCES[0x09] = '\\t';
+ESCAPE_SEQUENCES[0x0A] = '\\n';
+ESCAPE_SEQUENCES[0x0B] = '\\v';
+ESCAPE_SEQUENCES[0x0C] = '\\f';
+ESCAPE_SEQUENCES[0x0D] = '\\r';
+ESCAPE_SEQUENCES[0x1B] = '\\e';
+ESCAPE_SEQUENCES[0x22] = '\\"';
+ESCAPE_SEQUENCES[0x5C] = '\\\\';
+ESCAPE_SEQUENCES[0x85] = '\\N';
+ESCAPE_SEQUENCES[0xA0] = '\\_';
+ESCAPE_SEQUENCES[0x2028] = '\\L';
+ESCAPE_SEQUENCES[0x2029] = '\\P';
+
+var DEPRECATED_BOOLEANS_SYNTAX = [
+ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
+ 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
+];
+
+var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
+
+function compileStyleMap(schema, map) {
+ var result, keys, index, length, tag, style, type;
+
+ if (map === null) return {};
+
+ result = {};
+ keys = Object.keys(map);
+
+ for (index = 0, length = keys.length; index < length; index += 1) {
+ tag = keys[index];
+ style = String(map[tag]);
+
+ if (tag.slice(0, 2) === '!!') {
+ tag = 'tag:yaml.org,2002:' + tag.slice(2);
+ }
+ type = schema.compiledTypeMap['fallback'][tag];
+
+ if (type && _hasOwnProperty.call(type.styleAliases, style)) {
+ style = type.styleAliases[style];
+ }
+
+ result[tag] = style;
+ }
+
+ return result;
+}
+
+function encodeHex(character) {
+ var string, handle, length;
+
+ string = character.toString(16).toUpperCase();
+
+ if (character <= 0xFF) {
+ handle = 'x';
+ length = 2;
+ } else if (character <= 0xFFFF) {
+ handle = 'u';
+ length = 4;
+ } else if (character <= 0xFFFFFFFF) {
+ handle = 'U';
+ length = 8;
+ } else {
+ throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
+ }
+
+ return '\\' + handle + common.repeat('0', length - string.length) + string;
+}
+
+
+var QUOTING_TYPE_SINGLE = 1,
+ QUOTING_TYPE_DOUBLE = 2;
+
+function State(options) {
+ this.schema = options['schema'] || DEFAULT_SCHEMA;
+ this.indent = Math.max(1, (options['indent'] || 2));
+ this.noArrayIndent = options['noArrayIndent'] || false;
+ this.skipInvalid = options['skipInvalid'] || false;
+ this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
+ this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
+ this.sortKeys = options['sortKeys'] || false;
+ this.lineWidth = options['lineWidth'] || 80;
+ this.noRefs = options['noRefs'] || false;
+ this.noCompatMode = options['noCompatMode'] || false;
+ this.condenseFlow = options['condenseFlow'] || false;
+ this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
+ this.forceQuotes = options['forceQuotes'] || false;
+ this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null;
+
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.explicitTypes = this.schema.compiledExplicit;
+
+ this.tag = null;
+ this.result = '';
+
+ this.duplicates = [];
+ this.usedDuplicates = null;
+}
+
+// Indents every line in a string. Empty lines (\n only) are not indented.
+function indentString(string, spaces) {
+ var ind = common.repeat(' ', spaces),
+ position = 0,
+ next = -1,
+ result = '',
+ line,
+ length = string.length;
+
+ while (position < length) {
+ next = string.indexOf('\n', position);
+ if (next === -1) {
+ line = string.slice(position);
+ position = length;
+ } else {
+ line = string.slice(position, next + 1);
+ position = next + 1;
+ }
+
+ if (line.length && line !== '\n') result += ind;
+
+ result += line;
+ }
+
+ return result;
+}
+
+function generateNextLine(state, level) {
+ return '\n' + common.repeat(' ', state.indent * level);
+}
+
+function testImplicitResolving(state, str) {
+ var index, length, type;
+
+ for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
+ type = state.implicitTypes[index];
+
+ if (type.resolve(str)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// [33] s-white ::= s-space | s-tab
+function isWhitespace(c) {
+ return c === CHAR_SPACE || c === CHAR_TAB;
+}
+
+// Returns true if the character can be printed without escaping.
+// From YAML 1.2: "any allowed characters known to be non-printable
+// should also be escaped. [However,] This isn’t mandatory"
+// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
+function isPrintable(c) {
+ return (0x00020 <= c && c <= 0x00007E)
+ || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
+ || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
+ || (0x10000 <= c && c <= 0x10FFFF);
+}
+
+// [34] ns-char ::= nb-char - s-white
+// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
+// [26] b-char ::= b-line-feed | b-carriage-return
+// Including s-white (for some reason, examples doesn't match specs in this aspect)
+// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
+function isNsCharOrWhitespace(c) {
+ return isPrintable(c)
+ && c !== CHAR_BOM
+ // - b-char
+ && c !== CHAR_CARRIAGE_RETURN
+ && c !== CHAR_LINE_FEED;
+}
+
+// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out
+// c = flow-in ⇒ ns-plain-safe-in
+// c = block-key ⇒ ns-plain-safe-out
+// c = flow-key ⇒ ns-plain-safe-in
+// [128] ns-plain-safe-out ::= ns-char
+// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator
+// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” )
+// | ( /* An ns-char preceding */ “#” )
+// | ( “:” /* Followed by an ns-plain-safe(c) */ )
+function isPlainSafe(c, prev, inblock) {
+ var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
+ var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
+ return (
+ // ns-plain-safe
+ inblock ? // c = flow-in
+ cIsNsCharOrWhitespace
+ : cIsNsCharOrWhitespace
+ // - c-flow-indicator
+ && c !== CHAR_COMMA
+ && c !== CHAR_LEFT_SQUARE_BRACKET
+ && c !== CHAR_RIGHT_SQUARE_BRACKET
+ && c !== CHAR_LEFT_CURLY_BRACKET
+ && c !== CHAR_RIGHT_CURLY_BRACKET
+ )
+ // ns-plain-char
+ && c !== CHAR_SHARP // false on '#'
+ && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
+ || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
+ || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
+}
+
+// Simplified test for values allowed as the first character in plain style.
+function isPlainSafeFirst(c) {
+ // Uses a subset of ns-char - c-indicator
+ // where ns-char = nb-char - s-white.
+ // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
+ return isPrintable(c) && c !== CHAR_BOM
+ && !isWhitespace(c) // - s-white
+ // - (c-indicator ::=
+ // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
+ && c !== CHAR_MINUS
+ && c !== CHAR_QUESTION
+ && c !== CHAR_COLON
+ && c !== CHAR_COMMA
+ && c !== CHAR_LEFT_SQUARE_BRACKET
+ && c !== CHAR_RIGHT_SQUARE_BRACKET
+ && c !== CHAR_LEFT_CURLY_BRACKET
+ && c !== CHAR_RIGHT_CURLY_BRACKET
+ // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
+ && c !== CHAR_SHARP
+ && c !== CHAR_AMPERSAND
+ && c !== CHAR_ASTERISK
+ && c !== CHAR_EXCLAMATION
+ && c !== CHAR_VERTICAL_LINE
+ && c !== CHAR_EQUALS
+ && c !== CHAR_GREATER_THAN
+ && c !== CHAR_SINGLE_QUOTE
+ && c !== CHAR_DOUBLE_QUOTE
+ // | “%” | “@” | “`”)
+ && c !== CHAR_PERCENT
+ && c !== CHAR_COMMERCIAL_AT
+ && c !== CHAR_GRAVE_ACCENT;
+}
+
+// Simplified test for values allowed as the last character in plain style.
+function isPlainSafeLast(c) {
+ // just not whitespace or colon, it will be checked to be plain character later
+ return !isWhitespace(c) && c !== CHAR_COLON;
+}
+
+// Same as 'string'.codePointAt(pos), but works in older browsers.
+function codePointAt(string, pos) {
+ var first = string.charCodeAt(pos), second;
+ if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
+ second = string.charCodeAt(pos + 1);
+ if (second >= 0xDC00 && second <= 0xDFFF) {
+ // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+ return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+ }
+ }
+ return first;
+}
+
+// Determines whether block indentation indicator is required.
+function needIndentIndicator(string) {
+ var leadingSpaceRe = /^\n* /;
+ return leadingSpaceRe.test(string);
+}
+
+var STYLE_PLAIN = 1,
+ STYLE_SINGLE = 2,
+ STYLE_LITERAL = 3,
+ STYLE_FOLDED = 4,
+ STYLE_DOUBLE = 5;
+
+// Determines which scalar styles are possible and returns the preferred style.
+// lineWidth = -1 => no limit.
+// Pre-conditions: str.length > 0.
+// Post-conditions:
+// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
+// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
+// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
+function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
+ testAmbiguousType, quotingType, forceQuotes, inblock) {
+
+ var i;
+ var char = 0;
+ var prevChar = null;
+ var hasLineBreak = false;
+ var hasFoldableLine = false; // only checked if shouldTrackWidth
+ var shouldTrackWidth = lineWidth !== -1;
+ var previousLineBreak = -1; // count the first line correctly
+ var plain = isPlainSafeFirst(codePointAt(string, 0))
+ && isPlainSafeLast(codePointAt(string, string.length - 1));
+
+ if (singleLineOnly || forceQuotes) {
+ // Case: no block styles.
+ // Check for disallowed characters to rule out plain and single.
+ for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
+ char = codePointAt(string, i);
+ if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ plain = plain && isPlainSafe(char, prevChar, inblock);
+ prevChar = char;
+ }
+ } else {
+ // Case: block styles permitted.
+ for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
+ char = codePointAt(string, i);
+ if (char === CHAR_LINE_FEED) {
+ hasLineBreak = true;
+ // Check if any line can be folded.
+ if (shouldTrackWidth) {
+ hasFoldableLine = hasFoldableLine ||
+ // Foldable line = too long, and not more-indented.
+ (i - previousLineBreak - 1 > lineWidth &&
+ string[previousLineBreak + 1] !== ' ');
+ previousLineBreak = i;
+ }
+ } else if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ plain = plain && isPlainSafe(char, prevChar, inblock);
+ prevChar = char;
+ }
+ // in case the end is missing a \n
+ hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
+ (i - previousLineBreak - 1 > lineWidth &&
+ string[previousLineBreak + 1] !== ' '));
+ }
+ // Although every style can represent \n without escaping, prefer block styles
+ // for multiline, since they're more readable and they don't add empty lines.
+ // Also prefer folding a super-long line.
+ if (!hasLineBreak && !hasFoldableLine) {
+ // Strings interpretable as another type have to be quoted;
+ // e.g. the string 'true' vs. the boolean true.
+ if (plain && !forceQuotes && !testAmbiguousType(string)) {
+ return STYLE_PLAIN;
+ }
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
+ }
+ // Edge case: block indentation indicator can only have one digit.
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
+ return STYLE_DOUBLE;
+ }
+ // At this point we know block styles are valid.
+ // Prefer literal style unless we want to fold.
+ if (!forceQuotes) {
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
+ }
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
+}
+
+// Note: line breaking/folding is implemented for only the folded style.
+// NB. We drop the last trailing newline (if any) of a returned block scalar
+// since the dumper adds its own newline. This always works:
+// • No ending newline => unaffected; already using strip "-" chomping.
+// • Ending newline => removed then restored.
+// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
+function writeScalar(state, string, level, iskey, inblock) {
+ state.dump = (function () {
+ if (string.length === 0) {
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
+ }
+ if (!state.noCompatMode) {
+ if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
+ }
+ }
+
+ var indent = state.indent * Math.max(1, level); // no 0-indent scalars
+ // As indentation gets deeper, let the width decrease monotonically
+ // to the lower bound min(state.lineWidth, 40).
+ // Note that this implies
+ // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
+ // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
+ // This behaves better than a constant minimum width which disallows narrower options,
+ // or an indent threshold which causes the width to suddenly increase.
+ var lineWidth = state.lineWidth === -1
+ ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
+
+ // Without knowing if keys are implicit/explicit, assume implicit for safety.
+ var singleLineOnly = iskey
+ // No block styles in flow mode.
+ || (state.flowLevel > -1 && level >= state.flowLevel);
+ function testAmbiguity(string) {
+ return testImplicitResolving(state, string);
+ }
+
+ switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
+ testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
+
+ case STYLE_PLAIN:
+ return string;
+ case STYLE_SINGLE:
+ return "'" + string.replace(/'/g, "''") + "'";
+ case STYLE_LITERAL:
+ return '|' + blockHeader(string, state.indent)
+ + dropEndingNewline(indentString(string, indent));
+ case STYLE_FOLDED:
+ return '>' + blockHeader(string, state.indent)
+ + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
+ case STYLE_DOUBLE:
+ return '"' + escapeString(string, lineWidth) + '"';
+ default:
+ throw new YAMLException('impossible error: invalid scalar style');
+ }
+ }());
+}
+
+// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
+function blockHeader(string, indentPerLevel) {
+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
+
+ // note the special case: the string '\n' counts as a "trailing" empty line.
+ var clip = string[string.length - 1] === '\n';
+ var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
+ var chomp = keep ? '+' : (clip ? '' : '-');
+
+ return indentIndicator + chomp + '\n';
+}
+
+// (See the note for writeScalar.)
+function dropEndingNewline(string) {
+ return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
+}
+
+// Note: a long line without a suitable break point will exceed the width limit.
+// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
+function foldString(string, width) {
+ // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
+ // unless they're before or after a more-indented line, or at the very
+ // beginning or end, in which case $k$ maps to $k$.
+ // Therefore, parse each chunk as newline(s) followed by a content line.
+ var lineRe = /(\n+)([^\n]*)/g;
+
+ // first line (possibly an empty line)
+ var result = (function () {
+ var nextLF = string.indexOf('\n');
+ nextLF = nextLF !== -1 ? nextLF : string.length;
+ lineRe.lastIndex = nextLF;
+ return foldLine(string.slice(0, nextLF), width);
+ }());
+ // If we haven't reached the first content line yet, don't add an extra \n.
+ var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
+ var moreIndented;
+
+ // rest of the lines
+ var match;
+ while ((match = lineRe.exec(string))) {
+ var prefix = match[1], line = match[2];
+ moreIndented = (line[0] === ' ');
+ result += prefix
+ + (!prevMoreIndented && !moreIndented && line !== ''
+ ? '\n' : '')
+ + foldLine(line, width);
+ prevMoreIndented = moreIndented;
+ }
+
+ return result;
+}
+
+// Greedy line breaking.
+// Picks the longest line under the limit each time,
+// otherwise settles for the shortest line over the limit.
+// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
+function foldLine(line, width) {
+ if (line === '' || line[0] === ' ') return line;
+
+ // Since a more-indented line adds a \n, breaks can't be followed by a space.
+ var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
+ var match;
+ // start is an inclusive index. end, curr, and next are exclusive.
+ var start = 0, end, curr = 0, next = 0;
+ var result = '';
+
+ // Invariants: 0 <= start <= length-1.
+ // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
+ // Inside the loop:
+ // A match implies length >= 2, so curr and next are <= length-2.
+ while ((match = breakRe.exec(line))) {
+ next = match.index;
+ // maintain invariant: curr - start <= width
+ if (next - start > width) {
+ end = (curr > start) ? curr : next; // derive end <= length-2
+ result += '\n' + line.slice(start, end);
+ // skip the space that was output as \n
+ start = end + 1; // derive start <= length-1
+ }
+ curr = next;
+ }
+
+ // By the invariants, start <= length-1, so there is something left over.
+ // It is either the whole string or a part starting from non-whitespace.
+ result += '\n';
+ // Insert a break if the remainder is too long and there is a break available.
+ if (line.length - start > width && curr > start) {
+ result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
+ } else {
+ result += line.slice(start);
+ }
+
+ return result.slice(1); // drop extra \n joiner
+}
+
+// Escapes a double-quoted string.
+function escapeString(string) {
+ var result = '';
+ var char = 0;
+ var escapeSeq;
+
+ for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
+ char = codePointAt(string, i);
+ escapeSeq = ESCAPE_SEQUENCES[char];
+
+ if (!escapeSeq && isPrintable(char)) {
+ result += string[i];
+ if (char >= 0x10000) result += string[i + 1];
+ } else {
+ result += escapeSeq || encodeHex(char);
+ }
+ }
+
+ return result;
+}
+
+function writeFlowSequence(state, level, object) {
+ var _result = '',
+ _tag = state.tag,
+ index,
+ length,
+ value;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ value = object[index];
+
+ if (state.replacer) {
+ value = state.replacer.call(object, String(index), value);
+ }
+
+ // Write only valid elements, put null instead of invalid elements.
+ if (writeNode(state, level, value, false, false) ||
+ (typeof value === 'undefined' &&
+ writeNode(state, level, null, false, false))) {
+
+ if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
+ _result += state.dump;
+ }
+ }
+
+ state.tag = _tag;
+ state.dump = '[' + _result + ']';
+}
+
+function writeBlockSequence(state, level, object, compact) {
+ var _result = '',
+ _tag = state.tag,
+ index,
+ length,
+ value;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ value = object[index];
+
+ if (state.replacer) {
+ value = state.replacer.call(object, String(index), value);
+ }
+
+ // Write only valid elements, put null instead of invalid elements.
+ if (writeNode(state, level + 1, value, true, true, false, true) ||
+ (typeof value === 'undefined' &&
+ writeNode(state, level + 1, null, true, true, false, true))) {
+
+ if (!compact || _result !== '') {
+ _result += generateNextLine(state, level);
+ }
+
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ _result += '-';
+ } else {
+ _result += '- ';
+ }
+
+ _result += state.dump;
+ }
+ }
+
+ state.tag = _tag;
+ state.dump = _result || '[]'; // Empty sequence if no valid values.
+}
+
+function writeFlowMapping(state, level, object) {
+ var _result = '',
+ _tag = state.tag,
+ objectKeyList = Object.keys(object),
+ index,
+ length,
+ objectKey,
+ objectValue,
+ pairBuffer;
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+
+ pairBuffer = '';
+ if (_result !== '') pairBuffer += ', ';
+
+ if (state.condenseFlow) pairBuffer += '"';
+
+ objectKey = objectKeyList[index];
+ objectValue = object[objectKey];
+
+ if (state.replacer) {
+ objectValue = state.replacer.call(object, objectKey, objectValue);
+ }
+
+ if (!writeNode(state, level, objectKey, false, false)) {
+ continue; // Skip this pair because of invalid key;
+ }
+
+ if (state.dump.length > 1024) pairBuffer += '? ';
+
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
+
+ if (!writeNode(state, level, objectValue, false, false)) {
+ continue; // Skip this pair because of invalid value.
+ }
+
+ pairBuffer += state.dump;
+
+ // Both key and value are valid.
+ _result += pairBuffer;
+ }
+
+ state.tag = _tag;
+ state.dump = '{' + _result + '}';
+}
+
+function writeBlockMapping(state, level, object, compact) {
+ var _result = '',
+ _tag = state.tag,
+ objectKeyList = Object.keys(object),
+ index,
+ length,
+ objectKey,
+ objectValue,
+ explicitPair,
+ pairBuffer;
+
+ // Allow sorting keys so that the output file is deterministic
+ if (state.sortKeys === true) {
+ // Default sorting
+ objectKeyList.sort();
+ } else if (typeof state.sortKeys === 'function') {
+ // Custom sort function
+ objectKeyList.sort(state.sortKeys);
+ } else if (state.sortKeys) {
+ // Something is wrong
+ throw new YAMLException('sortKeys must be a boolean or a function');
+ }
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ pairBuffer = '';
+
+ if (!compact || _result !== '') {
+ pairBuffer += generateNextLine(state, level);
+ }
+
+ objectKey = objectKeyList[index];
+ objectValue = object[objectKey];
+
+ if (state.replacer) {
+ objectValue = state.replacer.call(object, objectKey, objectValue);
+ }
+
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
+ continue; // Skip this pair because of invalid key.
+ }
+
+ explicitPair = (state.tag !== null && state.tag !== '?') ||
+ (state.dump && state.dump.length > 1024);
+
+ if (explicitPair) {
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += '?';
+ } else {
+ pairBuffer += '? ';
+ }
+ }
+
+ pairBuffer += state.dump;
+
+ if (explicitPair) {
+ pairBuffer += generateNextLine(state, level);
+ }
+
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
+ continue; // Skip this pair because of invalid value.
+ }
+
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += ':';
+ } else {
+ pairBuffer += ': ';
+ }
+
+ pairBuffer += state.dump;
+
+ // Both key and value are valid.
+ _result += pairBuffer;
+ }
+
+ state.tag = _tag;
+ state.dump = _result || '{}'; // Empty mapping if no valid pairs.
+}
+
+function detectType(state, object, explicit) {
+ var _result, typeList, index, length, type, style;
+
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
+
+ for (index = 0, length = typeList.length; index < length; index += 1) {
+ type = typeList[index];
+
+ if ((type.instanceOf || type.predicate) &&
+ (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
+ (!type.predicate || type.predicate(object))) {
+
+ if (explicit) {
+ if (type.multi && type.representName) {
+ state.tag = type.representName(object);
+ } else {
+ state.tag = type.tag;
+ }
+ } else {
+ state.tag = '?';
+ }
+
+ if (type.represent) {
+ style = state.styleMap[type.tag] || type.defaultStyle;
+
+ if (_toString.call(type.represent) === '[object Function]') {
+ _result = type.represent(object, style);
+ } else if (_hasOwnProperty.call(type.represent, style)) {
+ _result = type.represent[style](object, style);
+ } else {
+ throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
+ }
+
+ state.dump = _result;
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// Serializes `object` and writes it to global `result`.
+// Returns true on success, or false on invalid object.
+//
+function writeNode(state, level, object, block, compact, iskey, isblockseq) {
+ state.tag = null;
+ state.dump = object;
+
+ if (!detectType(state, object, false)) {
+ detectType(state, object, true);
+ }
+
+ var type = _toString.call(state.dump);
+ var inblock = block;
+ var tagStr;
+
+ if (block) {
+ block = (state.flowLevel < 0 || state.flowLevel > level);
+ }
+
+ var objectOrArray = type === '[object Object]' || type === '[object Array]',
+ duplicateIndex,
+ duplicate;
+
+ if (objectOrArray) {
+ duplicateIndex = state.duplicates.indexOf(object);
+ duplicate = duplicateIndex !== -1;
+ }
+
+ if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
+ compact = false;
+ }
+
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
+ state.dump = '*ref_' + duplicateIndex;
+ } else {
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
+ state.usedDuplicates[duplicateIndex] = true;
+ }
+ if (type === '[object Object]') {
+ if (block && (Object.keys(state.dump).length !== 0)) {
+ writeBlockMapping(state, level, state.dump, compact);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowMapping(state, level, state.dump);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ }
+ }
+ } else if (type === '[object Array]') {
+ if (block && (state.dump.length !== 0)) {
+ if (state.noArrayIndent && !isblockseq && level > 0) {
+ writeBlockSequence(state, level - 1, state.dump, compact);
+ } else {
+ writeBlockSequence(state, level, state.dump, compact);
+ }
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowSequence(state, level, state.dump);
+ if (duplicate) {
+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
+ }
+ }
+ } else if (type === '[object String]') {
+ if (state.tag !== '?') {
+ writeScalar(state, state.dump, level, iskey, inblock);
+ }
+ } else if (type === '[object Undefined]') {
+ return false;
+ } else {
+ if (state.skipInvalid) return false;
+ throw new YAMLException('unacceptable kind of an object to dump ' + type);
+ }
+
+ if (state.tag !== null && state.tag !== '?') {
+ // Need to encode all characters except those allowed by the spec:
+ //
+ // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
+ // [36] ns-hex-digit ::= ns-dec-digit
+ // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
+ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
+ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
+ // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
+ // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
+ // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
+ //
+ // Also need to encode '!' because it has special meaning (end of tag prefix).
+ //
+ tagStr = encodeURI(
+ state.tag[0] === '!' ? state.tag.slice(1) : state.tag
+ ).replace(/!/g, '%21');
+
+ if (state.tag[0] === '!') {
+ tagStr = '!' + tagStr;
+ } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
+ tagStr = '!!' + tagStr.slice(18);
+ } else {
+ tagStr = '!<' + tagStr + '>';
+ }
+
+ state.dump = tagStr + ' ' + state.dump;
+ }
+ }
+
+ return true;
+}
+
+function getDuplicateReferences(object, state) {
+ var objects = [],
+ duplicatesIndexes = [],
+ index,
+ length;
+
+ inspectNode(object, objects, duplicatesIndexes);
+
+ for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
+ }
+ state.usedDuplicates = new Array(length);
+}
+
+function inspectNode(object, objects, duplicatesIndexes) {
+ var objectKeyList,
+ index,
+ length;
+
+ if (object !== null && typeof object === 'object') {
+ index = objects.indexOf(object);
+ if (index !== -1) {
+ if (duplicatesIndexes.indexOf(index) === -1) {
+ duplicatesIndexes.push(index);
+ }
+ } else {
+ objects.push(object);
+
+ if (Array.isArray(object)) {
+ for (index = 0, length = object.length; index < length; index += 1) {
+ inspectNode(object[index], objects, duplicatesIndexes);
+ }
+ } else {
+ objectKeyList = Object.keys(object);
+
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
+ }
+ }
+ }
+ }
+}
+
+function dump(input, options) {
+ options = options || {};
+
+ var state = new State(options);
+
+ if (!state.noRefs) getDuplicateReferences(input, state);
+
+ var value = input;
+
+ if (state.replacer) {
+ value = state.replacer.call({ '': value }, '', value);
+ }
+
+ if (writeNode(state, 0, value, true, true)) return state.dump + '\n';
+
+ return '';
+}
+
+module.exports.dump = dump;
+
+
+/***/ }),
+
+/***/ 30780:
+/***/ ((module) => {
+
+"use strict";
+// YAML error class. http://stackoverflow.com/questions/8458984
+//
+
+
+
+function formatError(exception, compact) {
+ var where = '', message = exception.reason || '(unknown reason)';
+
+ if (!exception.mark) return message;
+
+ if (exception.mark.name) {
+ where += 'in "' + exception.mark.name + '" ';
+ }
+
+ where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';
+
+ if (!compact && exception.mark.snippet) {
+ where += '\n\n' + exception.mark.snippet;
+ }
+
+ return message + ' ' + where;
+}
+
+
+function YAMLException(reason, mark) {
+ // Super constructor
+ Error.call(this);
+
+ this.name = 'YAMLException';
+ this.reason = reason;
+ this.mark = mark;
+ this.message = formatError(this, false);
+
+ // Include stack trace in error object
+ if (Error.captureStackTrace) {
+ // Chrome and NodeJS
+ Error.captureStackTrace(this, this.constructor);
+ } else {
+ // FF, IE 10+ and Safari 6+. Fallback for others
+ this.stack = (new Error()).stack || '';
+ }
+}
+
+
+// Inherit from Error
+YAMLException.prototype = Object.create(Error.prototype);
+YAMLException.prototype.constructor = YAMLException;
+
+
+YAMLException.prototype.toString = function toString(compact) {
+ return this.name + ': ' + formatError(this, compact);
+};
+
+
+module.exports = YAMLException;
+
+
+/***/ }),
+
+/***/ 26106:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+/*eslint-disable max-len,no-use-before-define*/
+
+var common = __nccwpck_require__(44828);
+var YAMLException = __nccwpck_require__(30780);
+var makeSnippet = __nccwpck_require__(68947);
+var DEFAULT_SCHEMA = __nccwpck_require__(77599);
+
+
+var _hasOwnProperty = Object.prototype.hasOwnProperty;
+
+
+var CONTEXT_FLOW_IN = 1;
+var CONTEXT_FLOW_OUT = 2;
+var CONTEXT_BLOCK_IN = 3;
+var CONTEXT_BLOCK_OUT = 4;
+
+
+var CHOMPING_CLIP = 1;
+var CHOMPING_STRIP = 2;
+var CHOMPING_KEEP = 3;
+
+
+var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
+var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
+var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
+var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
+var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
+
+
+function _class(obj) { return Object.prototype.toString.call(obj); }
+
+function is_EOL(c) {
+ return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
+}
+
+function is_WHITE_SPACE(c) {
+ return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
+}
+
+function is_WS_OR_EOL(c) {
+ return (c === 0x09/* Tab */) ||
+ (c === 0x20/* Space */) ||
+ (c === 0x0A/* LF */) ||
+ (c === 0x0D/* CR */);
+}
+
+function is_FLOW_INDICATOR(c) {
+ return c === 0x2C/* , */ ||
+ c === 0x5B/* [ */ ||
+ c === 0x5D/* ] */ ||
+ c === 0x7B/* { */ ||
+ c === 0x7D/* } */;
+}
+
+function fromHexCode(c) {
+ var lc;
+
+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
+ return c - 0x30;
+ }
+
+ /*eslint-disable no-bitwise*/
+ lc = c | 0x20;
+
+ if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
+ return lc - 0x61 + 10;
+ }
+
+ return -1;
+}
+
+function escapedHexLen(c) {
+ if (c === 0x78/* x */) { return 2; }
+ if (c === 0x75/* u */) { return 4; }
+ if (c === 0x55/* U */) { return 8; }
+ return 0;
+}
+
+function fromDecimalCode(c) {
+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
+ return c - 0x30;
+ }
+
+ return -1;
+}
+
+function simpleEscapeSequence(c) {
+ /* eslint-disable indent */
+ return (c === 0x30/* 0 */) ? '\x00' :
+ (c === 0x61/* a */) ? '\x07' :
+ (c === 0x62/* b */) ? '\x08' :
+ (c === 0x74/* t */) ? '\x09' :
+ (c === 0x09/* Tab */) ? '\x09' :
+ (c === 0x6E/* n */) ? '\x0A' :
+ (c === 0x76/* v */) ? '\x0B' :
+ (c === 0x66/* f */) ? '\x0C' :
+ (c === 0x72/* r */) ? '\x0D' :
+ (c === 0x65/* e */) ? '\x1B' :
+ (c === 0x20/* Space */) ? ' ' :
+ (c === 0x22/* " */) ? '\x22' :
+ (c === 0x2F/* / */) ? '/' :
+ (c === 0x5C/* \ */) ? '\x5C' :
+ (c === 0x4E/* N */) ? '\x85' :
+ (c === 0x5F/* _ */) ? '\xA0' :
+ (c === 0x4C/* L */) ? '\u2028' :
+ (c === 0x50/* P */) ? '\u2029' : '';
+}
+
+function charFromCodepoint(c) {
+ if (c <= 0xFFFF) {
+ return String.fromCharCode(c);
+ }
+ // Encode UTF-16 surrogate pair
+ // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
+ return String.fromCharCode(
+ ((c - 0x010000) >> 10) + 0xD800,
+ ((c - 0x010000) & 0x03FF) + 0xDC00
+ );
+}
+
+var simpleEscapeCheck = new Array(256); // integer, for fast access
+var simpleEscapeMap = new Array(256);
+for (var i = 0; i < 256; i++) {
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
+}
+
+
+function State(input, options) {
+ this.input = input;
+
+ this.filename = options['filename'] || null;
+ this.schema = options['schema'] || DEFAULT_SCHEMA;
+ this.onWarning = options['onWarning'] || null;
+ // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
+ // if such documents have no explicit %YAML directive
+ this.legacy = options['legacy'] || false;
+
+ this.json = options['json'] || false;
+ this.listener = options['listener'] || null;
+
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.typeMap = this.schema.compiledTypeMap;
+
+ this.length = input.length;
+ this.position = 0;
+ this.line = 0;
+ this.lineStart = 0;
+ this.lineIndent = 0;
+
+ // position of first leading tab in the current line,
+ // used to make sure there are no tabs in the indentation
+ this.firstTabInLine = -1;
+
+ this.documents = [];
+
+ /*
+ this.version;
+ this.checkLineBreaks;
+ this.tagMap;
+ this.anchorMap;
+ this.tag;
+ this.anchor;
+ this.kind;
+ this.result;*/
+
+}
+
+
+function generateError(state, message) {
+ var mark = {
+ name: state.filename,
+ buffer: state.input.slice(0, -1), // omit trailing \0
+ position: state.position,
+ line: state.line,
+ column: state.position - state.lineStart
+ };
+
+ mark.snippet = makeSnippet(mark);
+
+ return new YAMLException(message, mark);
+}
+
+function throwError(state, message) {
+ throw generateError(state, message);
+}
+
+function throwWarning(state, message) {
+ if (state.onWarning) {
+ state.onWarning.call(null, generateError(state, message));
+ }
+}
+
+
+var directiveHandlers = {
+
+ YAML: function handleYamlDirective(state, name, args) {
+
+ var match, major, minor;
+
+ if (state.version !== null) {
+ throwError(state, 'duplication of %YAML directive');
+ }
+
+ if (args.length !== 1) {
+ throwError(state, 'YAML directive accepts exactly one argument');
+ }
+
+ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
+
+ if (match === null) {
+ throwError(state, 'ill-formed argument of the YAML directive');
+ }
+
+ major = parseInt(match[1], 10);
+ minor = parseInt(match[2], 10);
+
+ if (major !== 1) {
+ throwError(state, 'unacceptable YAML version of the document');
+ }
+
+ state.version = args[0];
+ state.checkLineBreaks = (minor < 2);
+
+ if (minor !== 1 && minor !== 2) {
+ throwWarning(state, 'unsupported YAML version of the document');
+ }
+ },
+
+ TAG: function handleTagDirective(state, name, args) {
+
+ var handle, prefix;
+
+ if (args.length !== 2) {
+ throwError(state, 'TAG directive accepts exactly two arguments');
+ }
+
+ handle = args[0];
+ prefix = args[1];
+
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
+ throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
+ }
+
+ if (_hasOwnProperty.call(state.tagMap, handle)) {
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
+ }
+
+ if (!PATTERN_TAG_URI.test(prefix)) {
+ throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
+ }
+
+ try {
+ prefix = decodeURIComponent(prefix);
+ } catch (err) {
+ throwError(state, 'tag prefix is malformed: ' + prefix);
+ }
+
+ state.tagMap[handle] = prefix;
+ }
+};
+
+
+function captureSegment(state, start, end, checkJson) {
+ var _position, _length, _character, _result;
+
+ if (start < end) {
+ _result = state.input.slice(start, end);
+
+ if (checkJson) {
+ for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
+ _character = _result.charCodeAt(_position);
+ if (!(_character === 0x09 ||
+ (0x20 <= _character && _character <= 0x10FFFF))) {
+ throwError(state, 'expected valid JSON character');
+ }
+ }
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
+ throwError(state, 'the stream contains non-printable characters');
+ }
+
+ state.result += _result;
+ }
+}
+
+function mergeMappings(state, destination, source, overridableKeys) {
+ var sourceKeys, key, index, quantity;
+
+ if (!common.isObject(source)) {
+ throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
+ }
+
+ sourceKeys = Object.keys(source);
+
+ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
+ key = sourceKeys[index];
+
+ if (!_hasOwnProperty.call(destination, key)) {
+ destination[key] = source[key];
+ overridableKeys[key] = true;
+ }
+ }
+}
+
+function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
+ startLine, startLineStart, startPos) {
+
+ var index, quantity;
+
+ // The output is a plain object here, so keys can only be strings.
+ // We need to convert keyNode to a string, but doing so can hang the process
+ // (deeply nested arrays that explode exponentially using aliases).
+ if (Array.isArray(keyNode)) {
+ keyNode = Array.prototype.slice.call(keyNode);
+
+ for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
+ if (Array.isArray(keyNode[index])) {
+ throwError(state, 'nested arrays are not supported inside keys');
+ }
+
+ if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
+ keyNode[index] = '[object Object]';
+ }
+ }
+ }
+
+ // Avoid code execution in load() via toString property
+ // (still use its own toString for arrays, timestamps,
+ // and whatever user schema extensions happen to have @@toStringTag)
+ if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
+ keyNode = '[object Object]';
+ }
+
+
+ keyNode = String(keyNode);
+
+ if (_result === null) {
+ _result = {};
+ }
+
+ if (keyTag === 'tag:yaml.org,2002:merge') {
+ if (Array.isArray(valueNode)) {
+ for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
+ }
+ } else {
+ mergeMappings(state, _result, valueNode, overridableKeys);
+ }
+ } else {
+ if (!state.json &&
+ !_hasOwnProperty.call(overridableKeys, keyNode) &&
+ _hasOwnProperty.call(_result, keyNode)) {
+ state.line = startLine || state.line;
+ state.lineStart = startLineStart || state.lineStart;
+ state.position = startPos || state.position;
+ throwError(state, 'duplicated mapping key');
+ }
+
+ // used for this specific key only because Object.defineProperty is slow
+ if (keyNode === '__proto__') {
+ Object.defineProperty(_result, keyNode, {
+ configurable: true,
+ enumerable: true,
+ writable: true,
+ value: valueNode
+ });
+ } else {
+ _result[keyNode] = valueNode;
+ }
+ delete overridableKeys[keyNode];
+ }
+
+ return _result;
+}
+
+function readLineBreak(state) {
+ var ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x0A/* LF */) {
+ state.position++;
+ } else if (ch === 0x0D/* CR */) {
+ state.position++;
+ if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
+ state.position++;
+ }
+ } else {
+ throwError(state, 'a line break is expected');
+ }
+
+ state.line += 1;
+ state.lineStart = state.position;
+ state.firstTabInLine = -1;
+}
+
+function skipSeparationSpace(state, allowComments, checkIndent) {
+ var lineBreaks = 0,
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
+ state.firstTabInLine = state.position;
+ }
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (allowComments && ch === 0x23/* # */) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
+ }
+
+ if (is_EOL(ch)) {
+ readLineBreak(state);
+
+ ch = state.input.charCodeAt(state.position);
+ lineBreaks++;
+ state.lineIndent = 0;
+
+ while (ch === 0x20/* Space */) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
+ throwWarning(state, 'deficient indentation');
+ }
+
+ return lineBreaks;
+}
+
+function testDocumentSeparator(state) {
+ var _position = state.position,
+ ch;
+
+ ch = state.input.charCodeAt(_position);
+
+ // Condition state.position === state.lineStart is tested
+ // in parent on each call, for efficiency. No needs to test here again.
+ if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
+ ch === state.input.charCodeAt(_position + 1) &&
+ ch === state.input.charCodeAt(_position + 2)) {
+
+ _position += 3;
+
+ ch = state.input.charCodeAt(_position);
+
+ if (ch === 0 || is_WS_OR_EOL(ch)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function writeFoldedLines(state, count) {
+ if (count === 1) {
+ state.result += ' ';
+ } else if (count > 1) {
+ state.result += common.repeat('\n', count - 1);
+ }
+}
+
+
+function readPlainScalar(state, nodeIndent, withinFlowCollection) {
+ var preceding,
+ following,
+ captureStart,
+ captureEnd,
+ hasPendingContent,
+ _line,
+ _lineStart,
+ _lineIndent,
+ _kind = state.kind,
+ _result = state.result,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (is_WS_OR_EOL(ch) ||
+ is_FLOW_INDICATOR(ch) ||
+ ch === 0x23/* # */ ||
+ ch === 0x26/* & */ ||
+ ch === 0x2A/* * */ ||
+ ch === 0x21/* ! */ ||
+ ch === 0x7C/* | */ ||
+ ch === 0x3E/* > */ ||
+ ch === 0x27/* ' */ ||
+ ch === 0x22/* " */ ||
+ ch === 0x25/* % */ ||
+ ch === 0x40/* @ */ ||
+ ch === 0x60/* ` */) {
+ return false;
+ }
+
+ if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following) ||
+ withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ return false;
+ }
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+
+ while (ch !== 0) {
+ if (ch === 0x3A/* : */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following) ||
+ withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ break;
+ }
+
+ } else if (ch === 0x23/* # */) {
+ preceding = state.input.charCodeAt(state.position - 1);
+
+ if (is_WS_OR_EOL(preceding)) {
+ break;
+ }
+
+ } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
+ withinFlowCollection && is_FLOW_INDICATOR(ch)) {
+ break;
+
+ } else if (is_EOL(ch)) {
+ _line = state.line;
+ _lineStart = state.lineStart;
+ _lineIndent = state.lineIndent;
+ skipSeparationSpace(state, false, -1);
+
+ if (state.lineIndent >= nodeIndent) {
+ hasPendingContent = true;
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ } else {
+ state.position = captureEnd;
+ state.line = _line;
+ state.lineStart = _lineStart;
+ state.lineIndent = _lineIndent;
+ break;
+ }
+ }
+
+ if (hasPendingContent) {
+ captureSegment(state, captureStart, captureEnd, false);
+ writeFoldedLines(state, state.line - _line);
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+ }
+
+ if (!is_WHITE_SPACE(ch)) {
+ captureEnd = state.position + 1;
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ captureSegment(state, captureStart, captureEnd, false);
+
+ if (state.result) {
+ return true;
+ }
+
+ state.kind = _kind;
+ state.result = _result;
+ return false;
+}
+
+function readSingleQuotedScalar(state, nodeIndent) {
+ var ch,
+ captureStart, captureEnd;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x27/* ' */) {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ state.position++;
+ captureStart = captureEnd = state.position;
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 0x27/* ' */) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x27/* ' */) {
+ captureStart = state.position;
+ state.position++;
+ captureEnd = state.position;
+ } else {
+ return true;
+ }
+
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, 'unexpected end of the document within a single quoted scalar');
+
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a single quoted scalar');
+}
+
+function readDoubleQuotedScalar(state, nodeIndent) {
+ var captureStart,
+ captureEnd,
+ hexLength,
+ hexResult,
+ tmp,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x22/* " */) {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+ state.position++;
+ captureStart = captureEnd = state.position;
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 0x22/* " */) {
+ captureSegment(state, captureStart, state.position, true);
+ state.position++;
+ return true;
+
+ } else if (ch === 0x5C/* \ */) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+
+ if (is_EOL(ch)) {
+ skipSeparationSpace(state, false, nodeIndent);
+
+ // TODO: rework to inline fn with no type cast?
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
+ state.result += simpleEscapeMap[ch];
+ state.position++;
+
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
+ hexLength = tmp;
+ hexResult = 0;
+
+ for (; hexLength > 0; hexLength--) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if ((tmp = fromHexCode(ch)) >= 0) {
+ hexResult = (hexResult << 4) + tmp;
+
+ } else {
+ throwError(state, 'expected hexadecimal character');
+ }
+ }
+
+ state.result += charFromCodepoint(hexResult);
+
+ state.position++;
+
+ } else {
+ throwError(state, 'unknown escape sequence');
+ }
+
+ captureStart = captureEnd = state.position;
+
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, 'unexpected end of the document within a double quoted scalar');
+
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a double quoted scalar');
+}
+
+function readFlowCollection(state, nodeIndent) {
+ var readNext = true,
+ _line,
+ _lineStart,
+ _pos,
+ _tag = state.tag,
+ _result,
+ _anchor = state.anchor,
+ following,
+ terminator,
+ isPair,
+ isExplicitPair,
+ isMapping,
+ overridableKeys = Object.create(null),
+ keyNode,
+ keyTag,
+ valueNode,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x5B/* [ */) {
+ terminator = 0x5D;/* ] */
+ isMapping = false;
+ _result = [];
+ } else if (ch === 0x7B/* { */) {
+ terminator = 0x7D;/* } */
+ isMapping = true;
+ _result = {};
+ } else {
+ return false;
+ }
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+
+ while (ch !== 0) {
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === terminator) {
+ state.position++;
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = isMapping ? 'mapping' : 'sequence';
+ state.result = _result;
+ return true;
+ } else if (!readNext) {
+ throwError(state, 'missed comma between flow collection entries');
+ } else if (ch === 0x2C/* , */) {
+ // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
+ throwError(state, "expected the node content, but found ','");
+ }
+
+ keyTag = keyNode = valueNode = null;
+ isPair = isExplicitPair = false;
+
+ if (ch === 0x3F/* ? */) {
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (is_WS_OR_EOL(following)) {
+ isPair = isExplicitPair = true;
+ state.position++;
+ skipSeparationSpace(state, true, nodeIndent);
+ }
+ }
+
+ _line = state.line; // Save the current line.
+ _lineStart = state.lineStart;
+ _pos = state.position;
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ keyTag = state.tag;
+ keyNode = state.result;
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
+ isPair = true;
+ ch = state.input.charCodeAt(++state.position);
+ skipSeparationSpace(state, true, nodeIndent);
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ valueNode = state.result;
+ }
+
+ if (isMapping) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
+ } else if (isPair) {
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
+ } else {
+ _result.push(keyNode);
+ }
+
+ skipSeparationSpace(state, true, nodeIndent);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x2C/* , */) {
+ readNext = true;
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ readNext = false;
+ }
+ }
+
+ throwError(state, 'unexpected end of the stream within a flow collection');
+}
+
+function readBlockScalar(state, nodeIndent) {
+ var captureStart,
+ folding,
+ chomping = CHOMPING_CLIP,
+ didReadContent = false,
+ detectedIndent = false,
+ textIndent = nodeIndent,
+ emptyLines = 0,
+ atMoreIndented = false,
+ tmp,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch === 0x7C/* | */) {
+ folding = false;
+ } else if (ch === 0x3E/* > */) {
+ folding = true;
+ } else {
+ return false;
+ }
+
+ state.kind = 'scalar';
+ state.result = '';
+
+ while (ch !== 0) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
+ if (CHOMPING_CLIP === chomping) {
+ chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
+ } else {
+ throwError(state, 'repeat of a chomping mode identifier');
+ }
+
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
+ if (tmp === 0) {
+ throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
+ } else if (!detectedIndent) {
+ textIndent = nodeIndent + tmp - 1;
+ detectedIndent = true;
+ } else {
+ throwError(state, 'repeat of an indentation width identifier');
+ }
+
+ } else {
+ break;
+ }
+ }
+
+ if (is_WHITE_SPACE(ch)) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (is_WHITE_SPACE(ch));
+
+ if (ch === 0x23/* # */) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (!is_EOL(ch) && (ch !== 0));
+ }
+ }
+
+ while (ch !== 0) {
+ readLineBreak(state);
+ state.lineIndent = 0;
+
+ ch = state.input.charCodeAt(state.position);
+
+ while ((!detectedIndent || state.lineIndent < textIndent) &&
+ (ch === 0x20/* Space */)) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (!detectedIndent && state.lineIndent > textIndent) {
+ textIndent = state.lineIndent;
+ }
+
+ if (is_EOL(ch)) {
+ emptyLines++;
+ continue;
+ }
+
+ // End of the scalar.
+ if (state.lineIndent < textIndent) {
+
+ // Perform the chomping.
+ if (chomping === CHOMPING_KEEP) {
+ state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+ } else if (chomping === CHOMPING_CLIP) {
+ if (didReadContent) { // i.e. only if the scalar is not empty.
+ state.result += '\n';
+ }
+ }
+
+ // Break this `while` cycle and go to the funciton's epilogue.
+ break;
+ }
+
+ // Folded style: use fancy rules to handle line breaks.
+ if (folding) {
+
+ // Lines starting with white space characters (more-indented lines) are not folded.
+ if (is_WHITE_SPACE(ch)) {
+ atMoreIndented = true;
+ // except for the first content line (cf. Example 8.1)
+ state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+
+ // End of more-indented block.
+ } else if (atMoreIndented) {
+ atMoreIndented = false;
+ state.result += common.repeat('\n', emptyLines + 1);
+
+ // Just one line break - perceive as the same line.
+ } else if (emptyLines === 0) {
+ if (didReadContent) { // i.e. only if we have already read some scalar content.
+ state.result += ' ';
+ }
+
+ // Several line breaks - perceive as different lines.
+ } else {
+ state.result += common.repeat('\n', emptyLines);
+ }
+
+ // Literal style: just add exact number of line breaks between content lines.
+ } else {
+ // Keep all line breaks except the header line break.
+ state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
+ }
+
+ didReadContent = true;
+ detectedIndent = true;
+ emptyLines = 0;
+ captureStart = state.position;
+
+ while (!is_EOL(ch) && (ch !== 0)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ captureSegment(state, captureStart, state.position, false);
+ }
+
+ return true;
+}
+
+function readBlockSequence(state, nodeIndent) {
+ var _line,
+ _tag = state.tag,
+ _anchor = state.anchor,
+ _result = [],
+ following,
+ detected = false,
+ ch;
+
+ // there is a leading tab before this token, so it can't be a block sequence/mapping;
+ // it can still be flow sequence/mapping or a scalar
+ if (state.firstTabInLine !== -1) return false;
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ if (state.firstTabInLine !== -1) {
+ state.position = state.firstTabInLine;
+ throwError(state, 'tab characters must not be used in indentation');
+ }
+
+ if (ch !== 0x2D/* - */) {
+ break;
+ }
+
+ following = state.input.charCodeAt(state.position + 1);
+
+ if (!is_WS_OR_EOL(following)) {
+ break;
+ }
+
+ detected = true;
+ state.position++;
+
+ if (skipSeparationSpace(state, true, -1)) {
+ if (state.lineIndent <= nodeIndent) {
+ _result.push(null);
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ }
+ }
+
+ _line = state.line;
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
+ _result.push(state.result);
+ skipSeparationSpace(state, true, -1);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
+ throwError(state, 'bad indentation of a sequence entry');
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = 'sequence';
+ state.result = _result;
+ return true;
+ }
+ return false;
+}
+
+function readBlockMapping(state, nodeIndent, flowIndent) {
+ var following,
+ allowCompact,
+ _line,
+ _keyLine,
+ _keyLineStart,
+ _keyPos,
+ _tag = state.tag,
+ _anchor = state.anchor,
+ _result = {},
+ overridableKeys = Object.create(null),
+ keyTag = null,
+ keyNode = null,
+ valueNode = null,
+ atExplicitKey = false,
+ detected = false,
+ ch;
+
+ // there is a leading tab before this token, so it can't be a block sequence/mapping;
+ // it can still be flow sequence/mapping or a scalar
+ if (state.firstTabInLine !== -1) return false;
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+
+ ch = state.input.charCodeAt(state.position);
+
+ while (ch !== 0) {
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
+ state.position = state.firstTabInLine;
+ throwError(state, 'tab characters must not be used in indentation');
+ }
+
+ following = state.input.charCodeAt(state.position + 1);
+ _line = state.line; // Save the current line.
+
+ //
+ // Explicit notation case. There are two separate blocks:
+ // first for the key (denoted by "?") and second for the value (denoted by ":")
+ //
+ if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
+
+ if (ch === 0x3F/* ? */) {
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ detected = true;
+ atExplicitKey = true;
+ allowCompact = true;
+
+ } else if (atExplicitKey) {
+ // i.e. 0x3A/* : */ === character after the explicit key.
+ atExplicitKey = false;
+ allowCompact = true;
+
+ } else {
+ throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
+ }
+
+ state.position += 1;
+ ch = following;
+
+ //
+ // Implicit notation case. Flow-style node as the key first, then ":", and the value.
+ //
+ } else {
+ _keyLine = state.line;
+ _keyLineStart = state.lineStart;
+ _keyPos = state.position;
+
+ if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
+ // Neither implicit nor explicit notation.
+ // Reading is done. Go to the epilogue.
+ break;
+ }
+
+ if (state.line === _line) {
+ ch = state.input.charCodeAt(state.position);
+
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (ch === 0x3A/* : */) {
+ ch = state.input.charCodeAt(++state.position);
+
+ if (!is_WS_OR_EOL(ch)) {
+ throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
+ }
+
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ detected = true;
+ atExplicitKey = false;
+ allowCompact = false;
+ keyTag = state.tag;
+ keyNode = state.result;
+
+ } else if (detected) {
+ throwError(state, 'can not read an implicit mapping pair; a colon is missed');
+
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true; // Keep the result of `composeNode`.
+ }
+
+ } else if (detected) {
+ throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
+
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true; // Keep the result of `composeNode`.
+ }
+ }
+
+ //
+ // Common reading code for both explicit and implicit notations.
+ //
+ if (state.line === _line || state.lineIndent > nodeIndent) {
+ if (atExplicitKey) {
+ _keyLine = state.line;
+ _keyLineStart = state.lineStart;
+ _keyPos = state.position;
+ }
+
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
+ if (atExplicitKey) {
+ keyNode = state.result;
+ } else {
+ valueNode = state.result;
+ }
+ }
+
+ if (!atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
+ keyTag = keyNode = valueNode = null;
+ }
+
+ skipSeparationSpace(state, true, -1);
+ ch = state.input.charCodeAt(state.position);
+ }
+
+ if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
+ throwError(state, 'bad indentation of a mapping entry');
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+
+ //
+ // Epilogue.
+ //
+
+ // Special case: last mapping's node contains only the key in explicit notation.
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
+ }
+
+ // Expose the resulting mapping.
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = 'mapping';
+ state.result = _result;
+ }
+
+ return detected;
+}
+
+function readTagProperty(state) {
+ var _position,
+ isVerbatim = false,
+ isNamed = false,
+ tagHandle,
+ tagName,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x21/* ! */) return false;
+
+ if (state.tag !== null) {
+ throwError(state, 'duplication of a tag property');
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+
+ if (ch === 0x3C/* < */) {
+ isVerbatim = true;
+ ch = state.input.charCodeAt(++state.position);
+
+ } else if (ch === 0x21/* ! */) {
+ isNamed = true;
+ tagHandle = '!!';
+ ch = state.input.charCodeAt(++state.position);
+
+ } else {
+ tagHandle = '!';
+ }
+
+ _position = state.position;
+
+ if (isVerbatim) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (ch !== 0 && ch !== 0x3E/* > */);
+
+ if (state.position < state.length) {
+ tagName = state.input.slice(_position, state.position);
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ throwError(state, 'unexpected end of the stream within a verbatim tag');
+ }
+ } else {
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+
+ if (ch === 0x21/* ! */) {
+ if (!isNamed) {
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
+
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
+ throwError(state, 'named tag handle cannot contain such characters');
+ }
+
+ isNamed = true;
+ _position = state.position + 1;
+ } else {
+ throwError(state, 'tag suffix cannot contain exclamation marks');
+ }
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ tagName = state.input.slice(_position, state.position);
+
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
+ throwError(state, 'tag suffix cannot contain flow indicator characters');
+ }
+ }
+
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
+ throwError(state, 'tag name cannot contain such characters: ' + tagName);
+ }
+
+ try {
+ tagName = decodeURIComponent(tagName);
+ } catch (err) {
+ throwError(state, 'tag name is malformed: ' + tagName);
+ }
+
+ if (isVerbatim) {
+ state.tag = tagName;
+
+ } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
+ state.tag = state.tagMap[tagHandle] + tagName;
+
+ } else if (tagHandle === '!') {
+ state.tag = '!' + tagName;
+
+ } else if (tagHandle === '!!') {
+ state.tag = 'tag:yaml.org,2002:' + tagName;
+
+ } else {
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
+ }
+
+ return true;
+}
+
+function readAnchorProperty(state) {
+ var _position,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x26/* & */) return false;
+
+ if (state.anchor !== null) {
+ throwError(state, 'duplication of an anchor property');
+ }
+
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (state.position === _position) {
+ throwError(state, 'name of an anchor node must contain at least one character');
+ }
+
+ state.anchor = state.input.slice(_position, state.position);
+ return true;
+}
+
+function readAlias(state) {
+ var _position, alias,
+ ch;
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (ch !== 0x2A/* * */) return false;
+
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (state.position === _position) {
+ throwError(state, 'name of an alias node must contain at least one character');
+ }
+
+ alias = state.input.slice(_position, state.position);
+
+ if (!_hasOwnProperty.call(state.anchorMap, alias)) {
+ throwError(state, 'unidentified alias "' + alias + '"');
+ }
+
+ state.result = state.anchorMap[alias];
+ skipSeparationSpace(state, true, -1);
+ return true;
+}
+
+function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
+ var allowBlockStyles,
+ allowBlockScalars,
+ allowBlockCollections,
+ indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ }
+ }
+
+ if (indentStatus === 1) {
+ while (readTagProperty(state) || readAnchorProperty(state)) {
+ if (skipSeparationSpace(state, true, -1)) {
+ atNewLine = true;
+ allowBlockCollections = allowBlockStyles;
+
+ if (state.lineIndent > parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ } else {
+ allowBlockCollections = false;
+ }
+ }
+ }
+
+ if (allowBlockCollections) {
+ allowBlockCollections = atNewLine || allowCompact;
+ }
+
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
+ flowIndent = parentIndent;
+ } else {
+ flowIndent = parentIndent + 1;
+ }
+
+ blockIndent = state.position - state.lineStart;
+
+ if (indentStatus === 1) {
+ if (allowBlockCollections &&
+ (readBlockSequence(state, blockIndent) ||
+ readBlockMapping(state, blockIndent, flowIndent)) ||
+ readFlowCollection(state, flowIndent)) {
+ hasContent = true;
+ } else {
+ if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
+ readSingleQuotedScalar(state, flowIndent) ||
+ readDoubleQuotedScalar(state, flowIndent)) {
+ hasContent = true;
+
+ } else if (readAlias(state)) {
+ hasContent = true;
+
+ if (state.tag !== null || state.anchor !== null) {
+ throwError(state, 'alias node should not have any properties');
+ }
+
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
+ hasContent = true;
+
+ if (state.tag === null) {
+ state.tag = '?';
+ }
+ }
+
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ } else if (indentStatus === 0) {
+ // Special case: block sequences are allowed to have same indentation level as the parent.
+ // http://www.yaml.org/spec/1.2/spec.html#id2799784
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
+ }
+ }
+
+ if (state.tag === null) {
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+
+ } else if (state.tag === '?') {
+ // Implicit resolving is not allowed for non-scalar types, and '?'
+ // non-specific tag is only automatically assigned to plain scalars.
+ //
+ // We only need to check kind conformity in case user explicitly assigns '?'
+ // tag, for example like this: "!> [0]"
+ //
+ if (state.result !== null && state.kind !== 'scalar') {
+ throwError(state, 'unacceptable node kind for !> tag; it should be "scalar", not "' + state.kind + '"');
+ }
+
+ for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
+ type = state.implicitTypes[typeIndex];
+
+ if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
+ state.result = type.construct(state.result);
+ state.tag = type.tag;
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ break;
+ }
+ }
+ } else if (state.tag !== '!') {
+ if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
+ type = state.typeMap[state.kind || 'fallback'][state.tag];
+ } else {
+ // looking for multi type
+ type = null;
+ typeList = state.typeMap.multi[state.kind || 'fallback'];
+
+ for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
+ if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
+ type = typeList[typeIndex];
+ break;
+ }
+ }
+ }
+
+ if (!type) {
+ throwError(state, 'unknown tag !<' + state.tag + '>');
+ }
+
+ if (state.result !== null && type.kind !== state.kind) {
+ throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
+ }
+
+ if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
+ throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
+ } else {
+ state.result = type.construct(state.result, state.tag);
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ }
+
+ if (state.listener !== null) {
+ state.listener('close', state);
+ }
+ return state.tag !== null || state.anchor !== null || hasContent;
+}
+
+function readDocument(state) {
+ var documentStart = state.position,
+ _position,
+ directiveName,
+ directiveArgs,
+ hasDirectives = false,
+ ch;
+
+ state.version = null;
+ state.checkLineBreaks = state.legacy;
+ state.tagMap = Object.create(null);
+ state.anchorMap = Object.create(null);
+
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ skipSeparationSpace(state, true, -1);
+
+ ch = state.input.charCodeAt(state.position);
+
+ if (state.lineIndent > 0 || ch !== 0x25/* % */) {
+ break;
+ }
+
+ hasDirectives = true;
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ directiveName = state.input.slice(_position, state.position);
+ directiveArgs = [];
+
+ if (directiveName.length < 1) {
+ throwError(state, 'directive name must not be less than one character in length');
+ }
+
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ if (ch === 0x23/* # */) {
+ do { ch = state.input.charCodeAt(++state.position); }
+ while (ch !== 0 && !is_EOL(ch));
+ break;
+ }
+
+ if (is_EOL(ch)) break;
+
+ _position = state.position;
+
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+
+ directiveArgs.push(state.input.slice(_position, state.position));
+ }
+
+ if (ch !== 0) readLineBreak(state);
+
+ if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
+ } else {
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
+ }
+ }
+
+ skipSeparationSpace(state, true, -1);
+
+ if (state.lineIndent === 0 &&
+ state.input.charCodeAt(state.position) === 0x2D/* - */ &&
+ state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
+ state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+
+ } else if (hasDirectives) {
+ throwError(state, 'directives end mark is expected');
+ }
+
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
+ skipSeparationSpace(state, true, -1);
+
+ if (state.checkLineBreaks &&
+ PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
+ throwWarning(state, 'non-ASCII line breaks are interpreted as content');
+ }
+
+ state.documents.push(state.result);
+
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
+
+ if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+ }
+ return;
+ }
+
+ if (state.position < (state.length - 1)) {
+ throwError(state, 'end of the stream or a document separator is expected');
+ } else {
+ return;
+ }
+}
+
+
+function loadDocuments(input, options) {
+ input = String(input);
+ options = options || {};
+
+ if (input.length !== 0) {
+
+ // Add tailing `\n` if not exists
+ if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
+ input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
+ input += '\n';
+ }
+
+ // Strip BOM
+ if (input.charCodeAt(0) === 0xFEFF) {
+ input = input.slice(1);
+ }
+ }
+
+ var state = new State(input, options);
+
+ var nullpos = input.indexOf('\0');
+
+ if (nullpos !== -1) {
+ state.position = nullpos;
+ throwError(state, 'null byte is not allowed in input');
+ }
+
+ // Use 0 as string terminator. That significantly simplifies bounds check.
+ state.input += '\0';
+
+ while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
+ state.lineIndent += 1;
+ state.position += 1;
+ }
+
+ while (state.position < (state.length - 1)) {
+ readDocument(state);
+ }
+
+ return state.documents;
+}
+
+
+function loadAll(input, iterator, options) {
+ if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
+ options = iterator;
+ iterator = null;
+ }
+
+ var documents = loadDocuments(input, options);
+
+ if (typeof iterator !== 'function') {
+ return documents;
+ }
+
+ for (var index = 0, length = documents.length; index < length; index += 1) {
+ iterator(documents[index]);
+ }
+}
+
+
+function load(input, options) {
+ var documents = loadDocuments(input, options);
+
+ if (documents.length === 0) {
+ /*eslint-disable no-undefined*/
+ return undefined;
+ } else if (documents.length === 1) {
+ return documents[0];
+ }
+ throw new YAMLException('expected a single document in the stream, but found more');
+}
+
+
+module.exports.loadAll = loadAll;
+module.exports.load = load;
+
+
+/***/ }),
+
+/***/ 22258:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+/*eslint-disable max-len*/
+
+var YAMLException = __nccwpck_require__(30780);
+var Type = __nccwpck_require__(57480);
+
+
+function compileList(schema, name) {
+ var result = [];
+
+ schema[name].forEach(function (currentType) {
+ var newIndex = result.length;
+
+ result.forEach(function (previousType, previousIndex) {
+ if (previousType.tag === currentType.tag &&
+ previousType.kind === currentType.kind &&
+ previousType.multi === currentType.multi) {
+
+ newIndex = previousIndex;
+ }
+ });
+
+ result[newIndex] = currentType;
+ });
+
+ return result;
+}
+
+
+function compileMap(/* lists... */) {
+ var result = {
+ scalar: {},
+ sequence: {},
+ mapping: {},
+ fallback: {},
+ multi: {
+ scalar: [],
+ sequence: [],
+ mapping: [],
+ fallback: []
+ }
+ }, index, length;
+
+ function collectType(type) {
+ if (type.multi) {
+ result.multi[type.kind].push(type);
+ result.multi['fallback'].push(type);
+ } else {
+ result[type.kind][type.tag] = result['fallback'][type.tag] = type;
+ }
+ }
+
+ for (index = 0, length = arguments.length; index < length; index += 1) {
+ arguments[index].forEach(collectType);
+ }
+ return result;
+}
+
+
+function Schema(definition) {
+ return this.extend(definition);
+}
+
+
+Schema.prototype.extend = function extend(definition) {
+ var implicit = [];
+ var explicit = [];
+
+ if (definition instanceof Type) {
+ // Schema.extend(type)
+ explicit.push(definition);
+
+ } else if (Array.isArray(definition)) {
+ // Schema.extend([ type1, type2, ... ])
+ explicit = explicit.concat(definition);
+
+ } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
+ // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
+ if (definition.implicit) implicit = implicit.concat(definition.implicit);
+ if (definition.explicit) explicit = explicit.concat(definition.explicit);
+
+ } else {
+ throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' +
+ 'or a schema definition ({ implicit: [...], explicit: [...] })');
+ }
+
+ implicit.forEach(function (type) {
+ if (!(type instanceof Type)) {
+ throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ }
+
+ if (type.loadKind && type.loadKind !== 'scalar') {
+ throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
+ }
+
+ if (type.multi) {
+ throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
+ }
+ });
+
+ explicit.forEach(function (type) {
+ if (!(type instanceof Type)) {
+ throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
+ }
+ });
+
+ var result = Object.create(Schema.prototype);
+
+ result.implicit = (this.implicit || []).concat(implicit);
+ result.explicit = (this.explicit || []).concat(explicit);
+
+ result.compiledImplicit = compileList(result, 'implicit');
+ result.compiledExplicit = compileList(result, 'explicit');
+ result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
+
+ return result;
+};
+
+
+module.exports = Schema;
+
+
+/***/ }),
+
+/***/ 90085:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Standard YAML's Core schema.
+// http://www.yaml.org/spec/1.2/spec.html#id2804923
+//
+// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
+// So, Core schema has no distinctions from JSON schema is JS-YAML.
+
+
+
+
+
+module.exports = __nccwpck_require__(70265);
+
+
+/***/ }),
+
+/***/ 77599:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// JS-YAML's default schema for `safeLoad` function.
+// It is not described in the YAML specification.
+//
+// This schema is based on standard YAML's Core schema and includes most of
+// extra types described at YAML tag repository. (http://yaml.org/type/)
+
+
+
+
+
+module.exports = (__nccwpck_require__(90085).extend)({
+ implicit: [
+ __nccwpck_require__(9561),
+ __nccwpck_require__(70884)
+ ],
+ explicit: [
+ __nccwpck_require__(56942),
+ __nccwpck_require__(65894),
+ __nccwpck_require__(18978),
+ __nccwpck_require__(87424)
+ ]
+});
+
+
+/***/ }),
+
+/***/ 54323:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Standard YAML's Failsafe schema.
+// http://www.yaml.org/spec/1.2/spec.html#id2802346
+
+
+
+
+
+var Schema = __nccwpck_require__(22258);
+
+
+module.exports = new Schema({
+ explicit: [
+ __nccwpck_require__(32568),
+ __nccwpck_require__(89695),
+ __nccwpck_require__(74352)
+ ]
+});
+
+
+/***/ }),
+
+/***/ 70265:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+// Standard YAML's JSON schema.
+// http://www.yaml.org/spec/1.2/spec.html#id2803231
+//
+// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
+// So, this schema is not such strict as defined in the YAML specification.
+// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
+
+
+
+
+
+module.exports = (__nccwpck_require__(54323).extend)({
+ implicit: [
+ __nccwpck_require__(61002),
+ __nccwpck_require__(85327),
+ __nccwpck_require__(2848),
+ __nccwpck_require__(56128)
+ ]
+});
+
+
+/***/ }),
+
+/***/ 68947:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+
+var common = __nccwpck_require__(44828);
+
+
+// get snippet for a single line, respecting maxLength
+function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
+ var head = '';
+ var tail = '';
+ var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
+
+ if (position - lineStart > maxHalfLength) {
+ head = ' ... ';
+ lineStart = position - maxHalfLength + head.length;
+ }
+
+ if (lineEnd - position > maxHalfLength) {
+ tail = ' ...';
+ lineEnd = position + maxHalfLength - tail.length;
+ }
+
+ return {
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
+ pos: position - lineStart + head.length // relative position
+ };
+}
+
+
+function padStart(string, max) {
+ return common.repeat(' ', max - string.length) + string;
+}
+
+
+function makeSnippet(mark, options) {
+ options = Object.create(options || null);
+
+ if (!mark.buffer) return null;
+
+ if (!options.maxLength) options.maxLength = 79;
+ if (typeof options.indent !== 'number') options.indent = 1;
+ if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
+ if (typeof options.linesAfter !== 'number') options.linesAfter = 2;
+
+ var re = /\r?\n|\r|\0/g;
+ var lineStarts = [ 0 ];
+ var lineEnds = [];
+ var match;
+ var foundLineNo = -1;
+
+ while ((match = re.exec(mark.buffer))) {
+ lineEnds.push(match.index);
+ lineStarts.push(match.index + match[0].length);
+
+ if (mark.position <= match.index && foundLineNo < 0) {
+ foundLineNo = lineStarts.length - 2;
+ }
+ }
+
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
+
+ var result = '', i, line;
+ var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
+ var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
+
+ for (i = 1; i <= options.linesBefore; i++) {
+ if (foundLineNo - i < 0) break;
+ line = getLine(
+ mark.buffer,
+ lineStarts[foundLineNo - i],
+ lineEnds[foundLineNo - i],
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
+ maxLineLength
+ );
+ result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
+ ' | ' + line.str + '\n' + result;
+ }
+
+ line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
+ result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
+ ' | ' + line.str + '\n';
+ result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';
+
+ for (i = 1; i <= options.linesAfter; i++) {
+ if (foundLineNo + i >= lineEnds.length) break;
+ line = getLine(
+ mark.buffer,
+ lineStarts[foundLineNo + i],
+ lineEnds[foundLineNo + i],
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
+ maxLineLength
+ );
+ result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
+ ' | ' + line.str + '\n';
+ }
+
+ return result.replace(/\n$/, '');
+}
+
+
+module.exports = makeSnippet;
+
+
+/***/ }),
+
+/***/ 57480:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var YAMLException = __nccwpck_require__(30780);
+
+var TYPE_CONSTRUCTOR_OPTIONS = [
+ 'kind',
+ 'multi',
+ 'resolve',
+ 'construct',
+ 'instanceOf',
+ 'predicate',
+ 'represent',
+ 'representName',
+ 'defaultStyle',
+ 'styleAliases'
+];
+
+var YAML_NODE_KINDS = [
+ 'scalar',
+ 'sequence',
+ 'mapping'
+];
+
+function compileStyleAliases(map) {
+ var result = {};
+
+ if (map !== null) {
+ Object.keys(map).forEach(function (style) {
+ map[style].forEach(function (alias) {
+ result[String(alias)] = style;
+ });
+ });
+ }
+
+ return result;
+}
+
+function Type(tag, options) {
+ options = options || {};
+
+ Object.keys(options).forEach(function (name) {
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
+ throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
+ }
+ });
+
+ // TODO: Add tag format check.
+ this.options = options; // keep original options in case user wants to extend this type later
+ this.tag = tag;
+ this.kind = options['kind'] || null;
+ this.resolve = options['resolve'] || function () { return true; };
+ this.construct = options['construct'] || function (data) { return data; };
+ this.instanceOf = options['instanceOf'] || null;
+ this.predicate = options['predicate'] || null;
+ this.represent = options['represent'] || null;
+ this.representName = options['representName'] || null;
+ this.defaultStyle = options['defaultStyle'] || null;
+ this.multi = options['multi'] || false;
+ this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
+
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
+ throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
+ }
+}
+
+module.exports = Type;
+
+
+/***/ }),
+
+/***/ 56942:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+/*eslint-disable no-bitwise*/
+
+
+var Type = __nccwpck_require__(57480);
+
+
+// [ 64, 65, 66 ] -> [ padding, CR, LF ]
+var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
+
+
+function resolveYamlBinary(data) {
+ if (data === null) return false;
+
+ var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
+
+ // Convert one by one.
+ for (idx = 0; idx < max; idx++) {
+ code = map.indexOf(data.charAt(idx));
+
+ // Skip CR/LF
+ if (code > 64) continue;
+
+ // Fail on illegal characters
+ if (code < 0) return false;
+
+ bitlen += 6;
+ }
+
+ // If there are any bits left, source was corrupted
+ return (bitlen % 8) === 0;
+}
+
+function constructYamlBinary(data) {
+ var idx, tailbits,
+ input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
+ max = input.length,
+ map = BASE64_MAP,
+ bits = 0,
+ result = [];
+
+ // Collect by 6*4 bits (3 bytes)
+
+ for (idx = 0; idx < max; idx++) {
+ if ((idx % 4 === 0) && idx) {
+ result.push((bits >> 16) & 0xFF);
+ result.push((bits >> 8) & 0xFF);
+ result.push(bits & 0xFF);
+ }
+
+ bits = (bits << 6) | map.indexOf(input.charAt(idx));
+ }
+
+ // Dump tail
+
+ tailbits = (max % 4) * 6;
+
+ if (tailbits === 0) {
+ result.push((bits >> 16) & 0xFF);
+ result.push((bits >> 8) & 0xFF);
+ result.push(bits & 0xFF);
+ } else if (tailbits === 18) {
+ result.push((bits >> 10) & 0xFF);
+ result.push((bits >> 2) & 0xFF);
+ } else if (tailbits === 12) {
+ result.push((bits >> 4) & 0xFF);
+ }
+
+ return new Uint8Array(result);
+}
+
+function representYamlBinary(object /*, style*/) {
+ var result = '', bits = 0, idx, tail,
+ max = object.length,
+ map = BASE64_MAP;
+
+ // Convert every three bytes to 4 ASCII characters.
+
+ for (idx = 0; idx < max; idx++) {
+ if ((idx % 3 === 0) && idx) {
+ result += map[(bits >> 18) & 0x3F];
+ result += map[(bits >> 12) & 0x3F];
+ result += map[(bits >> 6) & 0x3F];
+ result += map[bits & 0x3F];
+ }
+
+ bits = (bits << 8) + object[idx];
+ }
+
+ // Dump tail
+
+ tail = max % 3;
+
+ if (tail === 0) {
+ result += map[(bits >> 18) & 0x3F];
+ result += map[(bits >> 12) & 0x3F];
+ result += map[(bits >> 6) & 0x3F];
+ result += map[bits & 0x3F];
+ } else if (tail === 2) {
+ result += map[(bits >> 10) & 0x3F];
+ result += map[(bits >> 4) & 0x3F];
+ result += map[(bits << 2) & 0x3F];
+ result += map[64];
+ } else if (tail === 1) {
+ result += map[(bits >> 2) & 0x3F];
+ result += map[(bits << 4) & 0x3F];
+ result += map[64];
+ result += map[64];
+ }
+
+ return result;
+}
+
+function isBinary(obj) {
+ return Object.prototype.toString.call(obj) === '[object Uint8Array]';
+}
+
+module.exports = new Type('tag:yaml.org,2002:binary', {
+ kind: 'scalar',
+ resolve: resolveYamlBinary,
+ construct: constructYamlBinary,
+ predicate: isBinary,
+ represent: representYamlBinary
+});
+
+
+/***/ }),
+
+/***/ 85327:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+function resolveYamlBoolean(data) {
+ if (data === null) return false;
+
+ var max = data.length;
+
+ return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
+ (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
+}
+
+function constructYamlBoolean(data) {
+ return data === 'true' ||
+ data === 'True' ||
+ data === 'TRUE';
+}
+
+function isBoolean(object) {
+ return Object.prototype.toString.call(object) === '[object Boolean]';
+}
+
+module.exports = new Type('tag:yaml.org,2002:bool', {
+ kind: 'scalar',
+ resolve: resolveYamlBoolean,
+ construct: constructYamlBoolean,
+ predicate: isBoolean,
+ represent: {
+ lowercase: function (object) { return object ? 'true' : 'false'; },
+ uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
+ camelcase: function (object) { return object ? 'True' : 'False'; }
+ },
+ defaultStyle: 'lowercase'
+});
+
+
+/***/ }),
+
+/***/ 56128:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var common = __nccwpck_require__(44828);
+var Type = __nccwpck_require__(57480);
+
+var YAML_FLOAT_PATTERN = new RegExp(
+ // 2.5e4, 2.5 and integers
+ '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
+ // .2e4, .2
+ // special case, seems not from spec
+ '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
+ // .inf
+ '|[-+]?\\.(?:inf|Inf|INF)' +
+ // .nan
+ '|\\.(?:nan|NaN|NAN))$');
+
+function resolveYamlFloat(data) {
+ if (data === null) return false;
+
+ if (!YAML_FLOAT_PATTERN.test(data) ||
+ // Quick hack to not allow integers end with `_`
+ // Probably should update regexp & check speed
+ data[data.length - 1] === '_') {
+ return false;
+ }
+
+ return true;
+}
+
+function constructYamlFloat(data) {
+ var value, sign;
+
+ value = data.replace(/_/g, '').toLowerCase();
+ sign = value[0] === '-' ? -1 : 1;
+
+ if ('+-'.indexOf(value[0]) >= 0) {
+ value = value.slice(1);
+ }
+
+ if (value === '.inf') {
+ return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
+
+ } else if (value === '.nan') {
+ return NaN;
+ }
+ return sign * parseFloat(value, 10);
+}
+
+
+var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
+
+function representYamlFloat(object, style) {
+ var res;
+
+ if (isNaN(object)) {
+ switch (style) {
+ case 'lowercase': return '.nan';
+ case 'uppercase': return '.NAN';
+ case 'camelcase': return '.NaN';
+ }
+ } else if (Number.POSITIVE_INFINITY === object) {
+ switch (style) {
+ case 'lowercase': return '.inf';
+ case 'uppercase': return '.INF';
+ case 'camelcase': return '.Inf';
+ }
+ } else if (Number.NEGATIVE_INFINITY === object) {
+ switch (style) {
+ case 'lowercase': return '-.inf';
+ case 'uppercase': return '-.INF';
+ case 'camelcase': return '-.Inf';
+ }
+ } else if (common.isNegativeZero(object)) {
+ return '-0.0';
+ }
+
+ res = object.toString(10);
+
+ // JS stringifier can build scientific format without dots: 5e-100,
+ // while YAML requres dot: 5.e-100. Fix it with simple hack
+
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
+}
+
+function isFloat(object) {
+ return (Object.prototype.toString.call(object) === '[object Number]') &&
+ (object % 1 !== 0 || common.isNegativeZero(object));
+}
+
+module.exports = new Type('tag:yaml.org,2002:float', {
+ kind: 'scalar',
+ resolve: resolveYamlFloat,
+ construct: constructYamlFloat,
+ predicate: isFloat,
+ represent: representYamlFloat,
+ defaultStyle: 'lowercase'
+});
+
+
+/***/ }),
+
+/***/ 2848:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var common = __nccwpck_require__(44828);
+var Type = __nccwpck_require__(57480);
+
+function isHexCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
+ ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
+ ((0x61/* a */ <= c) && (c <= 0x66/* f */));
+}
+
+function isOctCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
+}
+
+function isDecCode(c) {
+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
+}
+
+function resolveYamlInteger(data) {
+ if (data === null) return false;
+
+ var max = data.length,
+ index = 0,
+ hasDigits = false,
+ ch;
+
+ if (!max) return false;
+
+ ch = data[index];
+
+ // sign
+ if (ch === '-' || ch === '+') {
+ ch = data[++index];
+ }
+
+ if (ch === '0') {
+ // 0
+ if (index + 1 === max) return true;
+ ch = data[++index];
+
+ // base 2, base 8, base 16
+
+ if (ch === 'b') {
+ // base 2
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (ch !== '0' && ch !== '1') return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+
+ if (ch === 'x') {
+ // base 16
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isHexCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+
+
+ if (ch === 'o') {
+ // base 8
+ index++;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isOctCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== '_';
+ }
+ }
+
+ // base 10 (except 0)
+
+ // value should not start with `_`;
+ if (ch === '_') return false;
+
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === '_') continue;
+ if (!isDecCode(data.charCodeAt(index))) {
+ return false;
+ }
+ hasDigits = true;
+ }
+
+ // Should have digits and should not end with `_`
+ if (!hasDigits || ch === '_') return false;
+
+ return true;
+}
+
+function constructYamlInteger(data) {
+ var value = data, sign = 1, ch;
+
+ if (value.indexOf('_') !== -1) {
+ value = value.replace(/_/g, '');
+ }
+
+ ch = value[0];
+
+ if (ch === '-' || ch === '+') {
+ if (ch === '-') sign = -1;
+ value = value.slice(1);
+ ch = value[0];
+ }
+
+ if (value === '0') return 0;
+
+ if (ch === '0') {
+ if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
+ if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
+ if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
+ }
+
+ return sign * parseInt(value, 10);
+}
+
+function isInteger(object) {
+ return (Object.prototype.toString.call(object)) === '[object Number]' &&
+ (object % 1 === 0 && !common.isNegativeZero(object));
+}
+
+module.exports = new Type('tag:yaml.org,2002:int', {
+ kind: 'scalar',
+ resolve: resolveYamlInteger,
+ construct: constructYamlInteger,
+ predicate: isInteger,
+ represent: {
+ binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
+ octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); },
+ decimal: function (obj) { return obj.toString(10); },
+ /* eslint-disable max-len */
+ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
+ },
+ defaultStyle: 'decimal',
+ styleAliases: {
+ binary: [ 2, 'bin' ],
+ octal: [ 8, 'oct' ],
+ decimal: [ 10, 'dec' ],
+ hexadecimal: [ 16, 'hex' ]
+ }
+});
+
+
+/***/ }),
+
+/***/ 74352:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+module.exports = new Type('tag:yaml.org,2002:map', {
+ kind: 'mapping',
+ construct: function (data) { return data !== null ? data : {}; }
+});
+
+
+/***/ }),
+
+/***/ 70884:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+function resolveYamlMerge(data) {
+ return data === '<<' || data === null;
+}
+
+module.exports = new Type('tag:yaml.org,2002:merge', {
+ kind: 'scalar',
+ resolve: resolveYamlMerge
+});
+
+
+/***/ }),
+
+/***/ 61002:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+function resolveYamlNull(data) {
+ if (data === null) return true;
+
+ var max = data.length;
+
+ return (max === 1 && data === '~') ||
+ (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
+}
+
+function constructYamlNull() {
+ return null;
+}
+
+function isNull(object) {
+ return object === null;
+}
+
+module.exports = new Type('tag:yaml.org,2002:null', {
+ kind: 'scalar',
+ resolve: resolveYamlNull,
+ construct: constructYamlNull,
+ predicate: isNull,
+ represent: {
+ canonical: function () { return '~'; },
+ lowercase: function () { return 'null'; },
+ uppercase: function () { return 'NULL'; },
+ camelcase: function () { return 'Null'; },
+ empty: function () { return ''; }
+ },
+ defaultStyle: 'lowercase'
+});
+
+
+/***/ }),
+
+/***/ 65894:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+var _hasOwnProperty = Object.prototype.hasOwnProperty;
+var _toString = Object.prototype.toString;
+
+function resolveYamlOmap(data) {
+ if (data === null) return true;
+
+ var objectKeys = [], index, length, pair, pairKey, pairHasKey,
+ object = data;
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+ pairHasKey = false;
+
+ if (_toString.call(pair) !== '[object Object]') return false;
+
+ for (pairKey in pair) {
+ if (_hasOwnProperty.call(pair, pairKey)) {
+ if (!pairHasKey) pairHasKey = true;
+ else return false;
+ }
+ }
+
+ if (!pairHasKey) return false;
+
+ if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
+ else return false;
+ }
+
+ return true;
+}
+
+function constructYamlOmap(data) {
+ return data !== null ? data : [];
+}
+
+module.exports = new Type('tag:yaml.org,2002:omap', {
+ kind: 'sequence',
+ resolve: resolveYamlOmap,
+ construct: constructYamlOmap
+});
+
+
+/***/ }),
+
+/***/ 18978:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+var _toString = Object.prototype.toString;
+
+function resolveYamlPairs(data) {
+ if (data === null) return true;
+
+ var index, length, pair, keys, result,
+ object = data;
+
+ result = new Array(object.length);
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+
+ if (_toString.call(pair) !== '[object Object]') return false;
+
+ keys = Object.keys(pair);
+
+ if (keys.length !== 1) return false;
+
+ result[index] = [ keys[0], pair[keys[0]] ];
+ }
+
+ return true;
+}
+
+function constructYamlPairs(data) {
+ if (data === null) return [];
+
+ var index, length, pair, keys, result,
+ object = data;
+
+ result = new Array(object.length);
+
+ for (index = 0, length = object.length; index < length; index += 1) {
+ pair = object[index];
+
+ keys = Object.keys(pair);
+
+ result[index] = [ keys[0], pair[keys[0]] ];
+ }
+
+ return result;
+}
+
+module.exports = new Type('tag:yaml.org,2002:pairs', {
+ kind: 'sequence',
+ resolve: resolveYamlPairs,
+ construct: constructYamlPairs
+});
+
+
+/***/ }),
+
+/***/ 89695:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+module.exports = new Type('tag:yaml.org,2002:seq', {
+ kind: 'sequence',
+ construct: function (data) { return data !== null ? data : []; }
+});
+
+
+/***/ }),
+
+/***/ 87424:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+var _hasOwnProperty = Object.prototype.hasOwnProperty;
+
+function resolveYamlSet(data) {
+ if (data === null) return true;
+
+ var key, object = data;
+
+ for (key in object) {
+ if (_hasOwnProperty.call(object, key)) {
+ if (object[key] !== null) return false;
+ }
+ }
+
+ return true;
+}
+
+function constructYamlSet(data) {
+ return data !== null ? data : {};
+}
+
+module.exports = new Type('tag:yaml.org,2002:set', {
+ kind: 'mapping',
+ resolve: resolveYamlSet,
+ construct: constructYamlSet
+});
+
+
+/***/ }),
+
+/***/ 32568:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+module.exports = new Type('tag:yaml.org,2002:str', {
+ kind: 'scalar',
+ construct: function (data) { return data !== null ? data : ''; }
+});
+
+
+/***/ }),
+
+/***/ 9561:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var Type = __nccwpck_require__(57480);
+
+var YAML_DATE_REGEXP = new RegExp(
+ '^([0-9][0-9][0-9][0-9])' + // [1] year
+ '-([0-9][0-9])' + // [2] month
+ '-([0-9][0-9])$'); // [3] day
+
+var YAML_TIMESTAMP_REGEXP = new RegExp(
+ '^([0-9][0-9][0-9][0-9])' + // [1] year
+ '-([0-9][0-9]?)' + // [2] month
+ '-([0-9][0-9]?)' + // [3] day
+ '(?:[Tt]|[ \\t]+)' + // ...
+ '([0-9][0-9]?)' + // [4] hour
+ ':([0-9][0-9])' + // [5] minute
+ ':([0-9][0-9])' + // [6] second
+ '(?:\\.([0-9]*))?' + // [7] fraction
+ '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
+ '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
+
+function resolveYamlTimestamp(data) {
+ if (data === null) return false;
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
+ return false;
+}
+
+function constructYamlTimestamp(data) {
+ var match, year, month, day, hour, minute, second, fraction = 0,
+ delta = null, tz_hour, tz_minute, date;
+
+ match = YAML_DATE_REGEXP.exec(data);
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
+
+ if (match === null) throw new Error('Date resolve error');
+
+ // match: [1] year [2] month [3] day
+
+ year = +(match[1]);
+ month = +(match[2]) - 1; // JS month starts with 0
+ day = +(match[3]);
+
+ if (!match[4]) { // no hour
+ return new Date(Date.UTC(year, month, day));
+ }
+
+ // match: [4] hour [5] minute [6] second [7] fraction
+
+ hour = +(match[4]);
+ minute = +(match[5]);
+ second = +(match[6]);
+
+ if (match[7]) {
+ fraction = match[7].slice(0, 3);
+ while (fraction.length < 3) { // milli-seconds
+ fraction += '0';
+ }
+ fraction = +fraction;
+ }
+
+ // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
+
+ if (match[9]) {
+ tz_hour = +(match[10]);
+ tz_minute = +(match[11] || 0);
+ delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
+ if (match[9] === '-') delta = -delta;
+ }
+
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
+
+ if (delta) date.setTime(date.getTime() - delta);
+
+ return date;
+}
+
+function representYamlTimestamp(object /*, style*/) {
+ return object.toISOString();
+}
+
+module.exports = new Type('tag:yaml.org,2002:timestamp', {
+ kind: 'scalar',
+ resolve: resolveYamlTimestamp,
+ construct: constructYamlTimestamp,
+ instanceOf: Date,
+ represent: representYamlTimestamp
+});
+
+
+/***/ }),
+
+/***/ 39662:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+module.exports = { getTransformStream };
+
+const { Transform } = __nccwpck_require__(51642);
+
+const prettyFactory = __nccwpck_require__(67362);
+const Sentry = __nccwpck_require__(22783);
+
+const LEVEL_MAP = {
+ 10: "trace",
+ 20: "debug",
+ 30: "info",
+ 40: "warn",
+ 50: "error",
+ 60: "fatal",
+};
+
+/**
+ * Implements Probot's default logging formatting and error captionaing using Sentry.
+ *
+ * @param {import("./").Options} options
+ * @returns Transform
+ * @see https://getpino.io/#/docs/transports
+ */
+function getTransformStream(options = {}) {
+ const formattingEnabled = options.logFormat !== "json";
+
+ const levelAsString = options.logLevelInString;
+ const sentryEnabled = !!options.sentryDsn;
+
+ if (sentryEnabled) {
+ Sentry.init({
+ dsn: options.sentryDsn,
+ // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615
+ // 6 is enough to serialize the deepest property across all GitHub Event payloads
+ normalizeDepth: 6,
+ });
+ }
+
+ const pretty = prettyFactory({
+ ignore: [
+ // default pino keys
+ "time",
+ "pid",
+ "hostname",
+ // remove keys from pino-http
+ "req",
+ "res",
+ "responseTime",
+ ].join(","),
+ errorProps: ["event", "status", "headers", "request", "sentryEventId"].join(
+ ","
+ ),
+ });
+
+ return new Transform({
+ objectMode: true,
+ transform(chunk, enc, cb) {
+ const line = chunk.toString().trim();
+
+ /* istanbul ignore if */
+ if (line === undefined) return cb();
+
+ const data = sentryEnabled ? JSON.parse(line) : null;
+
+ if (!sentryEnabled || data.level < 50) {
+ if (formattingEnabled) {
+ return cb(null, pretty(line));
+ }
+
+ if (levelAsString) {
+ return cb(null, stringifyLogLevel(JSON.parse(line)));
+ }
+
+ cb(null, line + "\n");
+ return;
+ }
+
+ Sentry.withScope(function (scope) {
+ const sentryLevelName =
+ data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal;
+ scope.setLevel(sentryLevelName);
+
+ for (const extra of ["event", "headers", "request", "status"]) {
+ if (!data[extra]) continue;
+
+ scope.setExtra(extra, data[extra]);
+ }
+
+ // set user id and username to installation ID and account login
+ if (data.event && data.event.payload) {
+ const {
+ // When GitHub App is installed organization wide
+ installation: { id, account: { login: account } = {} } = {},
+
+ // When the repository belongs to an organization
+ organization: { login: organization } = {},
+ // When the repository belongs to a user
+ repository: { owner: { login: owner } = {} } = {},
+ } = data.event.payload;
+
+ scope.setUser({
+ id: id,
+ username: account || organization || owner,
+ });
+ }
+
+ const sentryEventId = Sentry.captureException(toSentryError(data));
+
+ // reduce logging data and add reference to sentry event instead
+ if (data.event) {
+ data.event = { id: data.event.id };
+ }
+ if (data.request) {
+ data.request = {
+ method: data.request.method,
+ url: data.request.url,
+ };
+ }
+ data.sentryEventId = sentryEventId;
+
+ if (formattingEnabled) {
+ return cb(null, pretty(data));
+ }
+
+ // istanbul ignore if
+ if (levelAsString) {
+ return cb(null, stringifyLogLevel(data));
+ }
+
+ cb(null, JSON.stringify(data) + "\n");
+ });
+ },
+ });
+}
+
+function stringifyLogLevel(data) {
+ data.level = LEVEL_MAP[data.level];
+ return JSON.stringify(data) + "\n";
+}
+
+function toSentryError(data) {
+ const error = new Error(data.msg);
+ error.name = data.type;
+ error.stack = data.stack;
+ return error;
+}
+
+
+/***/ }),
+
+/***/ 90785:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+var SENTRY_API_VERSION = '7';
+/**
+ * Helper class to provide urls, headers and metadata that can be used to form
+ * different types of requests to Sentry endpoints.
+ * Supports both envelopes and regular event requests.
+ *
+ * @deprecated Please use APIDetails
+ **/
+var API = /** @class */ (function () {
+ /** Create a new instance of API */
+ function API(dsn, metadata, tunnel) {
+ if (metadata === void 0) { metadata = {}; }
+ this.dsn = dsn;
+ this._dsnObject = utils_1.makeDsn(dsn);
+ this.metadata = metadata;
+ this._tunnel = tunnel;
+ }
+ /** Returns the Dsn object. */
+ API.prototype.getDsn = function () {
+ return this._dsnObject;
+ };
+ /** Does this transport force envelopes? */
+ API.prototype.forceEnvelope = function () {
+ return !!this._tunnel;
+ };
+ /** Returns the prefix to construct Sentry ingestion API endpoints. */
+ API.prototype.getBaseApiEndpoint = function () {
+ return getBaseApiEndpoint(this._dsnObject);
+ };
+ /** Returns the store endpoint URL. */
+ API.prototype.getStoreEndpoint = function () {
+ return getStoreEndpoint(this._dsnObject);
+ };
+ /**
+ * Returns the store endpoint URL with auth in the query string.
+ *
+ * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
+ */
+ API.prototype.getStoreEndpointWithUrlEncodedAuth = function () {
+ return getStoreEndpointWithUrlEncodedAuth(this._dsnObject);
+ };
+ /**
+ * Returns the envelope endpoint URL with auth in the query string.
+ *
+ * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
+ */
+ API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () {
+ return getEnvelopeEndpointWithUrlEncodedAuth(this._dsnObject, this._tunnel);
+ };
+ return API;
+}());
+exports.API = API;
+/** Initializes API Details */
+function initAPIDetails(dsn, metadata, tunnel) {
+ return {
+ initDsn: dsn,
+ metadata: metadata || {},
+ dsn: utils_1.makeDsn(dsn),
+ tunnel: tunnel,
+ };
+}
+exports.initAPIDetails = initAPIDetails;
+/** Returns the prefix to construct Sentry ingestion API endpoints. */
+function getBaseApiEndpoint(dsn) {
+ var protocol = dsn.protocol ? dsn.protocol + ":" : '';
+ var port = dsn.port ? ":" + dsn.port : '';
+ return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/";
+}
+/** Returns the ingest API endpoint for target. */
+function _getIngestEndpoint(dsn, target) {
+ return "" + getBaseApiEndpoint(dsn) + dsn.projectId + "/" + target + "/";
+}
+/** Returns a URL-encoded string with auth config suitable for a query string. */
+function _encodedAuth(dsn) {
+ return utils_1.urlEncode({
+ // We send only the minimum set of required information. See
+ // https://github.com/getsentry/sentry-javascript/issues/2572.
+ sentry_key: dsn.publicKey,
+ sentry_version: SENTRY_API_VERSION,
+ });
+}
+/** Returns the store endpoint URL. */
+function getStoreEndpoint(dsn) {
+ return _getIngestEndpoint(dsn, 'store');
+}
+/**
+ * Returns the store endpoint URL with auth in the query string.
+ *
+ * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
+ */
+function getStoreEndpointWithUrlEncodedAuth(dsn) {
+ return getStoreEndpoint(dsn) + "?" + _encodedAuth(dsn);
+}
+exports.getStoreEndpointWithUrlEncodedAuth = getStoreEndpointWithUrlEncodedAuth;
+/** Returns the envelope endpoint URL. */
+function _getEnvelopeEndpoint(dsn) {
+ return _getIngestEndpoint(dsn, 'envelope');
+}
+/**
+ * Returns the envelope endpoint URL with auth in the query string.
+ *
+ * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
+ */
+function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel) {
+ return tunnel ? tunnel : _getEnvelopeEndpoint(dsn) + "?" + _encodedAuth(dsn);
+}
+exports.getEnvelopeEndpointWithUrlEncodedAuth = getEnvelopeEndpointWithUrlEncodedAuth;
+/**
+ * Returns an object that can be used in request headers.
+ * This is needed for node and the old /store endpoint in sentry
+ */
+function getRequestHeaders(dsn, clientName, clientVersion) {
+ // CHANGE THIS to use metadata but keep clientName and clientVersion compatible
+ var header = ["Sentry sentry_version=" + SENTRY_API_VERSION];
+ header.push("sentry_client=" + clientName + "/" + clientVersion);
+ header.push("sentry_key=" + dsn.publicKey);
+ if (dsn.pass) {
+ header.push("sentry_secret=" + dsn.pass);
+ }
+ return {
+ 'Content-Type': 'application/json',
+ 'X-Sentry-Auth': header.join(', '),
+ };
+}
+exports.getRequestHeaders = getRequestHeaders;
+/** Returns the url to the report dialog endpoint. */
+function getReportDialogEndpoint(dsnLike, dialogOptions) {
+ var dsn = utils_1.makeDsn(dsnLike);
+ var endpoint = getBaseApiEndpoint(dsn) + "embed/error-page/";
+ var encodedOptions = "dsn=" + utils_1.dsnToString(dsn);
+ for (var key in dialogOptions) {
+ if (key === 'dsn') {
+ continue;
+ }
+ if (key === 'user') {
+ if (!dialogOptions.user) {
+ continue;
+ }
+ if (dialogOptions.user.name) {
+ encodedOptions += "&name=" + encodeURIComponent(dialogOptions.user.name);
+ }
+ if (dialogOptions.user.email) {
+ encodedOptions += "&email=" + encodeURIComponent(dialogOptions.user.email);
+ }
+ }
+ else {
+ encodedOptions += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key]);
+ }
+ }
+ return endpoint + "?" + encodedOptions;
+}
+exports.getReportDialogEndpoint = getReportDialogEndpoint;
+//# sourceMappingURL=api.js.map
+
+/***/ }),
+
+/***/ 25886:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var utils_1 = __nccwpck_require__(1620);
+var api_1 = __nccwpck_require__(90785);
+var flags_1 = __nccwpck_require__(91839);
+var request_1 = __nccwpck_require__(1553);
+var noop_1 = __nccwpck_require__(68641);
+/**
+ * This is the base implemention of a Backend.
+ * @hidden
+ */
+var BaseBackend = /** @class */ (function () {
+ /** Creates a new backend instance. */
+ function BaseBackend(options) {
+ this._options = options;
+ if (!this._options.dsn) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('No DSN provided, backend will not do anything.');
+ }
+ this._transport = this._setupTransport();
+ }
+ /**
+ * @inheritDoc
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
+ BaseBackend.prototype.eventFromException = function (_exception, _hint) {
+ throw new utils_1.SentryError('Backend has to implement `eventFromException` method');
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) {
+ throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method');
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseBackend.prototype.sendEvent = function (event) {
+ // TODO(v7): Remove the if-else
+ if (this._newTransport &&
+ this._options.dsn &&
+ this._options._experiments &&
+ this._options._experiments.newTransport) {
+ var api = api_1.initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);
+ var env = request_1.createEventEnvelope(event, api);
+ void this._newTransport.send(env).then(null, function (reason) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error('Error while sending event:', reason);
+ });
+ }
+ else {
+ void this._transport.sendEvent(event).then(null, function (reason) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error('Error while sending event:', reason);
+ });
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseBackend.prototype.sendSession = function (session) {
+ if (!this._transport.sendSession) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession");
+ return;
+ }
+ // TODO(v7): Remove the if-else
+ if (this._newTransport &&
+ this._options.dsn &&
+ this._options._experiments &&
+ this._options._experiments.newTransport) {
+ var api = api_1.initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel);
+ var _a = tslib_1.__read(request_1.createSessionEnvelope(session, api), 1), env = _a[0];
+ void this._newTransport.send(env).then(null, function (reason) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error('Error while sending session:', reason);
+ });
+ }
+ else {
+ void this._transport.sendSession(session).then(null, function (reason) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error('Error while sending session:', reason);
+ });
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseBackend.prototype.getTransport = function () {
+ return this._transport;
+ };
+ /**
+ * Sets up the transport so it can be used later to send requests.
+ */
+ BaseBackend.prototype._setupTransport = function () {
+ return new noop_1.NoopTransport();
+ };
+ return BaseBackend;
+}());
+exports.BaseBackend = BaseBackend;
+//# sourceMappingURL=basebackend.js.map
+
+/***/ }),
+
+/***/ 25684:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+/* eslint-disable max-lines */
+var hub_1 = __nccwpck_require__(6393);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(91839);
+var integration_1 = __nccwpck_require__(58500);
+var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
+/**
+ * Base implementation for all JavaScript SDK clients.
+ *
+ * Call the constructor with the corresponding backend constructor and options
+ * specific to the client subclass. To access these options later, use
+ * {@link Client.getOptions}. Also, the Backend instance is available via
+ * {@link Client.getBackend}.
+ *
+ * If a Dsn is specified in the options, it will be parsed and stored. Use
+ * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is
+ * invalid, the constructor will throw a {@link SentryException}. Note that
+ * without a valid Dsn, the SDK will not send any events to Sentry.
+ *
+ * Before sending an event via the backend, it is passed through
+ * {@link BaseClient._prepareEvent} to add SDK information and scope data
+ * (breadcrumbs and context). To add more custom information, override this
+ * method and extend the resulting prepared event.
+ *
+ * To issue automatically created events (e.g. via instrumentation), use
+ * {@link Client.captureEvent}. It will prepare the event and pass it through
+ * the callback lifecycle. To issue auto-breadcrumbs, use
+ * {@link Client.addBreadcrumb}.
+ *
+ * @example
+ * class NodeClient extends BaseClient {
+ * public constructor(options: NodeOptions) {
+ * super(NodeBackend, options);
+ * }
+ *
+ * // ...
+ * }
+ */
+var BaseClient = /** @class */ (function () {
+ /**
+ * Initializes this client instance.
+ *
+ * @param backendClass A constructor function to create the backend.
+ * @param options Options for the client.
+ */
+ function BaseClient(backendClass, options) {
+ /** Array of used integrations. */
+ this._integrations = {};
+ /** Number of calls being processed */
+ this._numProcessing = 0;
+ this._backend = new backendClass(options);
+ this._options = options;
+ if (options.dsn) {
+ this._dsn = utils_1.makeDsn(options.dsn);
+ }
+ }
+ /**
+ * @inheritDoc
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
+ BaseClient.prototype.captureException = function (exception, hint, scope) {
+ var _this = this;
+ // ensure we haven't captured this very object before
+ if (utils_1.checkOrSetAlreadyCaught(exception)) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.log(ALREADY_SEEN_ERROR);
+ return;
+ }
+ var eventId = hint && hint.event_id;
+ this._process(this._getBackend()
+ .eventFromException(exception, hint)
+ .then(function (event) { return _this._captureEvent(event, hint, scope); })
+ .then(function (result) {
+ eventId = result;
+ }));
+ return eventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.captureMessage = function (message, level, hint, scope) {
+ var _this = this;
+ var eventId = hint && hint.event_id;
+ var promisedEvent = utils_1.isPrimitive(message)
+ ? this._getBackend().eventFromMessage(String(message), level, hint)
+ : this._getBackend().eventFromException(message, hint);
+ this._process(promisedEvent
+ .then(function (event) { return _this._captureEvent(event, hint, scope); })
+ .then(function (result) {
+ eventId = result;
+ }));
+ return eventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.captureEvent = function (event, hint, scope) {
+ // ensure we haven't captured this very object before
+ if (hint && hint.originalException && utils_1.checkOrSetAlreadyCaught(hint.originalException)) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.log(ALREADY_SEEN_ERROR);
+ return;
+ }
+ var eventId = hint && hint.event_id;
+ this._process(this._captureEvent(event, hint, scope).then(function (result) {
+ eventId = result;
+ }));
+ return eventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.captureSession = function (session) {
+ if (!this._isEnabled()) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('SDK not enabled, will not capture session.');
+ return;
+ }
+ if (!(typeof session.release === 'string')) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('Discarded session because of missing or non-string release');
+ }
+ else {
+ this._sendSession(session);
+ // After sending, we set init false to indicate it's not the first occurrence
+ session.update({ init: false });
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.getDsn = function () {
+ return this._dsn;
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.getOptions = function () {
+ return this._options;
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.getTransport = function () {
+ return this._getBackend().getTransport();
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.flush = function (timeout) {
+ var _this = this;
+ return this._isClientDoneProcessing(timeout).then(function (clientFinished) {
+ return _this.getTransport()
+ .close(timeout)
+ .then(function (transportFlushed) { return clientFinished && transportFlushed; });
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.close = function (timeout) {
+ var _this = this;
+ return this.flush(timeout).then(function (result) {
+ _this.getOptions().enabled = false;
+ return result;
+ });
+ };
+ /**
+ * Sets up the integrations
+ */
+ BaseClient.prototype.setupIntegrations = function () {
+ if (this._isEnabled() && !this._integrations.initialized) {
+ this._integrations = integration_1.setupIntegrations(this._options);
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseClient.prototype.getIntegration = function (integration) {
+ try {
+ return this._integrations[integration.id] || null;
+ }
+ catch (_oO) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client");
+ return null;
+ }
+ };
+ /** Updates existing session based on the provided event */
+ BaseClient.prototype._updateSessionFromEvent = function (session, event) {
+ var e_1, _a;
+ var crashed = false;
+ var errored = false;
+ var exceptions = event.exception && event.exception.values;
+ if (exceptions) {
+ errored = true;
+ try {
+ for (var exceptions_1 = tslib_1.__values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) {
+ var ex = exceptions_1_1.value;
+ var mechanism = ex.mechanism;
+ if (mechanism && mechanism.handled === false) {
+ crashed = true;
+ break;
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ }
+ // A session is updated and that session update is sent in only one of the two following scenarios:
+ // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update
+ // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update
+ var sessionNonTerminal = session.status === 'ok';
+ var shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);
+ if (shouldUpdateAndSend) {
+ session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: 'crashed' })), { errors: session.errors || Number(errored || crashed) }));
+ this.captureSession(session);
+ }
+ };
+ /** Deliver captured session to Sentry */
+ BaseClient.prototype._sendSession = function (session) {
+ this._getBackend().sendSession(session);
+ };
+ /**
+ * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying
+ * "no" (resolving to `false`) in order to give the client a chance to potentially finish first.
+ *
+ * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not
+ * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to
+ * `true`.
+ * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and
+ * `false` otherwise
+ */
+ BaseClient.prototype._isClientDoneProcessing = function (timeout) {
+ var _this = this;
+ return new utils_1.SyncPromise(function (resolve) {
+ var ticked = 0;
+ var tick = 1;
+ var interval = setInterval(function () {
+ if (_this._numProcessing == 0) {
+ clearInterval(interval);
+ resolve(true);
+ }
+ else {
+ ticked += tick;
+ if (timeout && ticked >= timeout) {
+ clearInterval(interval);
+ resolve(false);
+ }
+ }
+ }, tick);
+ });
+ };
+ /** Returns the current backend. */
+ BaseClient.prototype._getBackend = function () {
+ return this._backend;
+ };
+ /** Determines whether this SDK is enabled and a valid Dsn is present. */
+ BaseClient.prototype._isEnabled = function () {
+ return this.getOptions().enabled !== false && this._dsn !== undefined;
+ };
+ /**
+ * Adds common information to events.
+ *
+ * The information includes release and environment from `options`,
+ * breadcrumbs and context (extra, tags and user) from the scope.
+ *
+ * Information that is already present in the event is never overwritten. For
+ * nested objects, such as the context, keys are merged.
+ *
+ * @param event The original event.
+ * @param hint May contain additional information about the original exception.
+ * @param scope A scope containing event metadata.
+ * @returns A new event with more information.
+ */
+ BaseClient.prototype._prepareEvent = function (event, scope, hint) {
+ var _this = this;
+ var _a = this.getOptions(), _b = _a.normalizeDepth, normalizeDepth = _b === void 0 ? 3 : _b, _c = _a.normalizeMaxBreadth, normalizeMaxBreadth = _c === void 0 ? 1000 : _c;
+ var prepared = tslib_1.__assign(tslib_1.__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : utils_1.uuid4()), timestamp: event.timestamp || utils_1.dateTimestampInSeconds() });
+ this._applyClientOptions(prepared);
+ this._applyIntegrationsMetadata(prepared);
+ // If we have scope given to us, use it as the base for further modifications.
+ // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.
+ var finalScope = scope;
+ if (hint && hint.captureContext) {
+ finalScope = hub_1.Scope.clone(finalScope).update(hint.captureContext);
+ }
+ // We prepare the result here with a resolved Event.
+ var result = utils_1.resolvedSyncPromise(prepared);
+ // This should be the last thing called, since we want that
+ // {@link Hub.addEventProcessor} gets the finished prepared event.
+ if (finalScope) {
+ // In case we have a hub we reassign it.
+ result = finalScope.applyToEvent(prepared, hint);
+ }
+ return result.then(function (evt) {
+ if (evt) {
+ // TODO this is more of the hack trying to solve https://github.com/getsentry/sentry-javascript/issues/2809
+ // it is only attached as extra data to the event if the event somehow skips being normalized
+ evt.sdkProcessingMetadata = tslib_1.__assign(tslib_1.__assign({}, evt.sdkProcessingMetadata), { normalizeDepth: utils_1.normalize(normalizeDepth) + " (" + typeof normalizeDepth + ")" });
+ }
+ if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {
+ return _this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
+ }
+ return evt;
+ });
+ };
+ /**
+ * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
+ * Normalized keys:
+ * - `breadcrumbs.data`
+ * - `user`
+ * - `contexts`
+ * - `extra`
+ * @param event Event
+ * @returns Normalized event
+ */
+ BaseClient.prototype._normalizeEvent = function (event, depth, maxBreadth) {
+ if (!event) {
+ return null;
+ }
+ var normalized = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, event), (event.breadcrumbs && {
+ breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_1.__assign(tslib_1.__assign({}, b), (b.data && {
+ data: utils_1.normalize(b.data, depth, maxBreadth),
+ }))); }),
+ })), (event.user && {
+ user: utils_1.normalize(event.user, depth, maxBreadth),
+ })), (event.contexts && {
+ contexts: utils_1.normalize(event.contexts, depth, maxBreadth),
+ })), (event.extra && {
+ extra: utils_1.normalize(event.extra, depth, maxBreadth),
+ }));
+ // event.contexts.trace stores information about a Transaction. Similarly,
+ // event.spans[] stores information about child Spans. Given that a
+ // Transaction is conceptually a Span, normalization should apply to both
+ // Transactions and Spans consistently.
+ // For now the decision is to skip normalization of Transactions and Spans,
+ // so this block overwrites the normalized event to add back the original
+ // Transaction information prior to normalization.
+ if (event.contexts && event.contexts.trace) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ normalized.contexts.trace = event.contexts.trace;
+ }
+ normalized.sdkProcessingMetadata = tslib_1.__assign(tslib_1.__assign({}, normalized.sdkProcessingMetadata), { baseClientNormalized: true });
+ return normalized;
+ };
+ /**
+ * Enhances event using the client configuration.
+ * It takes care of all "static" values like environment, release and `dist`,
+ * as well as truncating overly long values.
+ * @param event event instance to be enhanced
+ */
+ BaseClient.prototype._applyClientOptions = function (event) {
+ var options = this.getOptions();
+ var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a;
+ if (!('environment' in event)) {
+ event.environment = 'environment' in options ? environment : 'production';
+ }
+ if (event.release === undefined && release !== undefined) {
+ event.release = release;
+ }
+ if (event.dist === undefined && dist !== undefined) {
+ event.dist = dist;
+ }
+ if (event.message) {
+ event.message = utils_1.truncate(event.message, maxValueLength);
+ }
+ var exception = event.exception && event.exception.values && event.exception.values[0];
+ if (exception && exception.value) {
+ exception.value = utils_1.truncate(exception.value, maxValueLength);
+ }
+ var request = event.request;
+ if (request && request.url) {
+ request.url = utils_1.truncate(request.url, maxValueLength);
+ }
+ };
+ /**
+ * This function adds all used integrations to the SDK info in the event.
+ * @param event The event that will be filled with all integrations.
+ */
+ BaseClient.prototype._applyIntegrationsMetadata = function (event) {
+ var integrationsArray = Object.keys(this._integrations);
+ if (integrationsArray.length > 0) {
+ event.sdk = event.sdk || {};
+ event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), integrationsArray);
+ }
+ };
+ /**
+ * Tells the backend to send this event
+ * @param event The Sentry event to send
+ */
+ BaseClient.prototype._sendEvent = function (event) {
+ this._getBackend().sendEvent(event);
+ };
+ /**
+ * Processes the event and logs an error in case of rejection
+ * @param event
+ * @param hint
+ * @param scope
+ */
+ BaseClient.prototype._captureEvent = function (event, hint, scope) {
+ return this._processEvent(event, hint, scope).then(function (finalEvent) {
+ return finalEvent.event_id;
+ }, function (reason) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error(reason);
+ return undefined;
+ });
+ };
+ /**
+ * Processes an event (either error or message) and sends it to Sentry.
+ *
+ * This also adds breadcrumbs and context information to the event. However,
+ * platform specific meta data (such as the User's IP address) must be added
+ * by the SDK implementor.
+ *
+ *
+ * @param event The event to send to Sentry.
+ * @param hint May contain additional information about the original exception.
+ * @param scope A scope containing event metadata.
+ * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.
+ */
+ BaseClient.prototype._processEvent = function (event, hint, scope) {
+ var _this = this;
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate;
+ var transport = this.getTransport();
+ function recordLostEvent(outcome, category) {
+ if (transport.recordLostEvent) {
+ transport.recordLostEvent(outcome, category);
+ }
+ }
+ if (!this._isEnabled()) {
+ return utils_1.rejectedSyncPromise(new utils_1.SentryError('SDK not enabled, will not capture event.'));
+ }
+ var isTransaction = event.type === 'transaction';
+ // 1.0 === 100% events are sent
+ // 0.0 === 0% events are sent
+ // Sampling for transaction happens somewhere else
+ if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {
+ recordLostEvent('sample_rate', 'event');
+ return utils_1.rejectedSyncPromise(new utils_1.SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")"));
+ }
+ return this._prepareEvent(event, scope, hint)
+ .then(function (prepared) {
+ if (prepared === null) {
+ recordLostEvent('event_processor', event.type || 'event');
+ throw new utils_1.SentryError('An event processor returned null, will not send event.');
+ }
+ var isInternalException = hint && hint.data && hint.data.__sentry__ === true;
+ if (isInternalException || isTransaction || !beforeSend) {
+ return prepared;
+ }
+ var beforeSendResult = beforeSend(prepared, hint);
+ return _ensureBeforeSendRv(beforeSendResult);
+ })
+ .then(function (processedEvent) {
+ if (processedEvent === null) {
+ recordLostEvent('before_send', event.type || 'event');
+ throw new utils_1.SentryError('`beforeSend` returned `null`, will not send event.');
+ }
+ var session = scope && scope.getSession && scope.getSession();
+ if (!isTransaction && session) {
+ _this._updateSessionFromEvent(session, processedEvent);
+ }
+ _this._sendEvent(processedEvent);
+ return processedEvent;
+ })
+ .then(null, function (reason) {
+ if (reason instanceof utils_1.SentryError) {
+ throw reason;
+ }
+ _this.captureException(reason, {
+ data: {
+ __sentry__: true,
+ },
+ originalException: reason,
+ });
+ throw new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason);
+ });
+ };
+ /**
+ * Occupies the client with processing and event
+ */
+ BaseClient.prototype._process = function (promise) {
+ var _this = this;
+ this._numProcessing += 1;
+ void promise.then(function (value) {
+ _this._numProcessing -= 1;
+ return value;
+ }, function (reason) {
+ _this._numProcessing -= 1;
+ return reason;
+ });
+ };
+ return BaseClient;
+}());
+exports.BaseClient = BaseClient;
+/**
+ * Verifies that return value of configured `beforeSend` is of expected type.
+ */
+function _ensureBeforeSendRv(rv) {
+ var nullErr = '`beforeSend` method has to return `null` or a valid event.';
+ if (utils_1.isThenable(rv)) {
+ return rv.then(function (event) {
+ if (!(utils_1.isPlainObject(event) || event === null)) {
+ throw new utils_1.SentryError(nullErr);
+ }
+ return event;
+ }, function (e) {
+ throw new utils_1.SentryError("beforeSend rejected with " + e);
+ });
+ }
+ else if (!(utils_1.isPlainObject(rv) || rv === null)) {
+ throw new utils_1.SentryError(nullErr);
+ }
+ return rv;
+}
+//# sourceMappingURL=baseclient.js.map
+
+/***/ }),
+
+/***/ 91839:
+/***/ ((__unused_webpack_module, exports) => {
+
+/*
+ * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking
+ * for users.
+ *
+ * Debug flags need to be declared in each package individually and must not be imported across package boundaries,
+ * because some build tools have trouble tree-shaking imported guards.
+ *
+ * As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
+ *
+ * Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during
+ * our, or the user's build process. Take care when introducing new flags - they must not throw if they are not
+ * replaced.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/** Flag that is true for debug builds, false otherwise. */
+exports.IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;
+//# sourceMappingURL=flags.js.map
+
+/***/ }),
+
+/***/ 79212:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var minimal_1 = __nccwpck_require__(88455);
+exports.addBreadcrumb = minimal_1.addBreadcrumb;
+exports.captureException = minimal_1.captureException;
+exports.captureEvent = minimal_1.captureEvent;
+exports.captureMessage = minimal_1.captureMessage;
+exports.configureScope = minimal_1.configureScope;
+exports.startTransaction = minimal_1.startTransaction;
+exports.setContext = minimal_1.setContext;
+exports.setExtra = minimal_1.setExtra;
+exports.setExtras = minimal_1.setExtras;
+exports.setTag = minimal_1.setTag;
+exports.setTags = minimal_1.setTags;
+exports.setUser = minimal_1.setUser;
+exports.withScope = minimal_1.withScope;
+var hub_1 = __nccwpck_require__(6393);
+exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor;
+exports.getCurrentHub = hub_1.getCurrentHub;
+exports.getHubFromCarrier = hub_1.getHubFromCarrier;
+exports.Hub = hub_1.Hub;
+exports.makeMain = hub_1.makeMain;
+exports.Scope = hub_1.Scope;
+exports.Session = hub_1.Session;
+var api_1 = __nccwpck_require__(90785);
+// eslint-disable-next-line deprecation/deprecation
+exports.API = api_1.API;
+exports.getEnvelopeEndpointWithUrlEncodedAuth = api_1.getEnvelopeEndpointWithUrlEncodedAuth;
+exports.getStoreEndpointWithUrlEncodedAuth = api_1.getStoreEndpointWithUrlEncodedAuth;
+exports.getRequestHeaders = api_1.getRequestHeaders;
+exports.initAPIDetails = api_1.initAPIDetails;
+exports.getReportDialogEndpoint = api_1.getReportDialogEndpoint;
+var baseclient_1 = __nccwpck_require__(25684);
+exports.BaseClient = baseclient_1.BaseClient;
+var basebackend_1 = __nccwpck_require__(25886);
+exports.BaseBackend = basebackend_1.BaseBackend;
+var request_1 = __nccwpck_require__(1553);
+exports.eventToSentryRequest = request_1.eventToSentryRequest;
+exports.sessionToSentryRequest = request_1.sessionToSentryRequest;
+var sdk_1 = __nccwpck_require__(46406);
+exports.initAndBind = sdk_1.initAndBind;
+var noop_1 = __nccwpck_require__(68641);
+exports.NoopTransport = noop_1.NoopTransport;
+var base_1 = __nccwpck_require__(309);
+exports.createTransport = base_1.createTransport;
+var version_1 = __nccwpck_require__(33493);
+exports.SDK_VERSION = version_1.SDK_VERSION;
+var Integrations = __nccwpck_require__(96727);
+exports.Integrations = Integrations;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 58500:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var hub_1 = __nccwpck_require__(6393);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(91839);
+exports.installedIntegrations = [];
+/**
+ * @private
+ */
+function filterDuplicates(integrations) {
+ return integrations.reduce(function (acc, integrations) {
+ if (acc.every(function (accIntegration) { return integrations.name !== accIntegration.name; })) {
+ acc.push(integrations);
+ }
+ return acc;
+ }, []);
+}
+/** Gets integration to install */
+function getIntegrationsToSetup(options) {
+ var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || [];
+ var userIntegrations = options.integrations;
+ var integrations = tslib_1.__spread(filterDuplicates(defaultIntegrations));
+ if (Array.isArray(userIntegrations)) {
+ // Filter out integrations that are also included in user options
+ integrations = tslib_1.__spread(integrations.filter(function (integrations) {
+ return userIntegrations.every(function (userIntegration) { return userIntegration.name !== integrations.name; });
+ }), filterDuplicates(userIntegrations));
+ }
+ else if (typeof userIntegrations === 'function') {
+ integrations = userIntegrations(integrations);
+ integrations = Array.isArray(integrations) ? integrations : [integrations];
+ }
+ // Make sure that if present, `Debug` integration will always run last
+ var integrationsNames = integrations.map(function (i) { return i.name; });
+ var alwaysLastToRun = 'Debug';
+ if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {
+ integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));
+ }
+ return integrations;
+}
+exports.getIntegrationsToSetup = getIntegrationsToSetup;
+/** Setup given integration */
+function setupIntegration(integration) {
+ if (exports.installedIntegrations.indexOf(integration.name) !== -1) {
+ return;
+ }
+ integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub);
+ exports.installedIntegrations.push(integration.name);
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.log("Integration installed: " + integration.name);
+}
+exports.setupIntegration = setupIntegration;
+/**
+ * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default
+ * integrations are added unless they were already provided before.
+ * @param integrations array of integration instances
+ * @param withDefault should enable default integrations
+ */
+function setupIntegrations(options) {
+ var integrations = {};
+ getIntegrationsToSetup(options).forEach(function (integration) {
+ integrations[integration.name] = integration;
+ setupIntegration(integration);
+ });
+ // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`
+ // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be
+ // considered a member of the index the way the actual integrations are
+ utils_1.addNonEnumerableProperty(integrations, 'initialized', true);
+ return integrations;
+}
+exports.setupIntegrations = setupIntegrations;
+//# sourceMappingURL=integration.js.map
+
+/***/ }),
+
+/***/ 87349:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+var originalFunctionToString;
+/** Patch toString calls to return proper name for wrapped functions */
+var FunctionToString = /** @class */ (function () {
+ function FunctionToString() {
+ /**
+ * @inheritDoc
+ */
+ this.name = FunctionToString.id;
+ }
+ /**
+ * @inheritDoc
+ */
+ FunctionToString.prototype.setupOnce = function () {
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ originalFunctionToString = Function.prototype.toString;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ Function.prototype.toString = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var context = utils_1.getOriginalFunction(this) || this;
+ return originalFunctionToString.apply(context, args);
+ };
+ };
+ /**
+ * @inheritDoc
+ */
+ FunctionToString.id = 'FunctionToString';
+ return FunctionToString;
+}());
+exports.FunctionToString = FunctionToString;
+//# sourceMappingURL=functiontostring.js.map
+
+/***/ }),
+
+/***/ 54838:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(91839);
+// "Script error." is hard coded into browsers for errors that it can't read.
+// this is the result of a script being pulled in from an external domain and CORS.
+var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/];
+/** Inbound filters configurable by the user */
+var InboundFilters = /** @class */ (function () {
+ function InboundFilters(_options) {
+ if (_options === void 0) { _options = {}; }
+ this._options = _options;
+ /**
+ * @inheritDoc
+ */
+ this.name = InboundFilters.id;
+ }
+ /**
+ * @inheritDoc
+ */
+ InboundFilters.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) {
+ addGlobalEventProcessor(function (event) {
+ var hub = getCurrentHub();
+ if (hub) {
+ var self_1 = hub.getIntegration(InboundFilters);
+ if (self_1) {
+ var client = hub.getClient();
+ var clientOptions = client ? client.getOptions() : {};
+ var options = _mergeOptions(self_1._options, clientOptions);
+ return _shouldDropEvent(event, options) ? null : event;
+ }
+ }
+ return event;
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ InboundFilters.id = 'InboundFilters';
+ return InboundFilters;
+}());
+exports.InboundFilters = InboundFilters;
+/** JSDoc */
+function _mergeOptions(internalOptions, clientOptions) {
+ if (internalOptions === void 0) { internalOptions = {}; }
+ if (clientOptions === void 0) { clientOptions = {}; }
+ return {
+ allowUrls: tslib_1.__spread((internalOptions.whitelistUrls || []), (internalOptions.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])),
+ denyUrls: tslib_1.__spread((internalOptions.blacklistUrls || []), (internalOptions.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])),
+ ignoreErrors: tslib_1.__spread((internalOptions.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS),
+ ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,
+ };
+}
+exports._mergeOptions = _mergeOptions;
+/** JSDoc */
+function _shouldDropEvent(event, options) {
+ if (options.ignoreInternal && _isSentryError(event)) {
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event));
+ return true;
+ }
+ if (_isIgnoredError(event, options.ignoreErrors)) {
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event));
+ return true;
+ }
+ if (_isDeniedUrl(event, options.denyUrls)) {
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + _getEventFilterUrl(event));
+ return true;
+ }
+ if (!_isAllowedUrl(event, options.allowUrls)) {
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + _getEventFilterUrl(event));
+ return true;
+ }
+ return false;
+}
+exports._shouldDropEvent = _shouldDropEvent;
+function _isIgnoredError(event, ignoreErrors) {
+ if (!ignoreErrors || !ignoreErrors.length) {
+ return false;
+ }
+ return _getPossibleEventMessages(event).some(function (message) {
+ return ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); });
+ });
+}
+function _isDeniedUrl(event, denyUrls) {
+ // TODO: Use Glob instead?
+ if (!denyUrls || !denyUrls.length) {
+ return false;
+ }
+ var url = _getEventFilterUrl(event);
+ return !url ? false : denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); });
+}
+function _isAllowedUrl(event, allowUrls) {
+ // TODO: Use Glob instead?
+ if (!allowUrls || !allowUrls.length) {
+ return true;
+ }
+ var url = _getEventFilterUrl(event);
+ return !url ? true : allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); });
+}
+function _getPossibleEventMessages(event) {
+ if (event.message) {
+ return [event.message];
+ }
+ if (event.exception) {
+ try {
+ var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c;
+ return ["" + value, type + ": " + value];
+ }
+ catch (oO) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event));
+ return [];
+ }
+ }
+ return [];
+}
+function _isSentryError(event) {
+ try {
+ // @ts-ignore can't be a sentry error if undefined
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ return event.exception.values[0].type === 'SentryError';
+ }
+ catch (e) {
+ // ignore
+ }
+ return false;
+}
+function _getLastValidUrl(frames) {
+ if (frames === void 0) { frames = []; }
+ for (var i = frames.length - 1; i >= 0; i--) {
+ var frame = frames[i];
+ if (frame && frame.filename !== '' && frame.filename !== '[native code]') {
+ return frame.filename || null;
+ }
+ }
+ return null;
+}
+function _getEventFilterUrl(event) {
+ try {
+ if (event.stacktrace) {
+ return _getLastValidUrl(event.stacktrace.frames);
+ }
+ var frames_1;
+ try {
+ // @ts-ignore we only care about frames if the whole thing here is defined
+ frames_1 = event.exception.values[0].stacktrace.frames;
+ }
+ catch (e) {
+ // ignore
+ }
+ return frames_1 ? _getLastValidUrl(frames_1) : null;
+ }
+ catch (oO) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event));
+ return null;
+ }
+}
+//# sourceMappingURL=inboundfilters.js.map
+
+/***/ }),
+
+/***/ 96727:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var functiontostring_1 = __nccwpck_require__(87349);
+exports.FunctionToString = functiontostring_1.FunctionToString;
+var inboundfilters_1 = __nccwpck_require__(54838);
+exports.InboundFilters = inboundfilters_1.InboundFilters;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 1553:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var utils_1 = __nccwpck_require__(1620);
+var api_1 = __nccwpck_require__(90785);
+/** Extract sdk info from from the API metadata */
+function getSdkMetadataForEnvelopeHeader(api) {
+ if (!api.metadata || !api.metadata.sdk) {
+ return;
+ }
+ var _a = api.metadata.sdk, name = _a.name, version = _a.version;
+ return { name: name, version: version };
+}
+/**
+ * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.
+ * Merge with existing data if any.
+ **/
+function enhanceEventWithSdkInfo(event, sdkInfo) {
+ if (!sdkInfo) {
+ return event;
+ }
+ event.sdk = event.sdk || {};
+ event.sdk.name = event.sdk.name || sdkInfo.name;
+ event.sdk.version = event.sdk.version || sdkInfo.version;
+ event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), (sdkInfo.integrations || []));
+ event.sdk.packages = tslib_1.__spread((event.sdk.packages || []), (sdkInfo.packages || []));
+ return event;
+}
+/** Creates an envelope from a Session */
+function createSessionEnvelope(session, api) {
+ var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
+ var envelopeHeaders = tslib_1.__assign(tslib_1.__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: utils_1.dsnToString(api.dsn) }));
+ // I know this is hacky but we don't want to add `sessions` to request type since it's never rate limited
+ var type = 'aggregates' in session ? 'sessions' : 'session';
+ // TODO (v7) Have to cast type because envelope items do not accept a `SentryRequestType`
+ var envelopeItem = [{ type: type }, session];
+ var envelope = utils_1.createEnvelope(envelopeHeaders, [envelopeItem]);
+ return [envelope, type];
+}
+exports.createSessionEnvelope = createSessionEnvelope;
+/** Creates a SentryRequest from a Session. */
+function sessionToSentryRequest(session, api) {
+ var _a = tslib_1.__read(createSessionEnvelope(session, api), 2), envelope = _a[0], type = _a[1];
+ return {
+ body: utils_1.serializeEnvelope(envelope),
+ type: type,
+ url: api_1.getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel),
+ };
+}
+exports.sessionToSentryRequest = sessionToSentryRequest;
+/**
+ * Create an Envelope from an event. Note that this is duplicated from below,
+ * but on purpose as this will be refactored in v7.
+ */
+function createEventEnvelope(event, api) {
+ var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
+ var eventType = event.type || 'event';
+ var transactionSampling = (event.sdkProcessingMetadata || {}).transactionSampling;
+ var _a = transactionSampling || {}, samplingMethod = _a.method, sampleRate = _a.rate;
+ // TODO: Below is a temporary hack in order to debug a serialization error - see
+ // https://github.com/getsentry/sentry-javascript/issues/2809,
+ // https://github.com/getsentry/sentry-javascript/pull/4425, and
+ // https://github.com/getsentry/sentry-javascript/pull/4574.
+ //
+ // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to
+ // throw a circular reference error.
+ //
+ // When it's time to remove it:
+ // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting
+ // `sdkProcessingMetadata`
+ // 2. Restore the original version of the request body, which is commented out
+ // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the
+ // baseClient tests in this package
+ enhanceEventWithSdkInfo(event, api.metadata.sdk);
+ event.tags = event.tags || {};
+ event.extra = event.extra || {};
+ // In theory, all events should be marked as having gone through normalization and so
+ // we should never set this tag/extra data
+ if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {
+ event.tags.skippedNormalization = true;
+ event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset';
+ }
+ // prevent this data from being sent to sentry
+ // TODO: This is NOT part of the hack - DO NOT DELETE
+ delete event.sdkProcessingMetadata;
+ var envelopeHeaders = tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: utils_1.dsnToString(api.dsn) }));
+ var eventItem = [
+ {
+ type: eventType,
+ sample_rates: [{ id: samplingMethod, rate: sampleRate }],
+ },
+ event,
+ ];
+ return utils_1.createEnvelope(envelopeHeaders, [eventItem]);
+}
+exports.createEventEnvelope = createEventEnvelope;
+/** Creates a SentryRequest from an event. */
+function eventToSentryRequest(event, api) {
+ var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
+ var eventType = event.type || 'event';
+ var useEnvelope = eventType === 'transaction' || !!api.tunnel;
+ var transactionSampling = (event.sdkProcessingMetadata || {}).transactionSampling;
+ var _a = transactionSampling || {}, samplingMethod = _a.method, sampleRate = _a.rate;
+ // TODO: Below is a temporary hack in order to debug a serialization error - see
+ // https://github.com/getsentry/sentry-javascript/issues/2809,
+ // https://github.com/getsentry/sentry-javascript/pull/4425, and
+ // https://github.com/getsentry/sentry-javascript/pull/4574.
+ //
+ // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to
+ // throw a circular reference error.
+ //
+ // When it's time to remove it:
+ // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting
+ // `sdkProcessingMetadata`
+ // 2. Restore the original version of the request body, which is commented out
+ // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the
+ // baseClient tests in this package
+ enhanceEventWithSdkInfo(event, api.metadata.sdk);
+ event.tags = event.tags || {};
+ event.extra = event.extra || {};
+ // In theory, all events should be marked as having gone through normalization and so
+ // we should never set this tag/extra data
+ if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {
+ event.tags.skippedNormalization = true;
+ event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset';
+ }
+ // prevent this data from being sent to sentry
+ // TODO: This is NOT part of the hack - DO NOT DELETE
+ delete event.sdkProcessingMetadata;
+ var body;
+ try {
+ // 99.9% of events should get through just fine - no change in behavior for them
+ body = JSON.stringify(event);
+ }
+ catch (err) {
+ // Record data about the error without replacing original event data, then force renormalization
+ event.tags.JSONStringifyError = true;
+ event.extra.JSONStringifyError = err;
+ try {
+ body = JSON.stringify(utils_1.normalize(event));
+ }
+ catch (newErr) {
+ // At this point even renormalization hasn't worked, meaning something about the event data has gone very wrong.
+ // Time to cut our losses and record only the new error. With luck, even in the problematic cases we're trying to
+ // debug with this hack, we won't ever land here.
+ var innerErr = newErr;
+ body = JSON.stringify({
+ message: 'JSON.stringify error after renormalization',
+ // setting `extra: { innerErr }` here for some reason results in an empty object, so unpack manually
+ extra: { message: innerErr.message, stack: innerErr.stack },
+ });
+ }
+ }
+ var req = {
+ // this is the relevant line of code before the hack was added, to make it easy to undo said hack once we've solved
+ // the mystery
+ // body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),
+ body: body,
+ type: eventType,
+ url: useEnvelope
+ ? api_1.getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel)
+ : api_1.getStoreEndpointWithUrlEncodedAuth(api.dsn),
+ };
+ // https://develop.sentry.dev/sdk/envelopes/
+ // Since we don't need to manipulate envelopes nor store them, there is no
+ // exported concept of an Envelope with operations including serialization and
+ // deserialization. Instead, we only implement a minimal subset of the spec to
+ // serialize events inline here.
+ if (useEnvelope) {
+ var envelopeHeaders = tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: utils_1.dsnToString(api.dsn) }));
+ var eventItem = [
+ {
+ type: eventType,
+ sample_rates: [{ id: samplingMethod, rate: sampleRate }],
+ },
+ req.body,
+ ];
+ var envelope = utils_1.createEnvelope(envelopeHeaders, [eventItem]);
+ req.body = utils_1.serializeEnvelope(envelope);
+ }
+ return req;
+}
+exports.eventToSentryRequest = eventToSentryRequest;
+//# sourceMappingURL=request.js.map
+
+/***/ }),
+
+/***/ 46406:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var hub_1 = __nccwpck_require__(6393);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(91839);
+/**
+ * Internal function to create a new SDK client instance. The client is
+ * installed and then bound to the current scope.
+ *
+ * @param clientClass The client class to instantiate.
+ * @param options Options to pass to the client.
+ */
+function initAndBind(clientClass, options) {
+ if (options.debug === true) {
+ if (flags_1.IS_DEBUG_BUILD) {
+ utils_1.logger.enable();
+ }
+ else {
+ // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped
+ // eslint-disable-next-line no-console
+ console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');
+ }
+ }
+ var hub = hub_1.getCurrentHub();
+ var scope = hub.getScope();
+ if (scope) {
+ scope.update(options.initialScope);
+ }
+ var client = new clientClass(options);
+ hub.bindClient(client);
+}
+exports.initAndBind = initAndBind;
+//# sourceMappingURL=sdk.js.map
+
+/***/ }),
+
+/***/ 309:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+exports.ERROR_TRANSPORT_CATEGORY = 'error';
+exports.TRANSACTION_TRANSPORT_CATEGORY = 'transaction';
+exports.ATTACHMENT_TRANSPORT_CATEGORY = 'attachment';
+exports.SESSION_TRANSPORT_CATEGORY = 'session';
+exports.DEFAULT_TRANSPORT_BUFFER_SIZE = 30;
+/**
+ * Creates a `NewTransport`
+ *
+ * @param options
+ * @param makeRequest
+ */
+function createTransport(options, makeRequest, buffer) {
+ if (buffer === void 0) { buffer = utils_1.makePromiseBuffer(options.bufferSize || exports.DEFAULT_TRANSPORT_BUFFER_SIZE); }
+ var rateLimits = {};
+ var flush = function (timeout) { return buffer.drain(timeout); };
+ function send(envelope) {
+ var envCategory = utils_1.getEnvelopeType(envelope);
+ var category = envCategory === 'event' ? 'error' : envCategory;
+ var request = {
+ category: category,
+ body: utils_1.serializeEnvelope(envelope),
+ };
+ // Don't add to buffer if transport is already rate-limited
+ if (utils_1.isRateLimited(rateLimits, category)) {
+ return utils_1.rejectedSyncPromise({
+ status: 'rate_limit',
+ reason: getRateLimitReason(rateLimits, category),
+ });
+ }
+ var requestTask = function () {
+ return makeRequest(request).then(function (_a) {
+ var body = _a.body, headers = _a.headers, reason = _a.reason, statusCode = _a.statusCode;
+ var status = utils_1.eventStatusFromHttpCode(statusCode);
+ if (headers) {
+ rateLimits = utils_1.updateRateLimits(rateLimits, headers);
+ }
+ if (status === 'success') {
+ return utils_1.resolvedSyncPromise({ status: status, reason: reason });
+ }
+ return utils_1.rejectedSyncPromise({
+ status: status,
+ reason: reason ||
+ body ||
+ (status === 'rate_limit' ? getRateLimitReason(rateLimits, category) : 'Unknown transport error'),
+ });
+ });
+ };
+ return buffer.add(requestTask);
+ }
+ return {
+ send: send,
+ flush: flush,
+ };
+}
+exports.createTransport = createTransport;
+function getRateLimitReason(rateLimits, category) {
+ return "Too many " + category + " requests, backing off until: " + new Date(utils_1.disabledUntil(rateLimits, category)).toISOString();
+}
+//# sourceMappingURL=base.js.map
+
+/***/ }),
+
+/***/ 68641:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+/** Noop transport */
+var NoopTransport = /** @class */ (function () {
+ function NoopTransport() {
+ }
+ /**
+ * @inheritDoc
+ */
+ NoopTransport.prototype.sendEvent = function (_) {
+ return utils_1.resolvedSyncPromise({
+ reason: 'NoopTransport: Event has been skipped because no Dsn is configured.',
+ status: 'skipped',
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ NoopTransport.prototype.close = function (_) {
+ return utils_1.resolvedSyncPromise(true);
+ };
+ return NoopTransport;
+}());
+exports.NoopTransport = NoopTransport;
+//# sourceMappingURL=noop.js.map
+
+/***/ }),
+
+/***/ 33493:
+/***/ ((__unused_webpack_module, exports) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SDK_VERSION = '6.19.7';
+//# sourceMappingURL=version.js.map
+
+/***/ }),
+
+/***/ 30369:
+/***/ ((__unused_webpack_module, exports) => {
+
+/*
+ * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking
+ * for users.
+ *
+ * Debug flags need to be declared in each package individually and must not be imported across package boundaries,
+ * because some build tools have trouble tree-shaking imported guards.
+ *
+ * As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
+ *
+ * Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during
+ * our, or the user's build process. Take care when introducing new flags - they must not throw if they are not
+ * replaced.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/** Flag that is true for debug builds, false otherwise. */
+exports.IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;
+//# sourceMappingURL=flags.js.map
+
+/***/ }),
+
+/***/ 53536:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(30369);
+var scope_1 = __nccwpck_require__(4213);
+var session_1 = __nccwpck_require__(12474);
+/**
+ * API compatibility version of this hub.
+ *
+ * WARNING: This number should only be increased when the global interface
+ * changes and new methods are introduced.
+ *
+ * @hidden
+ */
+exports.API_VERSION = 4;
+/**
+ * Default maximum number of breadcrumbs added to an event. Can be overwritten
+ * with {@link Options.maxBreadcrumbs}.
+ */
+var DEFAULT_BREADCRUMBS = 100;
+/**
+ * @inheritDoc
+ */
+var Hub = /** @class */ (function () {
+ /**
+ * Creates a new instance of the hub, will push one {@link Layer} into the
+ * internal stack on creation.
+ *
+ * @param client bound to the hub.
+ * @param scope bound to the hub.
+ * @param version number, higher number means higher priority.
+ */
+ function Hub(client, scope, _version) {
+ if (scope === void 0) { scope = new scope_1.Scope(); }
+ if (_version === void 0) { _version = exports.API_VERSION; }
+ this._version = _version;
+ /** Is a {@link Layer}[] containing the client and scope */
+ this._stack = [{}];
+ this.getStackTop().scope = scope;
+ if (client) {
+ this.bindClient(client);
+ }
+ }
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.isOlderThan = function (version) {
+ return this._version < version;
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.bindClient = function (client) {
+ var top = this.getStackTop();
+ top.client = client;
+ if (client && client.setupIntegrations) {
+ client.setupIntegrations();
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.pushScope = function () {
+ // We want to clone the content of prev scope
+ var scope = scope_1.Scope.clone(this.getScope());
+ this.getStack().push({
+ client: this.getClient(),
+ scope: scope,
+ });
+ return scope;
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.popScope = function () {
+ if (this.getStack().length <= 1)
+ return false;
+ return !!this.getStack().pop();
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.withScope = function (callback) {
+ var scope = this.pushScope();
+ try {
+ callback(scope);
+ }
+ finally {
+ this.popScope();
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.getClient = function () {
+ return this.getStackTop().client;
+ };
+ /** Returns the scope of the top stack. */
+ Hub.prototype.getScope = function () {
+ return this.getStackTop().scope;
+ };
+ /** Returns the scope stack for domains or the process. */
+ Hub.prototype.getStack = function () {
+ return this._stack;
+ };
+ /** Returns the topmost scope layer in the order domain > local > process. */
+ Hub.prototype.getStackTop = function () {
+ return this._stack[this._stack.length - 1];
+ };
+ /**
+ * @inheritDoc
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
+ Hub.prototype.captureException = function (exception, hint) {
+ var eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils_1.uuid4());
+ var finalHint = hint;
+ // If there's no explicit hint provided, mimic the same thing that would happen
+ // in the minimal itself to create a consistent behavior.
+ // We don't do this in the client, as it's the lowest level API, and doing this,
+ // would prevent user from having full control over direct calls.
+ if (!hint) {
+ var syntheticException = void 0;
+ try {
+ throw new Error('Sentry syntheticException');
+ }
+ catch (exception) {
+ syntheticException = exception;
+ }
+ finalHint = {
+ originalException: exception,
+ syntheticException: syntheticException,
+ };
+ }
+ this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId }));
+ return eventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.captureMessage = function (message, level, hint) {
+ var eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils_1.uuid4());
+ var finalHint = hint;
+ // If there's no explicit hint provided, mimic the same thing that would happen
+ // in the minimal itself to create a consistent behavior.
+ // We don't do this in the client, as it's the lowest level API, and doing this,
+ // would prevent user from having full control over direct calls.
+ if (!hint) {
+ var syntheticException = void 0;
+ try {
+ throw new Error(message);
+ }
+ catch (exception) {
+ syntheticException = exception;
+ }
+ finalHint = {
+ originalException: message,
+ syntheticException: syntheticException,
+ };
+ }
+ this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId }));
+ return eventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.captureEvent = function (event, hint) {
+ var eventId = hint && hint.event_id ? hint.event_id : utils_1.uuid4();
+ if (event.type !== 'transaction') {
+ this._lastEventId = eventId;
+ }
+ this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId }));
+ return eventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.lastEventId = function () {
+ return this._lastEventId;
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.addBreadcrumb = function (breadcrumb, hint) {
+ var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
+ if (!scope || !client)
+ return;
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d;
+ if (maxBreadcrumbs <= 0)
+ return;
+ var timestamp = utils_1.dateTimestampInSeconds();
+ var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb);
+ var finalBreadcrumb = beforeBreadcrumb
+ ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); })
+ : mergedBreadcrumb;
+ if (finalBreadcrumb === null)
+ return;
+ scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.setUser = function (user) {
+ var scope = this.getScope();
+ if (scope)
+ scope.setUser(user);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.setTags = function (tags) {
+ var scope = this.getScope();
+ if (scope)
+ scope.setTags(tags);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.setExtras = function (extras) {
+ var scope = this.getScope();
+ if (scope)
+ scope.setExtras(extras);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.setTag = function (key, value) {
+ var scope = this.getScope();
+ if (scope)
+ scope.setTag(key, value);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.setExtra = function (key, extra) {
+ var scope = this.getScope();
+ if (scope)
+ scope.setExtra(key, extra);
+ };
+ /**
+ * @inheritDoc
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ Hub.prototype.setContext = function (name, context) {
+ var scope = this.getScope();
+ if (scope)
+ scope.setContext(name, context);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.configureScope = function (callback) {
+ var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
+ if (scope && client) {
+ callback(scope);
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.run = function (callback) {
+ var oldHub = makeMain(this);
+ try {
+ callback(this);
+ }
+ finally {
+ makeMain(oldHub);
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.getIntegration = function (integration) {
+ var client = this.getClient();
+ if (!client)
+ return null;
+ try {
+ return client.getIntegration(integration);
+ }
+ catch (_oO) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub");
+ return null;
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.startSpan = function (context) {
+ return this._callExtensionMethod('startSpan', context);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.startTransaction = function (context, customSamplingContext) {
+ return this._callExtensionMethod('startTransaction', context, customSamplingContext);
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.traceHeaders = function () {
+ return this._callExtensionMethod('traceHeaders');
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.captureSession = function (endSession) {
+ if (endSession === void 0) { endSession = false; }
+ // both send the update and pull the session from the scope
+ if (endSession) {
+ return this.endSession();
+ }
+ // only send the update
+ this._sendSessionUpdate();
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.endSession = function () {
+ var layer = this.getStackTop();
+ var scope = layer && layer.scope;
+ var session = scope && scope.getSession();
+ if (session) {
+ session.close();
+ }
+ this._sendSessionUpdate();
+ // the session is over; take it off of the scope
+ if (scope) {
+ scope.setSession();
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Hub.prototype.startSession = function (context) {
+ var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
+ var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment;
+ // Will fetch userAgent if called from browser sdk
+ var global = utils_1.getGlobalObject();
+ var userAgent = (global.navigator || {}).userAgent;
+ var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ release: release,
+ environment: environment }, (scope && { user: scope.getUser() })), (userAgent && { userAgent: userAgent })), context));
+ if (scope) {
+ // End existing session if there's one
+ var currentSession = scope.getSession && scope.getSession();
+ if (currentSession && currentSession.status === 'ok') {
+ currentSession.update({ status: 'exited' });
+ }
+ this.endSession();
+ // Afterwards we set the new session on the scope
+ scope.setSession(session);
+ }
+ return session;
+ };
+ /**
+ * Sends the current Session on the scope
+ */
+ Hub.prototype._sendSessionUpdate = function () {
+ var _a = this.getStackTop(), scope = _a.scope, client = _a.client;
+ if (!scope)
+ return;
+ var session = scope.getSession && scope.getSession();
+ if (session) {
+ if (client && client.captureSession) {
+ client.captureSession(session);
+ }
+ }
+ };
+ /**
+ * Internal helper function to call a method on the top client if it exists.
+ *
+ * @param method The method to call on the client.
+ * @param args Arguments to pass to the client function.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ Hub.prototype._invokeClient = function (method) {
+ var _a;
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ var _b = this.getStackTop(), scope = _b.scope, client = _b.client;
+ if (client && client[method]) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
+ (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope]));
+ }
+ };
+ /**
+ * Calls global extension method and binding current instance to the function call
+ */
+ // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ Hub.prototype._callExtensionMethod = function (method) {
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ var carrier = getMainCarrier();
+ var sentry = carrier.__SENTRY__;
+ if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {
+ return sentry.extensions[method].apply(this, args);
+ }
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing.");
+ };
+ return Hub;
+}());
+exports.Hub = Hub;
+/**
+ * Returns the global shim registry.
+ *
+ * FIXME: This function is problematic, because despite always returning a valid Carrier,
+ * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check
+ * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.
+ **/
+function getMainCarrier() {
+ var carrier = utils_1.getGlobalObject();
+ carrier.__SENTRY__ = carrier.__SENTRY__ || {
+ extensions: {},
+ hub: undefined,
+ };
+ return carrier;
+}
+exports.getMainCarrier = getMainCarrier;
+/**
+ * Replaces the current main hub with the passed one on the global object
+ *
+ * @returns The old replaced hub
+ */
+function makeMain(hub) {
+ var registry = getMainCarrier();
+ var oldHub = getHubFromCarrier(registry);
+ setHubOnCarrier(registry, hub);
+ return oldHub;
+}
+exports.makeMain = makeMain;
+/**
+ * Returns the default hub instance.
+ *
+ * If a hub is already registered in the global carrier but this module
+ * contains a more recent version, it replaces the registered version.
+ * Otherwise, the currently registered hub will be returned.
+ */
+function getCurrentHub() {
+ // Get main carrier (global for every environment)
+ var registry = getMainCarrier();
+ // If there's no hub, or its an old API, assign a new one
+ if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) {
+ setHubOnCarrier(registry, new Hub());
+ }
+ // Prefer domains over global if they are there (applicable only to Node environment)
+ if (utils_1.isNodeEnv()) {
+ return getHubFromActiveDomain(registry);
+ }
+ // Return hub that lives on a global object
+ return getHubFromCarrier(registry);
+}
+exports.getCurrentHub = getCurrentHub;
+/**
+ * Returns the active domain, if one exists
+ * @deprecated No longer used; remove in v7
+ * @returns The domain, or undefined if there is no active domain
+ */
+// eslint-disable-next-line deprecation/deprecation
+function getActiveDomain() {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');
+ var sentry = getMainCarrier().__SENTRY__;
+ return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;
+}
+exports.getActiveDomain = getActiveDomain;
+/**
+ * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist
+ * @returns discovered hub
+ */
+function getHubFromActiveDomain(registry) {
+ try {
+ var sentry = getMainCarrier().__SENTRY__;
+ var activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;
+ // If there's no active domain, just return global hub
+ if (!activeDomain) {
+ return getHubFromCarrier(registry);
+ }
+ // If there's no hub on current domain, or it's an old API, assign a new one
+ if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) {
+ var registryHubTopStack = getHubFromCarrier(registry).getStackTop();
+ setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope)));
+ }
+ // Return hub that lives on a domain
+ return getHubFromCarrier(activeDomain);
+ }
+ catch (_Oo) {
+ // Return hub that lives on a global object
+ return getHubFromCarrier(registry);
+ }
+}
+/**
+ * This will tell whether a carrier has a hub on it or not
+ * @param carrier object
+ */
+function hasHubOnCarrier(carrier) {
+ return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
+}
+/**
+ * This will create a new {@link Hub} and add to the passed object on
+ * __SENTRY__.hub.
+ * @param carrier object
+ * @hidden
+ */
+function getHubFromCarrier(carrier) {
+ return utils_1.getGlobalSingleton('hub', function () { return new Hub(); }, carrier);
+}
+exports.getHubFromCarrier = getHubFromCarrier;
+/**
+ * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute
+ * @param carrier object
+ * @param hub Hub
+ * @returns A boolean indicating success or failure
+ */
+function setHubOnCarrier(carrier, hub) {
+ if (!carrier)
+ return false;
+ var __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});
+ __SENTRY__.hub = hub;
+ return true;
+}
+exports.setHubOnCarrier = setHubOnCarrier;
+//# sourceMappingURL=hub.js.map
+
+/***/ }),
+
+/***/ 6393:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var scope_1 = __nccwpck_require__(4213);
+exports.addGlobalEventProcessor = scope_1.addGlobalEventProcessor;
+exports.Scope = scope_1.Scope;
+var session_1 = __nccwpck_require__(12474);
+exports.Session = session_1.Session;
+var sessionflusher_1 = __nccwpck_require__(99695);
+exports.SessionFlusher = sessionflusher_1.SessionFlusher;
+var hub_1 = __nccwpck_require__(53536);
+// eslint-disable-next-line deprecation/deprecation
+exports.getActiveDomain = hub_1.getActiveDomain;
+exports.getCurrentHub = hub_1.getCurrentHub;
+exports.getHubFromCarrier = hub_1.getHubFromCarrier;
+exports.getMainCarrier = hub_1.getMainCarrier;
+exports.Hub = hub_1.Hub;
+exports.makeMain = hub_1.makeMain;
+exports.setHubOnCarrier = hub_1.setHubOnCarrier;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 4213:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var utils_1 = __nccwpck_require__(1620);
+/**
+ * Absolute maximum number of breadcrumbs added to an event.
+ * The `maxBreadcrumbs` option cannot be higher than this value.
+ */
+var MAX_BREADCRUMBS = 100;
+/**
+ * Holds additional event information. {@link Scope.applyToEvent} will be
+ * called by the client before an event will be sent.
+ */
+var Scope = /** @class */ (function () {
+ function Scope() {
+ /** Flag if notifying is happening. */
+ this._notifyingListeners = false;
+ /** Callback for client to receive scope changes. */
+ this._scopeListeners = [];
+ /** Callback list that will be called after {@link applyToEvent}. */
+ this._eventProcessors = [];
+ /** Array of breadcrumbs. */
+ this._breadcrumbs = [];
+ /** User */
+ this._user = {};
+ /** Tags */
+ this._tags = {};
+ /** Extra */
+ this._extra = {};
+ /** Contexts */
+ this._contexts = {};
+ /**
+ * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
+ * sent to Sentry
+ */
+ this._sdkProcessingMetadata = {};
+ }
+ /**
+ * Inherit values from the parent scope.
+ * @param scope to clone.
+ */
+ Scope.clone = function (scope) {
+ var newScope = new Scope();
+ if (scope) {
+ newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs);
+ newScope._tags = tslib_1.__assign({}, scope._tags);
+ newScope._extra = tslib_1.__assign({}, scope._extra);
+ newScope._contexts = tslib_1.__assign({}, scope._contexts);
+ newScope._user = scope._user;
+ newScope._level = scope._level;
+ newScope._span = scope._span;
+ newScope._session = scope._session;
+ newScope._transactionName = scope._transactionName;
+ newScope._fingerprint = scope._fingerprint;
+ newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors);
+ newScope._requestSession = scope._requestSession;
+ }
+ return newScope;
+ };
+ /**
+ * Add internal on change listener. Used for sub SDKs that need to store the scope.
+ * @hidden
+ */
+ Scope.prototype.addScopeListener = function (callback) {
+ this._scopeListeners.push(callback);
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.addEventProcessor = function (callback) {
+ this._eventProcessors.push(callback);
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setUser = function (user) {
+ this._user = user || {};
+ if (this._session) {
+ this._session.update({ user: user });
+ }
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.getUser = function () {
+ return this._user;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.getRequestSession = function () {
+ return this._requestSession;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setRequestSession = function (requestSession) {
+ this._requestSession = requestSession;
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setTags = function (tags) {
+ this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags);
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setTag = function (key, value) {
+ var _a;
+ this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a));
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setExtras = function (extras) {
+ this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras);
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setExtra = function (key, extra) {
+ var _a;
+ this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a));
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setFingerprint = function (fingerprint) {
+ this._fingerprint = fingerprint;
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setLevel = function (level) {
+ this._level = level;
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setTransactionName = function (name) {
+ this._transactionName = name;
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * Can be removed in major version.
+ * @deprecated in favor of {@link this.setTransactionName}
+ */
+ Scope.prototype.setTransaction = function (name) {
+ return this.setTransactionName(name);
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setContext = function (key, context) {
+ var _a;
+ if (context === null) {
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
+ delete this._contexts[key];
+ }
+ else {
+ this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a));
+ }
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setSpan = function (span) {
+ this._span = span;
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.getSpan = function () {
+ return this._span;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.getTransaction = function () {
+ // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will
+ // have a pointer to the currently-active transaction.
+ var span = this.getSpan();
+ return span && span.transaction;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.setSession = function (session) {
+ if (!session) {
+ delete this._session;
+ }
+ else {
+ this._session = session;
+ }
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.getSession = function () {
+ return this._session;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.update = function (captureContext) {
+ if (!captureContext) {
+ return this;
+ }
+ if (typeof captureContext === 'function') {
+ var updatedScope = captureContext(this);
+ return updatedScope instanceof Scope ? updatedScope : this;
+ }
+ if (captureContext instanceof Scope) {
+ this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags);
+ this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra);
+ this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts);
+ if (captureContext._user && Object.keys(captureContext._user).length) {
+ this._user = captureContext._user;
+ }
+ if (captureContext._level) {
+ this._level = captureContext._level;
+ }
+ if (captureContext._fingerprint) {
+ this._fingerprint = captureContext._fingerprint;
+ }
+ if (captureContext._requestSession) {
+ this._requestSession = captureContext._requestSession;
+ }
+ }
+ else if (utils_1.isPlainObject(captureContext)) {
+ // eslint-disable-next-line no-param-reassign
+ captureContext = captureContext;
+ this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags);
+ this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra);
+ this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts);
+ if (captureContext.user) {
+ this._user = captureContext.user;
+ }
+ if (captureContext.level) {
+ this._level = captureContext.level;
+ }
+ if (captureContext.fingerprint) {
+ this._fingerprint = captureContext.fingerprint;
+ }
+ if (captureContext.requestSession) {
+ this._requestSession = captureContext.requestSession;
+ }
+ }
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.clear = function () {
+ this._breadcrumbs = [];
+ this._tags = {};
+ this._extra = {};
+ this._user = {};
+ this._contexts = {};
+ this._level = undefined;
+ this._transactionName = undefined;
+ this._fingerprint = undefined;
+ this._requestSession = undefined;
+ this._span = undefined;
+ this._session = undefined;
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) {
+ var maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;
+ // No data has been changed, so don't notify scope listeners
+ if (maxCrumbs <= 0) {
+ return this;
+ }
+ var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb);
+ this._breadcrumbs = tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs);
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * @inheritDoc
+ */
+ Scope.prototype.clearBreadcrumbs = function () {
+ this._breadcrumbs = [];
+ this._notifyScopeListeners();
+ return this;
+ };
+ /**
+ * Applies the current context and fingerprint to the event.
+ * Note that breadcrumbs will be added by the client.
+ * Also if the event has already breadcrumbs on it, we do not merge them.
+ * @param event Event
+ * @param hint May contain additional information about the original exception.
+ * @hidden
+ */
+ Scope.prototype.applyToEvent = function (event, hint) {
+ if (this._extra && Object.keys(this._extra).length) {
+ event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra);
+ }
+ if (this._tags && Object.keys(this._tags).length) {
+ event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags);
+ }
+ if (this._user && Object.keys(this._user).length) {
+ event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user);
+ }
+ if (this._contexts && Object.keys(this._contexts).length) {
+ event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts);
+ }
+ if (this._level) {
+ event.level = this._level;
+ }
+ if (this._transactionName) {
+ event.transaction = this._transactionName;
+ }
+ // We want to set the trace context for normal events only if there isn't already
+ // a trace context on the event. There is a product feature in place where we link
+ // errors with transaction and it relies on that.
+ if (this._span) {
+ event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts);
+ var transactionName = this._span.transaction && this._span.transaction.name;
+ if (transactionName) {
+ event.tags = tslib_1.__assign({ transaction: transactionName }, event.tags);
+ }
+ }
+ this._applyFingerprint(event);
+ event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs);
+ event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;
+ event.sdkProcessingMetadata = this._sdkProcessingMetadata;
+ return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint);
+ };
+ /**
+ * Add data which will be accessible during event processing but won't get sent to Sentry
+ */
+ Scope.prototype.setSDKProcessingMetadata = function (newData) {
+ this._sdkProcessingMetadata = tslib_1.__assign(tslib_1.__assign({}, this._sdkProcessingMetadata), newData);
+ return this;
+ };
+ /**
+ * This will be called after {@link applyToEvent} is finished.
+ */
+ Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) {
+ var _this = this;
+ if (index === void 0) { index = 0; }
+ return new utils_1.SyncPromise(function (resolve, reject) {
+ var processor = processors[index];
+ if (event === null || typeof processor !== 'function') {
+ resolve(event);
+ }
+ else {
+ var result = processor(tslib_1.__assign({}, event), hint);
+ if (utils_1.isThenable(result)) {
+ void result
+ .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); })
+ .then(null, reject);
+ }
+ else {
+ void _this._notifyEventProcessors(processors, result, hint, index + 1)
+ .then(resolve)
+ .then(null, reject);
+ }
+ }
+ });
+ };
+ /**
+ * This will be called on every set call.
+ */
+ Scope.prototype._notifyScopeListeners = function () {
+ var _this = this;
+ // We need this check for this._notifyingListeners to be able to work on scope during updates
+ // If this check is not here we'll produce endless recursion when something is done with the scope
+ // during the callback.
+ if (!this._notifyingListeners) {
+ this._notifyingListeners = true;
+ this._scopeListeners.forEach(function (callback) {
+ callback(_this);
+ });
+ this._notifyingListeners = false;
+ }
+ };
+ /**
+ * Applies fingerprint from the scope to the event if there's one,
+ * uses message if there's one instead or get rid of empty fingerprint
+ */
+ Scope.prototype._applyFingerprint = function (event) {
+ // Make sure it's an array first and we actually have something in place
+ event.fingerprint = event.fingerprint
+ ? Array.isArray(event.fingerprint)
+ ? event.fingerprint
+ : [event.fingerprint]
+ : [];
+ // If we have something on the scope, then merge it with event
+ if (this._fingerprint) {
+ event.fingerprint = event.fingerprint.concat(this._fingerprint);
+ }
+ // If we have no data at all, remove empty array default
+ if (event.fingerprint && !event.fingerprint.length) {
+ delete event.fingerprint;
+ }
+ };
+ return Scope;
+}());
+exports.Scope = Scope;
+/**
+ * Returns the global event processors.
+ */
+function getGlobalEventProcessors() {
+ return utils_1.getGlobalSingleton('globalEventProcessors', function () { return []; });
+}
+/**
+ * Add a EventProcessor to be kept globally.
+ * @param callback EventProcessor to add
+ */
+function addGlobalEventProcessor(callback) {
+ getGlobalEventProcessors().push(callback);
+}
+exports.addGlobalEventProcessor = addGlobalEventProcessor;
+//# sourceMappingURL=scope.js.map
+
+/***/ }),
+
+/***/ 12474:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+/**
+ * @inheritdoc
+ */
+var Session = /** @class */ (function () {
+ function Session(context) {
+ this.errors = 0;
+ this.sid = utils_1.uuid4();
+ this.duration = 0;
+ this.status = 'ok';
+ this.init = true;
+ this.ignoreDuration = false;
+ // Both timestamp and started are in seconds since the UNIX epoch.
+ var startingTime = utils_1.timestampInSeconds();
+ this.timestamp = startingTime;
+ this.started = startingTime;
+ if (context) {
+ this.update(context);
+ }
+ }
+ /** JSDoc */
+ // eslint-disable-next-line complexity
+ Session.prototype.update = function (context) {
+ if (context === void 0) { context = {}; }
+ if (context.user) {
+ if (!this.ipAddress && context.user.ip_address) {
+ this.ipAddress = context.user.ip_address;
+ }
+ if (!this.did && !context.did) {
+ this.did = context.user.id || context.user.email || context.user.username;
+ }
+ }
+ this.timestamp = context.timestamp || utils_1.timestampInSeconds();
+ if (context.ignoreDuration) {
+ this.ignoreDuration = context.ignoreDuration;
+ }
+ if (context.sid) {
+ // Good enough uuid validation. — Kamil
+ this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4();
+ }
+ if (context.init !== undefined) {
+ this.init = context.init;
+ }
+ if (!this.did && context.did) {
+ this.did = "" + context.did;
+ }
+ if (typeof context.started === 'number') {
+ this.started = context.started;
+ }
+ if (this.ignoreDuration) {
+ this.duration = undefined;
+ }
+ else if (typeof context.duration === 'number') {
+ this.duration = context.duration;
+ }
+ else {
+ var duration = this.timestamp - this.started;
+ this.duration = duration >= 0 ? duration : 0;
+ }
+ if (context.release) {
+ this.release = context.release;
+ }
+ if (context.environment) {
+ this.environment = context.environment;
+ }
+ if (!this.ipAddress && context.ipAddress) {
+ this.ipAddress = context.ipAddress;
+ }
+ if (!this.userAgent && context.userAgent) {
+ this.userAgent = context.userAgent;
+ }
+ if (typeof context.errors === 'number') {
+ this.errors = context.errors;
+ }
+ if (context.status) {
+ this.status = context.status;
+ }
+ };
+ /** JSDoc */
+ Session.prototype.close = function (status) {
+ if (status) {
+ this.update({ status: status });
+ }
+ else if (this.status === 'ok') {
+ this.update({ status: 'exited' });
+ }
+ else {
+ this.update();
+ }
+ };
+ /** JSDoc */
+ Session.prototype.toJSON = function () {
+ return utils_1.dropUndefinedKeys({
+ sid: "" + this.sid,
+ init: this.init,
+ // Make sure that sec is converted to ms for date constructor
+ started: new Date(this.started * 1000).toISOString(),
+ timestamp: new Date(this.timestamp * 1000).toISOString(),
+ status: this.status,
+ errors: this.errors,
+ did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined,
+ duration: this.duration,
+ attrs: {
+ release: this.release,
+ environment: this.environment,
+ ip_address: this.ipAddress,
+ user_agent: this.userAgent,
+ },
+ });
+ };
+ return Session;
+}());
+exports.Session = Session;
+//# sourceMappingURL=session.js.map
+
+/***/ }),
+
+/***/ 99695:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(30369);
+var hub_1 = __nccwpck_require__(53536);
+/**
+ * @inheritdoc
+ */
+var SessionFlusher = /** @class */ (function () {
+ function SessionFlusher(transport, attrs) {
+ var _this = this;
+ this.flushTimeout = 60;
+ this._pendingAggregates = {};
+ this._isEnabled = true;
+ this._transport = transport;
+ // Call to setInterval, so that flush is called every 60 seconds
+ this._intervalId = setInterval(function () { return _this.flush(); }, this.flushTimeout * 1000);
+ this._sessionAttrs = attrs;
+ }
+ /** Sends session aggregates to Transport */
+ SessionFlusher.prototype.sendSessionAggregates = function (sessionAggregates) {
+ if (!this._transport.sendSession) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession");
+ return;
+ }
+ void this._transport.sendSession(sessionAggregates).then(null, function (reason) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error('Error while sending session:', reason);
+ });
+ };
+ /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */
+ SessionFlusher.prototype.flush = function () {
+ var sessionAggregates = this.getSessionAggregates();
+ if (sessionAggregates.aggregates.length === 0) {
+ return;
+ }
+ this._pendingAggregates = {};
+ this.sendSessionAggregates(sessionAggregates);
+ };
+ /** Massages the entries in `pendingAggregates` and returns aggregated sessions */
+ SessionFlusher.prototype.getSessionAggregates = function () {
+ var _this = this;
+ var aggregates = Object.keys(this._pendingAggregates).map(function (key) {
+ return _this._pendingAggregates[parseInt(key)];
+ });
+ var sessionAggregates = {
+ attrs: this._sessionAttrs,
+ aggregates: aggregates,
+ };
+ return utils_1.dropUndefinedKeys(sessionAggregates);
+ };
+ /** JSDoc */
+ SessionFlusher.prototype.close = function () {
+ clearInterval(this._intervalId);
+ this._isEnabled = false;
+ this.flush();
+ };
+ /**
+ * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then
+ * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to
+ * `_incrementSessionStatusCount` along with the start date
+ */
+ SessionFlusher.prototype.incrementSessionStatusCount = function () {
+ if (!this._isEnabled) {
+ return;
+ }
+ var scope = hub_1.getCurrentHub().getScope();
+ var requestSession = scope && scope.getRequestSession();
+ if (requestSession && requestSession.status) {
+ this._incrementSessionStatusCount(requestSession.status, new Date());
+ // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in
+ // case captureRequestSession is called more than once to prevent double count
+ if (scope) {
+ scope.setRequestSession(undefined);
+ }
+ /* eslint-enable @typescript-eslint/no-unsafe-member-access */
+ }
+ };
+ /**
+ * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of
+ * the session received
+ */
+ SessionFlusher.prototype._incrementSessionStatusCount = function (status, date) {
+ // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys
+ var sessionStartedTrunc = new Date(date).setSeconds(0, 0);
+ this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};
+ // corresponds to aggregated sessions in one specific minute bucket
+ // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1}
+ var aggregationCounts = this._pendingAggregates[sessionStartedTrunc];
+ if (!aggregationCounts.started) {
+ aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();
+ }
+ switch (status) {
+ case 'errored':
+ aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;
+ return aggregationCounts.errored;
+ case 'ok':
+ aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;
+ return aggregationCounts.exited;
+ default:
+ aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;
+ return aggregationCounts.crashed;
+ }
+ };
+ return SessionFlusher;
+}());
+exports.SessionFlusher = SessionFlusher;
+//# sourceMappingURL=sessionflusher.js.map
+
+/***/ }),
+
+/***/ 88455:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var hub_1 = __nccwpck_require__(6393);
+/**
+ * This calls a function on the current hub.
+ * @param method function to call on hub.
+ * @param args to pass to function.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function callOnHub(method) {
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ var hub = hub_1.getCurrentHub();
+ if (hub && hub[method]) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return hub[method].apply(hub, tslib_1.__spread(args));
+ }
+ throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report.");
+}
+/**
+ * Captures an exception event and sends it to Sentry.
+ *
+ * @param exception An exception-like object.
+ * @returns The generated eventId.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
+function captureException(exception, captureContext) {
+ var syntheticException = new Error('Sentry syntheticException');
+ return callOnHub('captureException', exception, {
+ captureContext: captureContext,
+ originalException: exception,
+ syntheticException: syntheticException,
+ });
+}
+exports.captureException = captureException;
+/**
+ * Captures a message event and sends it to Sentry.
+ *
+ * @param message The message to send to Sentry.
+ * @param Severity Define the level of the message.
+ * @returns The generated eventId.
+ */
+function captureMessage(message, captureContext) {
+ var syntheticException = new Error(message);
+ // This is necessary to provide explicit scopes upgrade, without changing the original
+ // arity of the `captureMessage(message, level)` method.
+ var level = typeof captureContext === 'string' ? captureContext : undefined;
+ var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined;
+ return callOnHub('captureMessage', message, level, tslib_1.__assign({ originalException: message, syntheticException: syntheticException }, context));
+}
+exports.captureMessage = captureMessage;
+/**
+ * Captures a manually created event and sends it to Sentry.
+ *
+ * @param event The event to send to Sentry.
+ * @returns The generated eventId.
+ */
+function captureEvent(event) {
+ return callOnHub('captureEvent', event);
+}
+exports.captureEvent = captureEvent;
+/**
+ * Callback to set context information onto the scope.
+ * @param callback Callback function that receives Scope.
+ */
+function configureScope(callback) {
+ callOnHub('configureScope', callback);
+}
+exports.configureScope = configureScope;
+/**
+ * Records a new breadcrumb which will be attached to future events.
+ *
+ * Breadcrumbs will be added to subsequent events to provide more context on
+ * user's actions prior to an error or crash.
+ *
+ * @param breadcrumb The breadcrumb to record.
+ */
+function addBreadcrumb(breadcrumb) {
+ callOnHub('addBreadcrumb', breadcrumb);
+}
+exports.addBreadcrumb = addBreadcrumb;
+/**
+ * Sets context data with the given name.
+ * @param name of the context
+ * @param context Any kind of data. This data will be normalized.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function setContext(name, context) {
+ callOnHub('setContext', name, context);
+}
+exports.setContext = setContext;
+/**
+ * Set an object that will be merged sent as extra data with the event.
+ * @param extras Extras object to merge into current context.
+ */
+function setExtras(extras) {
+ callOnHub('setExtras', extras);
+}
+exports.setExtras = setExtras;
+/**
+ * Set an object that will be merged sent as tags data with the event.
+ * @param tags Tags context object to merge into current context.
+ */
+function setTags(tags) {
+ callOnHub('setTags', tags);
+}
+exports.setTags = setTags;
+/**
+ * Set key:value that will be sent as extra data with the event.
+ * @param key String of extra
+ * @param extra Any kind of data. This data will be normalized.
+ */
+function setExtra(key, extra) {
+ callOnHub('setExtra', key, extra);
+}
+exports.setExtra = setExtra;
+/**
+ * Set key:value that will be sent as tags data with the event.
+ *
+ * Can also be used to unset a tag, by passing `undefined`.
+ *
+ * @param key String key of tag
+ * @param value Value of tag
+ */
+function setTag(key, value) {
+ callOnHub('setTag', key, value);
+}
+exports.setTag = setTag;
+/**
+ * Updates user context information for future events.
+ *
+ * @param user User context object to be set in the current context. Pass `null` to unset the user.
+ */
+function setUser(user) {
+ callOnHub('setUser', user);
+}
+exports.setUser = setUser;
+/**
+ * Creates a new scope with and executes the given operation within.
+ * The scope is automatically removed once the operation
+ * finishes or throws.
+ *
+ * This is essentially a convenience function for:
+ *
+ * pushScope();
+ * callback();
+ * popScope();
+ *
+ * @param callback that will be enclosed into push/popScope.
+ */
+function withScope(callback) {
+ callOnHub('withScope', callback);
+}
+exports.withScope = withScope;
+/**
+ * Calls a function on the latest client. Use this with caution, it's meant as
+ * in "internal" helper so we don't need to expose every possible function in
+ * the shim. It is not guaranteed that the client actually implements the
+ * function.
+ *
+ * @param method The method to call on the client/client.
+ * @param args Arguments to pass to the client/fontend.
+ * @hidden
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function _callOnClient(method) {
+ var args = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ args[_i - 1] = arguments[_i];
+ }
+ callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args));
+}
+exports._callOnClient = _callOnClient;
+/**
+ * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.
+ *
+ * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a
+ * new child span within the transaction or any span, call the respective `.startChild()` method.
+ *
+ * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.
+ *
+ * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its
+ * finished child spans will be sent to Sentry.
+ *
+ * @param context Properties of the new `Transaction`.
+ * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent
+ * default values). See {@link Options.tracesSampler}.
+ *
+ * @returns The transaction which was just started
+ */
+function startTransaction(context, customSamplingContext) {
+ return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext);
+}
+exports.startTransaction = startTransaction;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 40508:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var types_1 = __nccwpck_require__(83789);
+var utils_1 = __nccwpck_require__(1620);
+var eventbuilder_1 = __nccwpck_require__(79287);
+var transports_1 = __nccwpck_require__(21437);
+/**
+ * The Sentry Node SDK Backend.
+ * @hidden
+ */
+var NodeBackend = /** @class */ (function (_super) {
+ tslib_1.__extends(NodeBackend, _super);
+ function NodeBackend() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ /**
+ * @inheritDoc
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
+ NodeBackend.prototype.eventFromException = function (exception, hint) {
+ return utils_1.resolvedSyncPromise(eventbuilder_1.eventFromUnknownInput(exception, hint));
+ };
+ /**
+ * @inheritDoc
+ */
+ NodeBackend.prototype.eventFromMessage = function (message, level, hint) {
+ if (level === void 0) { level = types_1.Severity.Info; }
+ return utils_1.resolvedSyncPromise(eventbuilder_1.eventFromMessage(message, level, hint, this._options.attachStacktrace));
+ };
+ /**
+ * @inheritDoc
+ */
+ NodeBackend.prototype._setupTransport = function () {
+ if (!this._options.dsn) {
+ // We return the noop transport here in case there is no Dsn.
+ return _super.prototype._setupTransport.call(this);
+ }
+ var dsn = utils_1.makeDsn(this._options.dsn);
+ var transportOptions = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this._options.transportOptions), (this._options.httpProxy && { httpProxy: this._options.httpProxy })), (this._options.httpsProxy && { httpsProxy: this._options.httpsProxy })), (this._options.caCerts && { caCerts: this._options.caCerts })), { dsn: this._options.dsn, tunnel: this._options.tunnel, _metadata: this._options._metadata });
+ if (this._options.transport) {
+ return new this._options.transport(transportOptions);
+ }
+ var api = core_1.initAPIDetails(transportOptions.dsn, transportOptions._metadata, transportOptions.tunnel);
+ var url = core_1.getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel);
+ this._newTransport = transports_1.makeNodeTransport({
+ url: url,
+ headers: transportOptions.headers,
+ proxy: transportOptions.httpProxy,
+ caCerts: transportOptions.caCerts,
+ });
+ if (dsn.protocol === 'http') {
+ return new transports_1.HTTPTransport(transportOptions);
+ }
+ return new transports_1.HTTPSTransport(transportOptions);
+ };
+ return NodeBackend;
+}(core_1.BaseBackend));
+exports.NodeBackend = NodeBackend;
+//# sourceMappingURL=backend.js.map
+
+/***/ }),
+
+/***/ 86147:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var hub_1 = __nccwpck_require__(6393);
+var utils_1 = __nccwpck_require__(1620);
+var backend_1 = __nccwpck_require__(40508);
+var flags_1 = __nccwpck_require__(71188);
+/**
+ * The Sentry Node SDK Client.
+ *
+ * @see NodeOptions for documentation on configuration options.
+ * @see SentryClient for usage documentation.
+ */
+var NodeClient = /** @class */ (function (_super) {
+ tslib_1.__extends(NodeClient, _super);
+ /**
+ * Creates a new Node SDK instance.
+ * @param options Configuration options for this SDK.
+ */
+ function NodeClient(options) {
+ var _this = this;
+ options._metadata = options._metadata || {};
+ options._metadata.sdk = options._metadata.sdk || {
+ name: 'sentry.javascript.node',
+ packages: [
+ {
+ name: 'npm:@sentry/node',
+ version: core_1.SDK_VERSION,
+ },
+ ],
+ version: core_1.SDK_VERSION,
+ };
+ _this = _super.call(this, backend_1.NodeBackend, options) || this;
+ return _this;
+ }
+ /**
+ * @inheritDoc
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
+ NodeClient.prototype.captureException = function (exception, hint, scope) {
+ // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only
+ // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload
+ // sent to the Server only when the `requestHandler` middleware is used
+ if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
+ var requestSession = scope.getRequestSession();
+ // Necessary checks to ensure this is code block is executed only within a request
+ // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage
+ if (requestSession && requestSession.status === 'ok') {
+ requestSession.status = 'errored';
+ }
+ }
+ return _super.prototype.captureException.call(this, exception, hint, scope);
+ };
+ /**
+ * @inheritDoc
+ */
+ NodeClient.prototype.captureEvent = function (event, hint, scope) {
+ // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only
+ // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload
+ // sent to the Server only when the `requestHandler` middleware is used
+ if (this._options.autoSessionTracking && this._sessionFlusher && scope) {
+ var eventType = event.type || 'exception';
+ var isException = eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;
+ // If the event is of type Exception, then a request session should be captured
+ if (isException) {
+ var requestSession = scope.getRequestSession();
+ // Ensure that this is happening within the bounds of a request, and make sure not to override
+ // Session Status if Errored / Crashed
+ if (requestSession && requestSession.status === 'ok') {
+ requestSession.status = 'errored';
+ }
+ }
+ }
+ return _super.prototype.captureEvent.call(this, event, hint, scope);
+ };
+ /**
+ *
+ * @inheritdoc
+ */
+ NodeClient.prototype.close = function (timeout) {
+ var _a;
+ (_a = this._sessionFlusher) === null || _a === void 0 ? void 0 : _a.close();
+ return _super.prototype.close.call(this, timeout);
+ };
+ /** Method that initialises an instance of SessionFlusher on Client */
+ NodeClient.prototype.initSessionFlusher = function () {
+ var _a = this._options, release = _a.release, environment = _a.environment;
+ if (!release) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');
+ }
+ else {
+ this._sessionFlusher = new hub_1.SessionFlusher(this.getTransport(), {
+ release: release,
+ environment: environment,
+ });
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ NodeClient.prototype._prepareEvent = function (event, scope, hint) {
+ event.platform = event.platform || 'node';
+ if (this.getOptions().serverName) {
+ event.server_name = this.getOptions().serverName;
+ }
+ return _super.prototype._prepareEvent.call(this, event, scope, hint);
+ };
+ /**
+ * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment
+ * appropriate session aggregates bucket
+ */
+ NodeClient.prototype._captureRequestSession = function () {
+ if (!this._sessionFlusher) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('Discarded request mode session because autoSessionTracking option was disabled');
+ }
+ else {
+ this._sessionFlusher.incrementSessionStatusCount();
+ }
+ };
+ return NodeClient;
+}(core_1.BaseClient));
+exports.NodeClient = NodeClient;
+//# sourceMappingURL=client.js.map
+
+/***/ }),
+
+/***/ 79287:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var hub_1 = __nccwpck_require__(6393);
+var types_1 = __nccwpck_require__(83789);
+var utils_1 = __nccwpck_require__(1620);
+var stack_parser_1 = __nccwpck_require__(94854);
+/**
+ * Extracts stack frames from the error.stack string
+ */
+function parseStackFrames(error) {
+ return utils_1.createStackParser(stack_parser_1.nodeStackParser)(error.stack || '', 1);
+}
+exports.parseStackFrames = parseStackFrames;
+/**
+ * Extracts stack frames from the error and builds a Sentry Exception
+ */
+function exceptionFromError(error) {
+ var exception = {
+ type: error.name || error.constructor.name,
+ value: error.message,
+ };
+ var frames = parseStackFrames(error);
+ if (frames.length) {
+ exception.stacktrace = { frames: frames };
+ }
+ return exception;
+}
+exports.exceptionFromError = exceptionFromError;
+/**
+ * Builds and Event from a Exception
+ * @hidden
+ */
+function eventFromUnknownInput(exception, hint) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ var ex = exception;
+ var providedMechanism = hint && hint.data && hint.data.mechanism;
+ var mechanism = providedMechanism || {
+ handled: true,
+ type: 'generic',
+ };
+ if (!utils_1.isError(exception)) {
+ if (utils_1.isPlainObject(exception)) {
+ // This will allow us to group events based on top-level keys
+ // which is much better than creating new group when any key/value change
+ var message = "Non-Error exception captured with keys: " + utils_1.extractExceptionKeysForMessage(exception);
+ hub_1.getCurrentHub().configureScope(function (scope) {
+ scope.setExtra('__serialized__', utils_1.normalizeToSize(exception));
+ });
+ ex = (hint && hint.syntheticException) || new Error(message);
+ ex.message = message;
+ }
+ else {
+ // This handles when someone does: `throw "something awesome";`
+ // We use synthesized Error here so we can extract a (rough) stack trace.
+ ex = (hint && hint.syntheticException) || new Error(exception);
+ ex.message = exception;
+ }
+ mechanism.synthetic = true;
+ }
+ var event = {
+ exception: {
+ values: [exceptionFromError(ex)],
+ },
+ };
+ utils_1.addExceptionTypeValue(event, undefined, undefined);
+ utils_1.addExceptionMechanism(event, mechanism);
+ return tslib_1.__assign(tslib_1.__assign({}, event), { event_id: hint && hint.event_id });
+}
+exports.eventFromUnknownInput = eventFromUnknownInput;
+/**
+ * Builds and Event from a Message
+ * @hidden
+ */
+function eventFromMessage(message, level, hint, attachStacktrace) {
+ if (level === void 0) { level = types_1.Severity.Info; }
+ var event = {
+ event_id: hint && hint.event_id,
+ level: level,
+ message: message,
+ };
+ if (attachStacktrace && hint && hint.syntheticException) {
+ var frames_1 = parseStackFrames(hint.syntheticException);
+ if (frames_1.length) {
+ event.stacktrace = { frames: frames_1 };
+ }
+ }
+ return event;
+}
+exports.eventFromMessage = eventFromMessage;
+//# sourceMappingURL=eventbuilder.js.map
+
+/***/ }),
+
+/***/ 71188:
+/***/ ((__unused_webpack_module, exports) => {
+
+/*
+ * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking
+ * for users.
+ *
+ * Debug flags need to be declared in each package individually and must not be imported across package boundaries,
+ * because some build tools have trouble tree-shaking imported guards.
+ *
+ * As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
+ *
+ * Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during
+ * our, or the user's build process. Take care when introducing new flags - they must not throw if they are not
+ * replaced.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/** Flag that is true for debug builds, false otherwise. */
+exports.IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;
+//# sourceMappingURL=flags.js.map
+
+/***/ }),
+
+/***/ 45400:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+/* eslint-disable max-lines */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var cookie = __nccwpck_require__(11668);
+var domain = __nccwpck_require__(13639);
+var os = __nccwpck_require__(22037);
+var url = __nccwpck_require__(57310);
+var flags_1 = __nccwpck_require__(71188);
+var sdk_1 = __nccwpck_require__(38836);
+/**
+ * Express-compatible tracing handler.
+ * @see Exposed as `Handlers.tracingHandler`
+ */
+function tracingHandler() {
+ return function sentryTracingMiddleware(req, res, next) {
+ // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision)
+ var traceparentData;
+ if (req.headers && utils_1.isString(req.headers['sentry-trace'])) {
+ traceparentData = utils_1.extractTraceparentData(req.headers['sentry-trace']);
+ }
+ var transaction = core_1.startTransaction(tslib_1.__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData),
+ // extra context passed to the tracesSampler
+ { request: extractRequestData(req) });
+ // We put the transaction on the scope so users can attach children to it
+ core_1.getCurrentHub().configureScope(function (scope) {
+ scope.setSpan(transaction);
+ });
+ // We also set __sentry_transaction on the response so people can grab the transaction there to add
+ // spans to it later.
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ res.__sentry_transaction = transaction;
+ res.once('finish', function () {
+ // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction
+ // closes
+ setImmediate(function () {
+ addExpressReqToTransaction(transaction, req);
+ transaction.setHttpStatus(res.statusCode);
+ transaction.finish();
+ });
+ });
+ next();
+ };
+}
+exports.tracingHandler = tracingHandler;
+/**
+ * Set parameterized as transaction name e.g.: `GET /users/:id`
+ * Also adds more context data on the transaction from the request
+ */
+function addExpressReqToTransaction(transaction, req) {
+ if (!transaction)
+ return;
+ transaction.name = extractExpressTransactionName(req, { path: true, method: true });
+ transaction.setData('url', req.originalUrl);
+ transaction.setData('baseUrl', req.baseUrl);
+ transaction.setData('query', req.query);
+}
+/**
+ * Extracts complete generalized path from the request object and uses it to construct transaction name.
+ *
+ * eg. GET /mountpoint/user/:id
+ *
+ * @param req The ExpressRequest object
+ * @param options What to include in the transaction name (method, path, or both)
+ *
+ * @returns The fully constructed transaction name
+ */
+function extractExpressTransactionName(req, options) {
+ if (options === void 0) { options = {}; }
+ var _a;
+ var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase();
+ var path = '';
+ if (req.route) {
+ path = "" + (req.baseUrl || '') + req.route.path;
+ }
+ else if (req.originalUrl || req.url) {
+ path = utils_1.stripUrlQueryAndFragment(req.originalUrl || req.url || '');
+ }
+ var info = '';
+ if (options.method && method) {
+ info += method;
+ }
+ if (options.method && options.path) {
+ info += ' ';
+ }
+ if (options.path && path) {
+ info += path;
+ }
+ return info;
+}
+/** JSDoc */
+function extractTransaction(req, type) {
+ var _a;
+ switch (type) {
+ case 'path': {
+ return extractExpressTransactionName(req, { path: true });
+ }
+ case 'handler': {
+ return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || '';
+ }
+ case 'methodPath':
+ default: {
+ return extractExpressTransactionName(req, { path: true, method: true });
+ }
+ }
+}
+/** Default user keys that'll be used to extract data from the request */
+var DEFAULT_USER_KEYS = ['id', 'username', 'email'];
+/** JSDoc */
+function extractUserData(user, keys) {
+ var extractedUser = {};
+ var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;
+ attributes.forEach(function (key) {
+ if (user && key in user) {
+ extractedUser[key] = user[key];
+ }
+ });
+ return extractedUser;
+}
+/** Default request keys that'll be used to extract data from the request */
+var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];
+/**
+ * Normalizes data from the request object, accounting for framework differences.
+ *
+ * @param req The request object from which to extract data
+ * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not
+ * provided.
+ * @returns An object containing normalized request data
+ */
+function extractRequestData(req, keys) {
+ if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; }
+ var requestData = {};
+ // headers:
+ // node, express, nextjs: req.headers
+ // koa: req.header
+ var headers = (req.headers || req.header || {});
+ // method:
+ // node, express, koa, nextjs: req.method
+ var method = req.method;
+ // host:
+ // express: req.hostname in > 4 and req.host in < 4
+ // koa: req.host
+ // node, nextjs: req.headers.host
+ var host = req.hostname || req.host || headers.host || '';
+ // protocol:
+ // node, nextjs:
+ // express, koa: req.protocol
+ var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted
+ ? 'https'
+ : 'http';
+ // url (including path and query string):
+ // node, express: req.originalUrl
+ // koa, nextjs: req.url
+ var originalUrl = (req.originalUrl || req.url || '');
+ // absolute url
+ var absoluteUrl = protocol + "://" + host + originalUrl;
+ keys.forEach(function (key) {
+ switch (key) {
+ case 'headers':
+ requestData.headers = headers;
+ break;
+ case 'method':
+ requestData.method = method;
+ break;
+ case 'url':
+ requestData.url = absoluteUrl;
+ break;
+ case 'cookies':
+ // cookies:
+ // node, express, koa: req.headers.cookie
+ // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ requestData.cookies = req.cookies || cookie.parse(headers.cookie || '');
+ break;
+ case 'query_string':
+ // query string:
+ // node: req.url (raw)
+ // express, koa, nextjs: req.query
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ requestData.query_string = req.query || url.parse(originalUrl || '', false).query;
+ break;
+ case 'data':
+ if (method === 'GET' || method === 'HEAD') {
+ break;
+ }
+ // body data:
+ // express, koa, nextjs: req.body
+ //
+ // when using node by itself, you have to read the incoming stream(see
+ // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know
+ // where they're going to store the final result, so they'll have to capture this data themselves
+ if (req.body !== undefined) {
+ requestData.data = utils_1.isString(req.body) ? req.body : JSON.stringify(utils_1.normalize(req.body));
+ }
+ break;
+ default:
+ if ({}.hasOwnProperty.call(req, key)) {
+ requestData[key] = req[key];
+ }
+ }
+ });
+ return requestData;
+}
+exports.extractRequestData = extractRequestData;
+/**
+ * Enriches passed event with request data.
+ *
+ * @param event Will be mutated and enriched with req data
+ * @param req Request object
+ * @param options object containing flags to enable functionality
+ * @hidden
+ */
+function parseRequest(event, req, options) {
+ // eslint-disable-next-line no-param-reassign
+ options = tslib_1.__assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options);
+ if (options.version) {
+ event.contexts = tslib_1.__assign(tslib_1.__assign({}, event.contexts), { runtime: {
+ name: 'node',
+ version: global.process.version,
+ } });
+ }
+ if (options.request) {
+ // if the option value is `true`, use the default set of keys by not passing anything to `extractRequestData()`
+ var extractedRequestData = Array.isArray(options.request)
+ ? extractRequestData(req, options.request)
+ : extractRequestData(req);
+ event.request = tslib_1.__assign(tslib_1.__assign({}, event.request), extractedRequestData);
+ }
+ if (options.serverName && !event.server_name) {
+ event.server_name = global.process.env.SENTRY_NAME || os.hostname();
+ }
+ if (options.user) {
+ var extractedUser = req.user && utils_1.isPlainObject(req.user) ? extractUserData(req.user, options.user) : {};
+ if (Object.keys(extractedUser)) {
+ event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), extractedUser);
+ }
+ }
+ // client ip:
+ // node, nextjs: req.connection.remoteAddress
+ // express, koa: req.ip
+ if (options.ip) {
+ var ip = req.ip || (req.connection && req.connection.remoteAddress);
+ if (ip) {
+ event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), { ip_address: ip });
+ }
+ }
+ if (options.transaction && !event.transaction) {
+ // TODO do we even need this anymore?
+ // TODO make this work for nextjs
+ event.transaction = extractTransaction(req, options.transaction);
+ }
+ return event;
+}
+exports.parseRequest = parseRequest;
+/**
+ * Express compatible request handler.
+ * @see Exposed as `Handlers.requestHandler`
+ */
+function requestHandler(options) {
+ var currentHub = core_1.getCurrentHub();
+ var client = currentHub.getClient();
+ // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the
+ // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode
+ if (client && sdk_1.isAutoSessionTrackingEnabled(client)) {
+ client.initSessionFlusher();
+ // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode
+ var scope = currentHub.getScope();
+ if (scope && scope.getSession()) {
+ scope.setSession();
+ }
+ }
+ return function sentryRequestMiddleware(req, res, next) {
+ if (options && options.flushTimeout && options.flushTimeout > 0) {
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ var _end_1 = res.end;
+ res.end = function (chunk, encoding, cb) {
+ var _this = this;
+ void sdk_1.flush(options.flushTimeout)
+ .then(function () {
+ _end_1.call(_this, chunk, encoding, cb);
+ })
+ .then(null, function (e) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.error(e);
+ _end_1.call(_this, chunk, encoding, cb);
+ });
+ };
+ }
+ var local = domain.create();
+ local.add(req);
+ local.add(res);
+ local.on('error', next);
+ local.run(function () {
+ var currentHub = core_1.getCurrentHub();
+ currentHub.configureScope(function (scope) {
+ scope.addEventProcessor(function (event) { return parseRequest(event, req, options); });
+ var client = currentHub.getClient();
+ if (sdk_1.isAutoSessionTrackingEnabled(client)) {
+ var scope_1 = currentHub.getScope();
+ if (scope_1) {
+ // Set `status` of `RequestSession` to Ok, at the beginning of the request
+ scope_1.setRequestSession({ status: 'ok' });
+ }
+ }
+ });
+ res.once('finish', function () {
+ var client = currentHub.getClient();
+ if (sdk_1.isAutoSessionTrackingEnabled(client)) {
+ setImmediate(function () {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ if (client && client._captureRequestSession) {
+ // Calling _captureRequestSession to capture request session at the end of the request by incrementing
+ // the correct SessionAggregates bucket i.e. crashed, errored or exited
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ client._captureRequestSession();
+ }
+ });
+ }
+ });
+ next();
+ });
+ };
+}
+exports.requestHandler = requestHandler;
+/** JSDoc */
+function getStatusCodeFromResponse(error) {
+ var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);
+ return statusCode ? parseInt(statusCode, 10) : 500;
+}
+/** Returns true if response code is internal server error */
+function defaultShouldHandleError(error) {
+ var status = getStatusCodeFromResponse(error);
+ return status >= 500;
+}
+/**
+ * Express compatible error handler.
+ * @see Exposed as `Handlers.errorHandler`
+ */
+function errorHandler(options) {
+ return function sentryErrorMiddleware(error, _req, res, next) {
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;
+ if (shouldHandleError(error)) {
+ core_1.withScope(function (_scope) {
+ // For some reason we need to set the transaction on the scope again
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ var transaction = res.__sentry_transaction;
+ if (transaction && _scope.getSpan() === undefined) {
+ _scope.setSpan(transaction);
+ }
+ var client = core_1.getCurrentHub().getClient();
+ if (client && sdk_1.isAutoSessionTrackingEnabled(client)) {
+ // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the
+ // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only
+ // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be
+ // running in SessionAggregates mode
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ var isSessionAggregatesMode = client._sessionFlusher !== undefined;
+ if (isSessionAggregatesMode) {
+ var requestSession = _scope.getRequestSession();
+ // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a
+ // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within
+ // the bounds of a request, and if so the status is updated
+ if (requestSession && requestSession.status !== undefined) {
+ requestSession.status = 'crashed';
+ }
+ }
+ }
+ var eventId = core_1.captureException(error);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ res.sentry = eventId;
+ next(error);
+ });
+ return;
+ }
+ next(error);
+ };
+}
+exports.errorHandler = errorHandler;
+//# sourceMappingURL=handlers.js.map
+
+/***/ }),
+
+/***/ 22783:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var types_1 = __nccwpck_require__(83789);
+exports.Severity = types_1.Severity;
+var core_1 = __nccwpck_require__(79212);
+exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor;
+exports.addBreadcrumb = core_1.addBreadcrumb;
+exports.captureException = core_1.captureException;
+exports.captureEvent = core_1.captureEvent;
+exports.captureMessage = core_1.captureMessage;
+exports.configureScope = core_1.configureScope;
+exports.getHubFromCarrier = core_1.getHubFromCarrier;
+exports.getCurrentHub = core_1.getCurrentHub;
+exports.Hub = core_1.Hub;
+exports.makeMain = core_1.makeMain;
+exports.Scope = core_1.Scope;
+exports.Session = core_1.Session;
+exports.startTransaction = core_1.startTransaction;
+exports.SDK_VERSION = core_1.SDK_VERSION;
+exports.setContext = core_1.setContext;
+exports.setExtra = core_1.setExtra;
+exports.setExtras = core_1.setExtras;
+exports.setTag = core_1.setTag;
+exports.setTags = core_1.setTags;
+exports.setUser = core_1.setUser;
+exports.withScope = core_1.withScope;
+var backend_1 = __nccwpck_require__(40508);
+exports.NodeBackend = backend_1.NodeBackend;
+var client_1 = __nccwpck_require__(86147);
+exports.NodeClient = client_1.NodeClient;
+var sdk_1 = __nccwpck_require__(38836);
+exports.defaultIntegrations = sdk_1.defaultIntegrations;
+exports.init = sdk_1.init;
+exports.lastEventId = sdk_1.lastEventId;
+exports.flush = sdk_1.flush;
+exports.close = sdk_1.close;
+exports.getSentryRelease = sdk_1.getSentryRelease;
+var utils_1 = __nccwpck_require__(27937);
+exports.deepReadDirSync = utils_1.deepReadDirSync;
+var version_1 = __nccwpck_require__(31271);
+exports.SDK_NAME = version_1.SDK_NAME;
+var core_2 = __nccwpck_require__(79212);
+var hub_1 = __nccwpck_require__(6393);
+var domain = __nccwpck_require__(13639);
+var Handlers = __nccwpck_require__(45400);
+exports.Handlers = Handlers;
+var NodeIntegrations = __nccwpck_require__(72310);
+var Transports = __nccwpck_require__(21437);
+exports.Transports = Transports;
+var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations);
+exports.Integrations = INTEGRATIONS;
+// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like
+// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`.
+var carrier = hub_1.getMainCarrier();
+if (carrier.__SENTRY__) {
+ carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};
+ carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain;
+}
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 29552:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var util = __nccwpck_require__(73837);
+/** Console module integration */
+var Console = /** @class */ (function () {
+ function Console() {
+ /**
+ * @inheritDoc
+ */
+ this.name = Console.id;
+ }
+ /**
+ * @inheritDoc
+ */
+ Console.prototype.setupOnce = function () {
+ var e_1, _a;
+ try {
+ for (var _b = tslib_1.__values(['debug', 'info', 'warn', 'error', 'log']), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var level = _c.value;
+ utils_1.fill(console, level, createConsoleWrapper(level));
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Console.id = 'Console';
+ return Console;
+}());
+exports.Console = Console;
+/**
+ * Wrapper function that'll be used for every console level
+ */
+function createConsoleWrapper(level) {
+ return function consoleWrapper(originalConsoleMethod) {
+ var sentryLevel = utils_1.severityFromString(level);
+ /* eslint-disable prefer-rest-params */
+ return function () {
+ if (core_1.getCurrentHub().getIntegration(Console)) {
+ core_1.getCurrentHub().addBreadcrumb({
+ category: 'console',
+ level: sentryLevel,
+ message: util.format.apply(undefined, arguments),
+ }, {
+ input: tslib_1.__spread(arguments),
+ level: level,
+ });
+ }
+ originalConsoleMethod.apply(this, arguments);
+ };
+ /* eslint-enable prefer-rest-params */
+ };
+}
+//# sourceMappingURL=console.js.map
+
+/***/ }),
+
+/***/ 27797:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var fs_1 = __nccwpck_require__(57147);
+var lru_map_1 = __nccwpck_require__(18424);
+var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100);
+var DEFAULT_LINES_OF_CONTEXT = 7;
+// TODO: Replace with promisify when minimum supported node >= v8
+function readTextFileAsync(path) {
+ return new Promise(function (resolve, reject) {
+ fs_1.readFile(path, 'utf8', function (err, data) {
+ if (err)
+ reject(err);
+ else
+ resolve(data);
+ });
+ });
+}
+/**
+ * Resets the file cache. Exists for testing purposes.
+ * @hidden
+ */
+function resetFileContentCache() {
+ FILE_CONTENT_CACHE.clear();
+}
+exports.resetFileContentCache = resetFileContentCache;
+/** Add node modules / packages to the event */
+var ContextLines = /** @class */ (function () {
+ function ContextLines(_options) {
+ if (_options === void 0) { _options = {}; }
+ this._options = _options;
+ /**
+ * @inheritDoc
+ */
+ this.name = ContextLines.id;
+ }
+ Object.defineProperty(ContextLines.prototype, "_contextLines", {
+ /** Get's the number of context lines to add */
+ get: function () {
+ var _a, _b;
+ // This is only here to copy frameContextLines from init options if it hasn't
+ // been set via this integrations constructor.
+ //
+ // TODO: Remove on next major!
+ if (this._options.frameContextLines === undefined) {
+ var initOptions = (_a = core_1.getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getOptions();
+ // eslint-disable-next-line deprecation/deprecation
+ this._options.frameContextLines = (_b = initOptions) === null || _b === void 0 ? void 0 : _b.frameContextLines;
+ }
+ return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * @inheritDoc
+ */
+ ContextLines.prototype.setupOnce = function (addGlobalEventProcessor) {
+ var _this = this;
+ addGlobalEventProcessor(function (event) { return _this.addSourceContext(event); });
+ };
+ /** Processes an event and adds context lines */
+ ContextLines.prototype.addSourceContext = function (event) {
+ var _a, _b;
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var _c, _d, exception, e_1_1;
+ var e_1, _e;
+ return tslib_1.__generator(this, function (_f) {
+ switch (_f.label) {
+ case 0:
+ if (!(this._contextLines > 0 && ((_a = event.exception) === null || _a === void 0 ? void 0 : _a.values))) return [3 /*break*/, 8];
+ _f.label = 1;
+ case 1:
+ _f.trys.push([1, 6, 7, 8]);
+ _c = tslib_1.__values(event.exception.values), _d = _c.next();
+ _f.label = 2;
+ case 2:
+ if (!!_d.done) return [3 /*break*/, 5];
+ exception = _d.value;
+ if (!((_b = exception.stacktrace) === null || _b === void 0 ? void 0 : _b.frames)) return [3 /*break*/, 4];
+ return [4 /*yield*/, this.addSourceContextToFrames(exception.stacktrace.frames)];
+ case 3:
+ _f.sent();
+ _f.label = 4;
+ case 4:
+ _d = _c.next();
+ return [3 /*break*/, 2];
+ case 5: return [3 /*break*/, 8];
+ case 6:
+ e_1_1 = _f.sent();
+ e_1 = { error: e_1_1 };
+ return [3 /*break*/, 8];
+ case 7:
+ try {
+ if (_d && !_d.done && (_e = _c.return)) _e.call(_c);
+ }
+ finally { if (e_1) throw e_1.error; }
+ return [7 /*endfinally*/];
+ case 8: return [2 /*return*/, event];
+ }
+ });
+ });
+ };
+ /** Adds context lines to frames */
+ ContextLines.prototype.addSourceContextToFrames = function (frames) {
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var contextLines, frames_1, frames_1_1, frame, sourceFile, lines, e_2_1;
+ var e_2, _a;
+ return tslib_1.__generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ contextLines = this._contextLines;
+ _b.label = 1;
+ case 1:
+ _b.trys.push([1, 6, 7, 8]);
+ frames_1 = tslib_1.__values(frames), frames_1_1 = frames_1.next();
+ _b.label = 2;
+ case 2:
+ if (!!frames_1_1.done) return [3 /*break*/, 5];
+ frame = frames_1_1.value;
+ if (!(frame.filename && frame.context_line === undefined)) return [3 /*break*/, 4];
+ return [4 /*yield*/, _readSourceFile(frame.filename)];
+ case 3:
+ sourceFile = _b.sent();
+ if (sourceFile) {
+ try {
+ lines = sourceFile.split('\n');
+ utils_1.addContextToFrame(lines, frame, contextLines);
+ }
+ catch (e) {
+ // anomaly, being defensive in case
+ // unlikely to ever happen in practice but can definitely happen in theory
+ }
+ }
+ _b.label = 4;
+ case 4:
+ frames_1_1 = frames_1.next();
+ return [3 /*break*/, 2];
+ case 5: return [3 /*break*/, 8];
+ case 6:
+ e_2_1 = _b.sent();
+ e_2 = { error: e_2_1 };
+ return [3 /*break*/, 8];
+ case 7:
+ try {
+ if (frames_1_1 && !frames_1_1.done && (_a = frames_1.return)) _a.call(frames_1);
+ }
+ finally { if (e_2) throw e_2.error; }
+ return [7 /*endfinally*/];
+ case 8: return [2 /*return*/];
+ }
+ });
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ ContextLines.id = 'ContextLines';
+ return ContextLines;
+}());
+exports.ContextLines = ContextLines;
+/**
+ * Reads file contents and caches them in a global LRU cache.
+ *
+ * @param filename filepath to read content from.
+ */
+function _readSourceFile(filename) {
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var cachedFile, content, _1;
+ return tslib_1.__generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ cachedFile = FILE_CONTENT_CACHE.get(filename);
+ // We have a cache hit
+ if (cachedFile !== undefined) {
+ return [2 /*return*/, cachedFile];
+ }
+ content = null;
+ _a.label = 1;
+ case 1:
+ _a.trys.push([1, 3, , 4]);
+ return [4 /*yield*/, readTextFileAsync(filename)];
+ case 2:
+ content = _a.sent();
+ return [3 /*break*/, 4];
+ case 3:
+ _1 = _a.sent();
+ return [3 /*break*/, 4];
+ case 4:
+ FILE_CONTENT_CACHE.set(filename, content);
+ return [2 /*return*/, content];
+ }
+ });
+ });
+}
+//# sourceMappingURL=contextlines.js.map
+
+/***/ }),
+
+/***/ 76280:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(71188);
+var http_1 = __nccwpck_require__(84103);
+var NODE_VERSION = utils_1.parseSemver(process.versions.node);
+/** http module integration */
+var Http = /** @class */ (function () {
+ /**
+ * @inheritDoc
+ */
+ function Http(options) {
+ if (options === void 0) { options = {}; }
+ /**
+ * @inheritDoc
+ */
+ this.name = Http.id;
+ this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;
+ this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing;
+ }
+ /**
+ * @inheritDoc
+ */
+ Http.prototype.setupOnce = function () {
+ // No need to instrument if we don't want to track anything
+ if (!this._breadcrumbs && !this._tracing) {
+ return;
+ }
+ var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing);
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ var httpModule = __nccwpck_require__(13685);
+ utils_1.fill(httpModule, 'get', wrappedHandlerMaker);
+ utils_1.fill(httpModule, 'request', wrappedHandlerMaker);
+ // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.
+ // If we do, we'd get double breadcrumbs and double spans for `https` calls.
+ // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately.
+ if (NODE_VERSION.major && NODE_VERSION.major > 8) {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ var httpsModule = __nccwpck_require__(95687);
+ utils_1.fill(httpsModule, 'get', wrappedHandlerMaker);
+ utils_1.fill(httpsModule, 'request', wrappedHandlerMaker);
+ }
+ };
+ /**
+ * @inheritDoc
+ */
+ Http.id = 'Http';
+ return Http;
+}());
+exports.Http = Http;
+/**
+ * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http`
+ * and `https` modules. (NB: Not a typo - this is a creator^2!)
+ *
+ * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs
+ * @param tracingEnabled Whether or not to record outgoing requests as tracing spans
+ *
+ * @returns A function which accepts the exiting handler and returns a wrapped handler
+ */
+function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) {
+ return function wrappedRequestMethodFactory(originalRequestMethod) {
+ return function wrappedMethod() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ var httpModule = this;
+ var requestArgs = http_1.normalizeRequestArgs(this, args);
+ var requestOptions = requestArgs[0];
+ var requestUrl = http_1.extractUrl(requestOptions);
+ // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method
+ if (http_1.isSentryRequest(requestUrl)) {
+ return originalRequestMethod.apply(httpModule, requestArgs);
+ }
+ var span;
+ var parentSpan;
+ var scope = core_1.getCurrentHub().getScope();
+ if (scope && tracingEnabled) {
+ parentSpan = scope.getSpan();
+ if (parentSpan) {
+ span = parentSpan.startChild({
+ description: (requestOptions.method || 'GET') + " " + requestUrl,
+ op: 'http.client',
+ });
+ var sentryTraceHeader = span.toTraceparent();
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": ");
+ requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader });
+ }
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ return originalRequestMethod
+ .apply(httpModule, requestArgs)
+ .once('response', function (res) {
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ var req = this;
+ if (breadcrumbsEnabled) {
+ addRequestBreadcrumb('response', requestUrl, req, res);
+ }
+ if (tracingEnabled && span) {
+ if (res.statusCode) {
+ span.setHttpStatus(res.statusCode);
+ }
+ span.description = http_1.cleanSpanDescription(span.description, requestOptions, req);
+ span.finish();
+ }
+ })
+ .once('error', function () {
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ var req = this;
+ if (breadcrumbsEnabled) {
+ addRequestBreadcrumb('error', requestUrl, req);
+ }
+ if (tracingEnabled && span) {
+ span.setHttpStatus(500);
+ span.description = http_1.cleanSpanDescription(span.description, requestOptions, req);
+ span.finish();
+ }
+ });
+ };
+ };
+}
+/**
+ * Captures Breadcrumb based on provided request/response pair
+ */
+function addRequestBreadcrumb(event, url, req, res) {
+ if (!core_1.getCurrentHub().getIntegration(Http)) {
+ return;
+ }
+ core_1.getCurrentHub().addBreadcrumb({
+ category: 'http',
+ data: {
+ method: req.method,
+ status_code: res && res.statusCode,
+ url: url,
+ },
+ type: 'http',
+ }, {
+ event: event,
+ request: req,
+ response: res,
+ });
+}
+//# sourceMappingURL=http.js.map
+
+/***/ }),
+
+/***/ 72310:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var console_1 = __nccwpck_require__(29552);
+exports.Console = console_1.Console;
+var http_1 = __nccwpck_require__(76280);
+exports.Http = http_1.Http;
+var onuncaughtexception_1 = __nccwpck_require__(50443);
+exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException;
+var onunhandledrejection_1 = __nccwpck_require__(87344);
+exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection;
+var linkederrors_1 = __nccwpck_require__(70208);
+exports.LinkedErrors = linkederrors_1.LinkedErrors;
+var modules_1 = __nccwpck_require__(90046);
+exports.Modules = modules_1.Modules;
+var contextlines_1 = __nccwpck_require__(27797);
+exports.ContextLines = contextlines_1.ContextLines;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 70208:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var eventbuilder_1 = __nccwpck_require__(79287);
+var contextlines_1 = __nccwpck_require__(27797);
+var DEFAULT_KEY = 'cause';
+var DEFAULT_LIMIT = 5;
+/** Adds SDK info to an event. */
+var LinkedErrors = /** @class */ (function () {
+ /**
+ * @inheritDoc
+ */
+ function LinkedErrors(options) {
+ if (options === void 0) { options = {}; }
+ /**
+ * @inheritDoc
+ */
+ this.name = LinkedErrors.id;
+ this._key = options.key || DEFAULT_KEY;
+ this._limit = options.limit || DEFAULT_LIMIT;
+ }
+ /**
+ * @inheritDoc
+ */
+ LinkedErrors.prototype.setupOnce = function () {
+ core_1.addGlobalEventProcessor(function (event, hint) {
+ var self = core_1.getCurrentHub().getIntegration(LinkedErrors);
+ if (self) {
+ var handler = self._handler && self._handler.bind(self);
+ return typeof handler === 'function' ? handler(event, hint) : event;
+ }
+ return event;
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ LinkedErrors.prototype._handler = function (event, hint) {
+ var _this = this;
+ if (!event.exception || !event.exception.values || !hint || !utils_1.isInstanceOf(hint.originalException, Error)) {
+ return utils_1.resolvedSyncPromise(event);
+ }
+ return new utils_1.SyncPromise(function (resolve) {
+ void _this._walkErrorTree(hint.originalException, _this._key)
+ .then(function (linkedErrors) {
+ if (event && event.exception && event.exception.values) {
+ event.exception.values = tslib_1.__spread(linkedErrors, event.exception.values);
+ }
+ resolve(event);
+ })
+ .then(null, function () {
+ resolve(event);
+ });
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ LinkedErrors.prototype._walkErrorTree = function (error, key, stack) {
+ if (stack === void 0) { stack = []; }
+ var _a;
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var exception, contextLines;
+ var _this = this;
+ return tslib_1.__generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ if (!utils_1.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {
+ return [2 /*return*/, Promise.resolve(stack)];
+ }
+ exception = eventbuilder_1.exceptionFromError(error[key]);
+ contextLines = core_1.getCurrentHub().getIntegration(contextlines_1.ContextLines);
+ if (!(contextLines && ((_a = exception.stacktrace) === null || _a === void 0 ? void 0 : _a.frames))) return [3 /*break*/, 2];
+ return [4 /*yield*/, contextLines.addSourceContextToFrames(exception.stacktrace.frames)];
+ case 1:
+ _b.sent();
+ _b.label = 2;
+ case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
+ void _this._walkErrorTree(error[key], key, tslib_1.__spread([exception], stack))
+ .then(resolve)
+ .then(null, function () {
+ reject();
+ });
+ })];
+ }
+ });
+ });
+ };
+ /**
+ * @inheritDoc
+ */
+ LinkedErrors.id = 'LinkedErrors';
+ return LinkedErrors;
+}());
+exports.LinkedErrors = LinkedErrors;
+//# sourceMappingURL=linkederrors.js.map
+
+/***/ }),
+
+/***/ 90046:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var fs_1 = __nccwpck_require__(57147);
+var path_1 = __nccwpck_require__(71017);
+var moduleCache;
+/** Extract information about paths */
+function getPaths() {
+ try {
+ return require.cache ? Object.keys(require.cache) : [];
+ }
+ catch (e) {
+ return [];
+ }
+}
+/** Extract information about package.json modules */
+function collectModules() {
+ var mainPaths = (require.main && require.main.paths) || [];
+ var paths = getPaths();
+ var infos = {};
+ var seen = {};
+ paths.forEach(function (path) {
+ var dir = path;
+ /** Traverse directories upward in the search of package.json file */
+ var updir = function () {
+ var orig = dir;
+ dir = path_1.dirname(orig);
+ if (!dir || orig === dir || seen[orig]) {
+ return undefined;
+ }
+ if (mainPaths.indexOf(dir) < 0) {
+ return updir();
+ }
+ var pkgfile = path_1.join(orig, 'package.json');
+ seen[orig] = true;
+ if (!fs_1.existsSync(pkgfile)) {
+ return updir();
+ }
+ try {
+ var info = JSON.parse(fs_1.readFileSync(pkgfile, 'utf8'));
+ infos[info.name] = info.version;
+ }
+ catch (_oO) {
+ // no-empty
+ }
+ };
+ updir();
+ });
+ return infos;
+}
+/** Add node modules / packages to the event */
+var Modules = /** @class */ (function () {
+ function Modules() {
+ /**
+ * @inheritDoc
+ */
+ this.name = Modules.id;
+ }
+ /**
+ * @inheritDoc
+ */
+ Modules.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) {
+ var _this = this;
+ addGlobalEventProcessor(function (event) {
+ if (!getCurrentHub().getIntegration(Modules)) {
+ return event;
+ }
+ return tslib_1.__assign(tslib_1.__assign({}, event), { modules: _this._getModules() });
+ });
+ };
+ /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */
+ Modules.prototype._getModules = function () {
+ if (!moduleCache) {
+ moduleCache = collectModules();
+ }
+ return moduleCache;
+ };
+ /**
+ * @inheritDoc
+ */
+ Modules.id = 'Modules';
+ return Modules;
+}());
+exports.Modules = Modules;
+//# sourceMappingURL=modules.js.map
+
+/***/ }),
+
+/***/ 50443:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var core_1 = __nccwpck_require__(79212);
+var types_1 = __nccwpck_require__(83789);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(71188);
+var errorhandling_1 = __nccwpck_require__(5635);
+/** Global Promise Rejection handler */
+var OnUncaughtException = /** @class */ (function () {
+ /**
+ * @inheritDoc
+ */
+ function OnUncaughtException(_options) {
+ if (_options === void 0) { _options = {}; }
+ this._options = _options;
+ /**
+ * @inheritDoc
+ */
+ this.name = OnUncaughtException.id;
+ /**
+ * @inheritDoc
+ */
+ this.handler = this._makeErrorHandler();
+ }
+ /**
+ * @inheritDoc
+ */
+ OnUncaughtException.prototype.setupOnce = function () {
+ global.process.on('uncaughtException', this.handler.bind(this));
+ };
+ /**
+ * @hidden
+ */
+ OnUncaughtException.prototype._makeErrorHandler = function () {
+ var _this = this;
+ var timeout = 2000;
+ var caughtFirstError = false;
+ var caughtSecondError = false;
+ var calledFatalError = false;
+ var firstError;
+ return function (error) {
+ var onFatalError = errorhandling_1.logAndExitProcess;
+ var client = core_1.getCurrentHub().getClient();
+ if (_this._options.onFatalError) {
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ onFatalError = _this._options.onFatalError;
+ }
+ else if (client && client.getOptions().onFatalError) {
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ onFatalError = client.getOptions().onFatalError;
+ }
+ if (!caughtFirstError) {
+ var hub_1 = core_1.getCurrentHub();
+ // this is the first uncaught error and the ultimate reason for shutting down
+ // we want to do absolutely everything possible to ensure it gets captured
+ // also we want to make sure we don't go recursion crazy if more errors happen after this one
+ firstError = error;
+ caughtFirstError = true;
+ if (hub_1.getIntegration(OnUncaughtException)) {
+ hub_1.withScope(function (scope) {
+ scope.setLevel(types_1.Severity.Fatal);
+ hub_1.captureException(error, {
+ originalException: error,
+ data: { mechanism: { handled: false, type: 'onuncaughtexception' } },
+ });
+ if (!calledFatalError) {
+ calledFatalError = true;
+ onFatalError(error);
+ }
+ });
+ }
+ else {
+ if (!calledFatalError) {
+ calledFatalError = true;
+ onFatalError(error);
+ }
+ }
+ }
+ else if (calledFatalError) {
+ // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown');
+ errorhandling_1.logAndExitProcess(error);
+ }
+ else if (!caughtSecondError) {
+ // two cases for how we can hit this branch:
+ // - capturing of first error blew up and we just caught the exception from that
+ // - quit trying to capture, proceed with shutdown
+ // - a second independent error happened while waiting for first error to capture
+ // - want to avoid causing premature shutdown before first error capture finishes
+ // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff
+ // so let's instead just delay a bit before we proceed with our action here
+ // in case 1, we just wait a bit unnecessarily but ultimately do the same thing
+ // in case 2, the delay hopefully made us wait long enough for the capture to finish
+ // two potential nonideal outcomes:
+ // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError
+ // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error
+ // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError)
+ // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish
+ caughtSecondError = true;
+ setTimeout(function () {
+ if (!calledFatalError) {
+ // it was probably case 1, let's treat err as the sendErr and call onFatalError
+ calledFatalError = true;
+ onFatalError(firstError, error);
+ }
+ else {
+ // it was probably case 2, our first error finished capturing while we waited, cool, do nothing
+ }
+ }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc
+ }
+ };
+ };
+ /**
+ * @inheritDoc
+ */
+ OnUncaughtException.id = 'OnUncaughtException';
+ return OnUncaughtException;
+}());
+exports.OnUncaughtException = OnUncaughtException;
+//# sourceMappingURL=onuncaughtexception.js.map
+
+/***/ }),
+
+/***/ 87344:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var errorhandling_1 = __nccwpck_require__(5635);
+/** Global Promise Rejection handler */
+var OnUnhandledRejection = /** @class */ (function () {
+ /**
+ * @inheritDoc
+ */
+ function OnUnhandledRejection(_options) {
+ if (_options === void 0) { _options = { mode: 'warn' }; }
+ this._options = _options;
+ /**
+ * @inheritDoc
+ */
+ this.name = OnUnhandledRejection.id;
+ }
+ /**
+ * @inheritDoc
+ */
+ OnUnhandledRejection.prototype.setupOnce = function () {
+ global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this));
+ };
+ /**
+ * Send an exception with reason
+ * @param reason string
+ * @param promise promise
+ */
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
+ OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) {
+ var hub = core_1.getCurrentHub();
+ if (!hub.getIntegration(OnUnhandledRejection)) {
+ this._handleRejection(reason);
+ return;
+ }
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
+ var context = (promise.domain && promise.domain.sentryContext) || {};
+ hub.withScope(function (scope) {
+ scope.setExtra('unhandledPromiseRejection', true);
+ // Preserve backwards compatibility with raven-node for now
+ if (context.user) {
+ scope.setUser(context.user);
+ }
+ if (context.tags) {
+ scope.setTags(context.tags);
+ }
+ if (context.extra) {
+ scope.setExtras(context.extra);
+ }
+ hub.captureException(reason, {
+ originalException: promise,
+ data: { mechanism: { handled: false, type: 'onunhandledrejection' } },
+ });
+ });
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
+ this._handleRejection(reason);
+ };
+ /**
+ * Handler for `mode` option
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ OnUnhandledRejection.prototype._handleRejection = function (reason) {
+ // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240
+ var rejectionWarning = 'This error originated either by ' +
+ 'throwing inside of an async function without a catch block, ' +
+ 'or by rejecting a promise which was not handled with .catch().' +
+ ' The promise rejected with the reason:';
+ /* eslint-disable no-console */
+ if (this._options.mode === 'warn') {
+ utils_1.consoleSandbox(function () {
+ console.warn(rejectionWarning);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ console.error(reason && reason.stack ? reason.stack : reason);
+ });
+ }
+ else if (this._options.mode === 'strict') {
+ utils_1.consoleSandbox(function () {
+ console.warn(rejectionWarning);
+ });
+ errorhandling_1.logAndExitProcess(reason);
+ }
+ /* eslint-enable no-console */
+ };
+ /**
+ * @inheritDoc
+ */
+ OnUnhandledRejection.id = 'OnUnhandledRejection';
+ return OnUnhandledRejection;
+}());
+exports.OnUnhandledRejection = OnUnhandledRejection;
+//# sourceMappingURL=onunhandledrejection.js.map
+
+/***/ }),
+
+/***/ 5635:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var flags_1 = __nccwpck_require__(71188);
+var DEFAULT_SHUTDOWN_TIMEOUT = 2000;
+/**
+ * @hidden
+ */
+function logAndExitProcess(error) {
+ // eslint-disable-next-line no-console
+ console.error(error && error.stack ? error.stack : error);
+ var client = core_1.getCurrentHub().getClient();
+ if (client === undefined) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('No NodeClient was defined, we are exiting the process now.');
+ global.process.exit(1);
+ }
+ var options = client.getOptions();
+ var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||
+ DEFAULT_SHUTDOWN_TIMEOUT;
+ utils_1.forget(client.close(timeout).then(function (result) {
+ if (!result) {
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');
+ }
+ global.process.exit(1);
+ }));
+}
+exports.logAndExitProcess = logAndExitProcess;
+//# sourceMappingURL=errorhandling.js.map
+
+/***/ }),
+
+/***/ 84103:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var url_1 = __nccwpck_require__(57310);
+var NODE_VERSION = utils_1.parseSemver(process.versions.node);
+/**
+ * Checks whether given url points to Sentry server
+ * @param url url to verify
+ */
+function isSentryRequest(url) {
+ var _a;
+ var dsn = (_a = core_1.getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getDsn();
+ return dsn ? url.includes(dsn.host) : false;
+}
+exports.isSentryRequest = isSentryRequest;
+/**
+ * Assemble a URL to be used for breadcrumbs and spans.
+ *
+ * @param requestOptions RequestOptions object containing the component parts for a URL
+ * @returns Fully-formed URL
+ */
+function extractUrl(requestOptions) {
+ var protocol = requestOptions.protocol || '';
+ var hostname = requestOptions.hostname || requestOptions.host || '';
+ // Don't log standard :80 (http) and :443 (https) ports to reduce the noise
+ var port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : ":" + requestOptions.port;
+ var path = requestOptions.path ? requestOptions.path : '/';
+ return protocol + "//" + hostname + port + path;
+}
+exports.extractUrl = extractUrl;
+/**
+ * Handle various edge cases in the span description (for spans representing http(s) requests).
+ *
+ * @param description current `description` property of the span representing the request
+ * @param requestOptions Configuration data for the request
+ * @param Request Request object
+ *
+ * @returns The cleaned description
+ */
+function cleanSpanDescription(description, requestOptions, request) {
+ var _a, _b, _c;
+ // nothing to clean
+ if (!description) {
+ return description;
+ }
+ // eslint-disable-next-line prefer-const
+ var _d = tslib_1.__read(description.split(' '), 2), method = _d[0], requestUrl = _d[1];
+ // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing,
+ // we're likely dealing with an internal route and this doesn't apply)
+ if (requestOptions.host && !requestOptions.protocol) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
+ requestOptions.protocol = (_b = (_a = request) === null || _a === void 0 ? void 0 : _a.agent) === null || _b === void 0 ? void 0 : _b.protocol; // worst comes to worst, this is undefined and nothing changes
+ requestUrl = extractUrl(requestOptions);
+ }
+ // internal routes can end up starting with a triple slash rather than a single one
+ if ((_c = requestUrl) === null || _c === void 0 ? void 0 : _c.startsWith('///')) {
+ requestUrl = requestUrl.slice(2);
+ }
+ return method + " " + requestUrl;
+}
+exports.cleanSpanDescription = cleanSpanDescription;
+/**
+ * Convert a URL object into a RequestOptions object.
+ *
+ * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the
+ * RequestOptions type above.
+ *
+ * See https://github.com/nodejs/node/blob/master/lib/internal/url.js.
+ */
+function urlToOptions(url) {
+ var options = {
+ protocol: url.protocol,
+ hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,
+ hash: url.hash,
+ search: url.search,
+ pathname: url.pathname,
+ path: "" + (url.pathname || '') + (url.search || ''),
+ href: url.href,
+ };
+ if (url.port !== '') {
+ options.port = Number(url.port);
+ }
+ if (url.username || url.password) {
+ options.auth = url.username + ":" + url.password;
+ }
+ return options;
+}
+exports.urlToOptions = urlToOptions;
+/**
+ * Normalize inputs to `http(s).request()` and `http(s).get()`.
+ *
+ * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms:
+ * [ RequestOptions | string | URL ],
+ * [ RequestOptions | string | URL, RequestCallback ],
+ * [ string | URL, RequestOptions ], and
+ * [ string | URL, RequestOptions, RequestCallback ].
+ *
+ * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is
+ * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact
+ * with the args in a standard way.
+ *
+ * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array.
+ *
+ * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ].
+ */
+function normalizeRequestArgs(httpModule, requestArgs) {
+ var _a, _b, _c, _d, _e, _f, _g, _h;
+ var callback, requestOptions;
+ // pop off the callback, if there is one
+ if (typeof requestArgs[requestArgs.length - 1] === 'function') {
+ callback = requestArgs.pop();
+ }
+ // create a RequestOptions object of whatever's at index 0
+ if (typeof requestArgs[0] === 'string') {
+ requestOptions = urlToOptions(new url_1.URL(requestArgs[0]));
+ }
+ else if (requestArgs[0] instanceof url_1.URL) {
+ requestOptions = urlToOptions(requestArgs[0]);
+ }
+ else {
+ requestOptions = requestArgs[0];
+ }
+ // if the options were given separately from the URL, fold them in
+ if (requestArgs.length === 2) {
+ requestOptions = tslib_1.__assign(tslib_1.__assign({}, requestOptions), requestArgs[1]);
+ }
+ // Figure out the protocol if it's currently missing
+ if (requestOptions.protocol === undefined) {
+ // Worst case we end up populating protocol with undefined, which it already is
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */
+ // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.
+ // Because of that, we cannot rely on `httpModule` to provide us with valid protocol,
+ // as it will always return `http`, even when using `https` module.
+ //
+ // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue.
+ if (NODE_VERSION.major && NODE_VERSION.major > 8) {
+ requestOptions.protocol =
+ ((_b = (_a = httpModule) === null || _a === void 0 ? void 0 : _a.globalAgent) === null || _b === void 0 ? void 0 : _b.protocol) || ((_c = requestOptions.agent) === null || _c === void 0 ? void 0 : _c.protocol) || ((_d = requestOptions._defaultAgent) === null || _d === void 0 ? void 0 : _d.protocol);
+ }
+ else {
+ requestOptions.protocol =
+ ((_e = requestOptions.agent) === null || _e === void 0 ? void 0 : _e.protocol) || ((_f = requestOptions._defaultAgent) === null || _f === void 0 ? void 0 : _f.protocol) || ((_h = (_g = httpModule) === null || _g === void 0 ? void 0 : _g.globalAgent) === null || _h === void 0 ? void 0 : _h.protocol);
+ }
+ /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */
+ }
+ // return args in standardized form
+ if (callback) {
+ return [requestOptions, callback];
+ }
+ else {
+ return [requestOptions];
+ }
+}
+exports.normalizeRequestArgs = normalizeRequestArgs;
+//# sourceMappingURL=http.js.map
+
+/***/ }),
+
+/***/ 38836:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var hub_1 = __nccwpck_require__(6393);
+var utils_1 = __nccwpck_require__(1620);
+var domain = __nccwpck_require__(13639);
+var client_1 = __nccwpck_require__(86147);
+var flags_1 = __nccwpck_require__(71188);
+var integrations_1 = __nccwpck_require__(72310);
+exports.defaultIntegrations = [
+ // Common
+ new core_1.Integrations.InboundFilters(),
+ new core_1.Integrations.FunctionToString(),
+ new integrations_1.ContextLines(),
+ // Native Wrappers
+ new integrations_1.Console(),
+ new integrations_1.Http(),
+ // Global Handlers
+ new integrations_1.OnUncaughtException(),
+ new integrations_1.OnUnhandledRejection(),
+ // Misc
+ new integrations_1.LinkedErrors(),
+];
+/**
+ * The Sentry Node SDK Client.
+ *
+ * To use this SDK, call the {@link init} function as early as possible in the
+ * main entry module. To set context information or send manual events, use the
+ * provided methods.
+ *
+ * @example
+ * ```
+ *
+ * const { init } = require('@sentry/node');
+ *
+ * init({
+ * dsn: '__DSN__',
+ * // ...
+ * });
+ * ```
+ *
+ * @example
+ * ```
+ *
+ * const { configureScope } = require('@sentry/node');
+ * configureScope((scope: Scope) => {
+ * scope.setExtra({ battery: 0.7 });
+ * scope.setTag({ user_mode: 'admin' });
+ * scope.setUser({ id: '4711' });
+ * });
+ * ```
+ *
+ * @example
+ * ```
+ *
+ * const { addBreadcrumb } = require('@sentry/node');
+ * addBreadcrumb({
+ * message: 'My Breadcrumb',
+ * // ...
+ * });
+ * ```
+ *
+ * @example
+ * ```
+ *
+ * const Sentry = require('@sentry/node');
+ * Sentry.captureMessage('Hello, world!');
+ * Sentry.captureException(new Error('Good bye'));
+ * Sentry.captureEvent({
+ * message: 'Manual',
+ * stacktrace: [
+ * // ...
+ * ],
+ * });
+ * ```
+ *
+ * @see {@link NodeOptions} for documentation on configuration options.
+ */
+function init(options) {
+ if (options === void 0) { options = {}; }
+ var _a;
+ var carrier = hub_1.getMainCarrier();
+ var autoloadedIntegrations = ((_a = carrier.__SENTRY__) === null || _a === void 0 ? void 0 : _a.integrations) || [];
+ options.defaultIntegrations =
+ options.defaultIntegrations === false
+ ? []
+ : tslib_1.__spread((Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : exports.defaultIntegrations), autoloadedIntegrations);
+ if (options.dsn === undefined && process.env.SENTRY_DSN) {
+ options.dsn = process.env.SENTRY_DSN;
+ }
+ if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) {
+ var tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE);
+ if (isFinite(tracesSampleRate)) {
+ options.tracesSampleRate = tracesSampleRate;
+ }
+ }
+ if (options.release === undefined) {
+ var detectedRelease = getSentryRelease();
+ if (detectedRelease !== undefined) {
+ options.release = detectedRelease;
+ }
+ else {
+ // If release is not provided, then we should disable autoSessionTracking
+ options.autoSessionTracking = false;
+ }
+ }
+ if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) {
+ options.environment = process.env.SENTRY_ENVIRONMENT;
+ }
+ if (options.autoSessionTracking === undefined && options.dsn !== undefined) {
+ options.autoSessionTracking = true;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
+ if (domain.active) {
+ hub_1.setHubOnCarrier(carrier, core_1.getCurrentHub());
+ }
+ core_1.initAndBind(client_1.NodeClient, options);
+ if (options.autoSessionTracking) {
+ startSessionTracking();
+ }
+}
+exports.init = init;
+/**
+ * This is the getter for lastEventId.
+ *
+ * @returns The last event id of a captured event.
+ */
+function lastEventId() {
+ return core_1.getCurrentHub().lastEventId();
+}
+exports.lastEventId = lastEventId;
+/**
+ * Call `flush()` on the current client, if there is one. See {@link Client.flush}.
+ *
+ * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
+ * the client to wait until all events are sent before resolving the promise.
+ * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
+ * doesn't (or if there's no client defined).
+ */
+function flush(timeout) {
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var client;
+ return tslib_1.__generator(this, function (_a) {
+ client = core_1.getCurrentHub().getClient();
+ if (client) {
+ return [2 /*return*/, client.flush(timeout)];
+ }
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('Cannot flush events. No client defined.');
+ return [2 /*return*/, Promise.resolve(false)];
+ });
+ });
+}
+exports.flush = flush;
+/**
+ * Call `close()` on the current client, if there is one. See {@link Client.close}.
+ *
+ * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
+ * parameter will cause the client to wait until all events are sent before disabling itself.
+ * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
+ * doesn't (or if there's no client defined).
+ */
+function close(timeout) {
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var client;
+ return tslib_1.__generator(this, function (_a) {
+ client = core_1.getCurrentHub().getClient();
+ if (client) {
+ return [2 /*return*/, client.close(timeout)];
+ }
+ flags_1.IS_DEBUG_BUILD && utils_1.logger.warn('Cannot flush events and disable SDK. No client defined.');
+ return [2 /*return*/, Promise.resolve(false)];
+ });
+ });
+}
+exports.close = close;
+/**
+ * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client
+ */
+function isAutoSessionTrackingEnabled(client) {
+ if (client === undefined) {
+ return false;
+ }
+ var clientOptions = client && client.getOptions();
+ if (clientOptions && clientOptions.autoSessionTracking !== undefined) {
+ return clientOptions.autoSessionTracking;
+ }
+ return false;
+}
+exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled;
+/**
+ * Returns a release dynamically from environment variables.
+ */
+function getSentryRelease(fallback) {
+ // Always read first as Sentry takes this as precedence
+ if (process.env.SENTRY_RELEASE) {
+ return process.env.SENTRY_RELEASE;
+ }
+ // This supports the variable that sentry-webpack-plugin injects
+ var global = utils_1.getGlobalObject();
+ if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) {
+ return global.SENTRY_RELEASE.id;
+ }
+ return (
+ // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables
+ process.env.GITHUB_SHA ||
+ // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata
+ process.env.COMMIT_REF ||
+ // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables
+ process.env.VERCEL_GIT_COMMIT_SHA ||
+ process.env.VERCEL_GITHUB_COMMIT_SHA ||
+ process.env.VERCEL_GITLAB_COMMIT_SHA ||
+ process.env.VERCEL_BITBUCKET_COMMIT_SHA ||
+ // Zeit (now known as Vercel)
+ process.env.ZEIT_GITHUB_COMMIT_SHA ||
+ process.env.ZEIT_GITLAB_COMMIT_SHA ||
+ process.env.ZEIT_BITBUCKET_COMMIT_SHA ||
+ fallback);
+}
+exports.getSentryRelease = getSentryRelease;
+/**
+ * Enable automatic Session Tracking for the node process.
+ */
+function startSessionTracking() {
+ var hub = core_1.getCurrentHub();
+ hub.startSession();
+ // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because
+ // The 'beforeExit' event is not emitted for conditions causing explicit termination,
+ // such as calling process.exit() or uncaught exceptions.
+ // Ref: https://nodejs.org/api/process.html#process_event_beforeexit
+ process.on('beforeExit', function () {
+ var _a;
+ var session = (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.getSession();
+ var terminalStates = ['exited', 'crashed'];
+ // Only call endSession, if the Session exists on Scope and SessionStatus is not a
+ // Terminal Status i.e. Exited or Crashed because
+ // "When a session is moved away from ok it must not be updated anymore."
+ // Ref: https://develop.sentry.dev/sdk/sessions/
+ if (session && !terminalStates.includes(session.status))
+ hub.endSession();
+ });
+}
+//# sourceMappingURL=sdk.js.map
+
+/***/ }),
+
+/***/ 94854:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var utils_1 = __nccwpck_require__(1620);
+/** Gets the module */
+function getModule(filename) {
+ if (!filename) {
+ return;
+ }
+ // We could use optional chaining here but webpack does like that mixed with require
+ var base = ((require && require.main && require.main.filename && utils_1.dirname(require.main.filename)) || global.process.cwd()) + "/";
+ // It's specifically a module
+ var file = utils_1.basename(filename, '.js');
+ var path = utils_1.dirname(filename);
+ var n = path.lastIndexOf('/node_modules/');
+ if (n > -1) {
+ // /node_modules/ is 14 chars
+ return path.substr(n + 14).replace(/\//g, '.') + ":" + file;
+ }
+ // Let's see if it's a part of the main module
+ // To be a part of main module, it has to share the same base
+ n = (path + "/").lastIndexOf(base, 0);
+ if (n === 0) {
+ var moduleName = path.substr(base.length).replace(/\//g, '.');
+ if (moduleName) {
+ moduleName += ':';
+ }
+ moduleName += file;
+ return moduleName;
+ }
+ return file;
+}
+var FILENAME_MATCH = /^\s*[-]{4,}$/;
+var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/;
+// eslint-disable-next-line complexity
+var node = function (line) {
+ var _a;
+ if (line.match(FILENAME_MATCH)) {
+ return {
+ filename: line,
+ };
+ }
+ var lineMatch = line.match(FULL_MATCH);
+ if (!lineMatch) {
+ return undefined;
+ }
+ var object;
+ var method;
+ var functionName;
+ var typeName;
+ var methodName;
+ if (lineMatch[1]) {
+ functionName = lineMatch[1];
+ var methodStart = functionName.lastIndexOf('.');
+ if (functionName[methodStart - 1] === '.') {
+ // eslint-disable-next-line no-plusplus
+ 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 = undefined;
+ }
+ if (method) {
+ typeName = object;
+ methodName = method;
+ }
+ if (method === '') {
+ methodName = undefined;
+ functionName = undefined;
+ }
+ if (functionName === undefined) {
+ methodName = methodName || '';
+ functionName = typeName ? typeName + "." + methodName : methodName;
+ }
+ var filename = ((_a = lineMatch[2]) === null || _a === void 0 ? void 0 : _a.startsWith('file://')) ? lineMatch[2].substr(7) : lineMatch[2];
+ var isNative = lineMatch[5] === 'native';
+ var isInternal = isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1);
+ // in_app is all that's not an internal Node function or a module within node_modules
+ // note that isNative appears to return true even for node core libraries
+ // see https://github.com/getsentry/raven-node/issues/176
+ var in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/');
+ return {
+ filename: filename,
+ module: getModule(filename),
+ function: functionName,
+ lineno: parseInt(lineMatch[3], 10) || undefined,
+ colno: parseInt(lineMatch[4], 10) || undefined,
+ in_app: in_app,
+ };
+};
+exports.nodeStackParser = [90, node];
+//# sourceMappingURL=stack-parser.js.map
+
+/***/ }),
+
+/***/ 41194:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var fs = __nccwpck_require__(57147);
+var url_1 = __nccwpck_require__(57310);
+var flags_1 = __nccwpck_require__(71188);
+var version_1 = __nccwpck_require__(31271);
+var CATEGORY_MAPPING = {
+ event: 'error',
+ transaction: 'transaction',
+ session: 'session',
+ attachment: 'attachment',
+};
+/** Base Transport class implementation */
+var BaseTransport = /** @class */ (function () {
+ /** Create instance and set this.dsn */
+ function BaseTransport(options) {
+ this.options = options;
+ /** A simple buffer holding all requests. */
+ this._buffer = utils_1.makePromiseBuffer(30);
+ /** Locks transport after receiving rate limits in a response */
+ this._rateLimits = {};
+ /** Default function used to parse URLs */
+ this.urlParser = function (url) { return new url_1.URL(url); };
+ // eslint-disable-next-line deprecation/deprecation
+ this._api = core_1.initAPIDetails(options.dsn, options._metadata, options.tunnel);
+ }
+ /**
+ * @inheritDoc
+ */
+ BaseTransport.prototype.sendEvent = function (_) {
+ throw new utils_1.SentryError('Transport Class has to implement `sendEvent` method.');
+ };
+ /**
+ * @inheritDoc
+ */
+ BaseTransport.prototype.close = function (timeout) {
+ return this._buffer.drain(timeout);
+ };
+ /**
+ * Extracts proxy settings from client options and env variables.
+ *
+ * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion.
+ *
+ * An order of priority for available protocols is:
+ * `http` => `options.httpProxy` | `process.env.http_proxy`
+ * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy`
+ */
+ BaseTransport.prototype._getProxy = function (protocol) {
+ var e_1, _a;
+ var _b = process.env, no_proxy = _b.no_proxy, http_proxy = _b.http_proxy, https_proxy = _b.https_proxy;
+ var _c = this.options, httpProxy = _c.httpProxy, httpsProxy = _c.httpsProxy;
+ var proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy;
+ if (!no_proxy) {
+ return proxy;
+ }
+ var _d = this._api.dsn, host = _d.host, port = _d.port;
+ try {
+ for (var _e = tslib_1.__values(no_proxy.split(',')), _f = _e.next(); !_f.done; _f = _e.next()) {
+ var np = _f.value;
+ if (host.endsWith(np) || (host + ":" + port).endsWith(np)) {
+ return;
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ return proxy;
+ };
+ /** Returns a build request option object used by request */
+ BaseTransport.prototype._getRequestOptions = function (urlParts) {
+ var headers = tslib_1.__assign(tslib_1.__assign({}, core_1.getRequestHeaders(this._api.dsn, version_1.SDK_NAME, core_1.SDK_VERSION)), this.options.headers);
+ var hostname = urlParts.hostname, pathname = urlParts.pathname, port = urlParts.port, protocol = urlParts.protocol;
+ // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290
+ // We ignore the query string on purpose
+ var path = "" + pathname;
+ return tslib_1.__assign({ agent: this.client, headers: headers,
+ hostname: hostname, method: 'POST', path: path,
+ port: port,
+ protocol: protocol }, (this.options.caCerts && {
+ ca: fs.readFileSync(this.options.caCerts),
+ }));
+ };
+ /**
+ * Gets the time that given category is disabled until for rate limiting
+ */
+ BaseTransport.prototype._disabledUntil = function (requestType) {
+ var category = CATEGORY_MAPPING[requestType];
+ return this._rateLimits[category] || this._rateLimits.all;
+ };
+ /**
+ * Checks if a category is rate limited
+ */
+ BaseTransport.prototype._isRateLimited = function (requestType) {
+ return this._disabledUntil(requestType) > new Date(Date.now());
+ };
+ /**
+ * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header.
+ */
+ BaseTransport.prototype._handleRateLimit = function (headers) {
+ var e_2, _a, e_3, _b;
+ var now = Date.now();
+ var rlHeader = headers['x-sentry-rate-limits'];
+ var raHeader = headers['retry-after'];
+ if (rlHeader) {
+ try {
+ // rate limit headers are of the form
+ // ,,..
+ // where each is of the form
+ // : : :
+ // where
+ // is a delay in ms
+ // is the event type(s) (error, transaction, etc) being rate limited and is of the form
+ // ;;...
+ // is what's being limited (org, project, or key) - ignored by SDK
+ // is an arbitrary string like "org_quota" - ignored by SDK
+ for (var _c = tslib_1.__values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) {
+ var limit = _d.value;
+ var parameters = limit.split(':', 2);
+ var headerDelay = parseInt(parameters[0], 10);
+ var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default
+ try {
+ for (var _e = (e_3 = void 0, tslib_1.__values((parameters[1] && parameters[1].split(';')) || ['all'])), _f = _e.next(); !_f.done; _f = _e.next()) {
+ var category = _f.value;
+ // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this
+ // sdk and any categories that are not supported will not be added redundantly to the rateLimits object
+ var categoriesAllowed = tslib_1.__spread(Object.keys(CATEGORY_MAPPING).map(function (k) { return CATEGORY_MAPPING[k]; }), [
+ 'all',
+ ]);
+ if (categoriesAllowed.includes(category))
+ this._rateLimits[category] = new Date(now + delay);
+ }
+ }
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
+ finally {
+ try {
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
+ }
+ finally { if (e_3) throw e_3.error; }
+ }
+ }
+ }
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
+ }
+ finally { if (e_2) throw e_2.error; }
+ }
+ return true;
+ }
+ else if (raHeader) {
+ this._rateLimits.all = new Date(now + utils_1.parseRetryAfterHeader(raHeader, now));
+ return true;
+ }
+ return false;
+ };
+ /** JSDoc */
+ BaseTransport.prototype._send = function (sentryRequest, originalPayload) {
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
+ var _this = this;
+ return tslib_1.__generator(this, function (_a) {
+ if (!this.module) {
+ throw new utils_1.SentryError('No module available');
+ }
+ if (originalPayload && this._isRateLimited(sentryRequest.type)) {
+ return [2 /*return*/, Promise.reject({
+ payload: originalPayload,
+ type: sentryRequest.type,
+ reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.",
+ status: 429,
+ })];
+ }
+ return [2 /*return*/, this._buffer.add(function () {
+ return new Promise(function (resolve, reject) {
+ if (!_this.module) {
+ throw new utils_1.SentryError('No module available');
+ }
+ var options = _this._getRequestOptions(_this.urlParser(sentryRequest.url));
+ var req = _this.module.request(options, function (res) {
+ var statusCode = res.statusCode || 500;
+ var status = utils_1.eventStatusFromHttpCode(statusCode);
+ res.setEncoding('utf8');
+ /**
+ * "Key-value pairs of header names and values. Header names are lower-cased."
+ * https://nodejs.org/api/http.html#http_message_headers
+ */
+ var retryAfterHeader = res.headers ? res.headers['retry-after'] : '';
+ retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader);
+ var rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : '';
+ rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader);
+ var headers = {
+ 'x-sentry-rate-limits': rlHeader,
+ 'retry-after': retryAfterHeader,
+ };
+ var limited = _this._handleRateLimit(headers);
+ if (limited)
+ flags_1.IS_DEBUG_BUILD &&
+ utils_1.logger.warn("Too many " + sentryRequest.type + " requests, backing off until: " + _this._disabledUntil(sentryRequest.type));
+ if (status === 'success') {
+ resolve({ status: status });
+ }
+ else {
+ var rejectionMessage = "HTTP Error (" + statusCode + ")";
+ if (res.headers && res.headers['x-sentry-error']) {
+ rejectionMessage += ": " + res.headers['x-sentry-error'];
+ }
+ reject(new utils_1.SentryError(rejectionMessage));
+ }
+ // Force the socket to drain
+ res.on('data', function () {
+ // Drain
+ });
+ res.on('end', function () {
+ // Drain
+ });
+ });
+ req.on('error', reject);
+ req.end(sentryRequest.body);
+ });
+ })];
+ });
+ });
+ };
+ return BaseTransport;
+}());
+exports.BaseTransport = BaseTransport;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 84490:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var http = __nccwpck_require__(13685);
+var base_1 = __nccwpck_require__(41194);
+/** Node http module transport */
+var HTTPTransport = /** @class */ (function (_super) {
+ tslib_1.__extends(HTTPTransport, _super);
+ /** Create a new instance and set this.agent */
+ function HTTPTransport(options) {
+ var _this = _super.call(this, options) || this;
+ _this.options = options;
+ var proxy = _this._getProxy('http');
+ _this.module = http;
+ _this.client = proxy
+ ? new (__nccwpck_require__(77219))(proxy)
+ : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });
+ return _this;
+ }
+ /**
+ * @inheritDoc
+ */
+ HTTPTransport.prototype.sendEvent = function (event) {
+ return this._send(core_1.eventToSentryRequest(event, this._api), event);
+ };
+ /**
+ * @inheritDoc
+ */
+ HTTPTransport.prototype.sendSession = function (session) {
+ return this._send(core_1.sessionToSentryRequest(session, this._api), session);
+ };
+ return HTTPTransport;
+}(base_1.BaseTransport));
+exports.HTTPTransport = HTTPTransport;
+//# sourceMappingURL=http.js.map
+
+/***/ }),
+
+/***/ 68621:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var core_1 = __nccwpck_require__(79212);
+var https = __nccwpck_require__(95687);
+var base_1 = __nccwpck_require__(41194);
+/** Node https module transport */
+var HTTPSTransport = /** @class */ (function (_super) {
+ tslib_1.__extends(HTTPSTransport, _super);
+ /** Create a new instance and set this.agent */
+ function HTTPSTransport(options) {
+ var _this = _super.call(this, options) || this;
+ _this.options = options;
+ var proxy = _this._getProxy('https');
+ _this.module = https;
+ _this.client = proxy
+ ? new (__nccwpck_require__(77219))(proxy)
+ : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });
+ return _this;
+ }
+ /**
+ * @inheritDoc
+ */
+ HTTPSTransport.prototype.sendEvent = function (event) {
+ return this._send(core_1.eventToSentryRequest(event, this._api), event);
+ };
+ /**
+ * @inheritDoc
+ */
+ HTTPSTransport.prototype.sendSession = function (session) {
+ return this._send(core_1.sessionToSentryRequest(session, this._api), session);
+ };
+ return HTTPSTransport;
+}(base_1.BaseTransport));
+exports.HTTPSTransport = HTTPSTransport;
+//# sourceMappingURL=https.js.map
+
+/***/ }),
+
+/***/ 21437:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var base_1 = __nccwpck_require__(41194);
+exports.BaseTransport = base_1.BaseTransport;
+var http_1 = __nccwpck_require__(84490);
+exports.HTTPTransport = http_1.HTTPTransport;
+var https_1 = __nccwpck_require__(68621);
+exports.HTTPSTransport = https_1.HTTPSTransport;
+var new_1 = __nccwpck_require__(72208);
+exports.makeNodeTransport = new_1.makeNodeTransport;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 72208:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var core_1 = __nccwpck_require__(79212);
+var utils_1 = __nccwpck_require__(1620);
+var http = __nccwpck_require__(13685);
+var https = __nccwpck_require__(95687);
+var url_1 = __nccwpck_require__(57310);
+/**
+ * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry.
+ */
+function makeNodeTransport(options) {
+ var _a;
+ var urlSegments = new url_1.URL(options.url);
+ var isHttps = urlSegments.protocol === 'https:';
+ // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy`
+ // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy`
+ var proxy = applyNoProxyOption(urlSegments, options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy);
+ var nativeHttpModule = isHttps ? https : http;
+ // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node
+ // versions(>= 8) as they had memory leaks when using it: #2555
+ var agent = proxy
+ ? new (__nccwpck_require__(77219))(proxy)
+ : new nativeHttpModule.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });
+ var requestExecutor = createRequestExecutor(options, (_a = options.httpModule, (_a !== null && _a !== void 0 ? _a : nativeHttpModule)), agent);
+ return core_1.createTransport({ bufferSize: options.bufferSize }, requestExecutor);
+}
+exports.makeNodeTransport = makeNodeTransport;
+/**
+ * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion.
+ *
+ * @param transportUrl The URL the transport intends to send events to.
+ * @param proxy The client configured proxy.
+ * @returns A proxy the transport should use.
+ */
+function applyNoProxyOption(transportUrlSegments, proxy) {
+ var no_proxy = process.env.no_proxy;
+ var urlIsExemptFromProxy = no_proxy &&
+ no_proxy
+ .split(',')
+ .some(function (exemption) { return transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption); });
+ if (urlIsExemptFromProxy) {
+ return undefined;
+ }
+ else {
+ return proxy;
+ }
+}
+/**
+ * Creates a RequestExecutor to be used with `createTransport`.
+ */
+function createRequestExecutor(options, httpModule, agent) {
+ var _a = new url_1.URL(options.url), hostname = _a.hostname, pathname = _a.pathname, port = _a.port, protocol = _a.protocol, search = _a.search;
+ return function makeRequest(request) {
+ return new Promise(function (resolve, reject) {
+ var req = httpModule.request({
+ method: 'POST',
+ agent: agent,
+ headers: options.headers,
+ hostname: hostname,
+ path: "" + pathname + search,
+ port: port,
+ protocol: protocol,
+ ca: options.caCerts,
+ }, function (res) {
+ var _a, _b, _c;
+ res.on('data', function () {
+ // Drain socket
+ });
+ res.on('end', function () {
+ // Drain socket
+ });
+ var statusCode = (_a = res.statusCode, (_a !== null && _a !== void 0 ? _a : 500));
+ var status = utils_1.eventStatusFromHttpCode(statusCode);
+ res.setEncoding('utf8');
+ // "Key-value pairs of header names and values. Header names are lower-cased."
+ // https://nodejs.org/api/http.html#http_message_headers
+ var retryAfterHeader = (_b = res.headers['retry-after'], (_b !== null && _b !== void 0 ? _b : null));
+ var rateLimitsHeader = (_c = res.headers['x-sentry-rate-limits'], (_c !== null && _c !== void 0 ? _c : null));
+ resolve({
+ headers: {
+ 'retry-after': retryAfterHeader,
+ 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader,
+ },
+ reason: status,
+ statusCode: statusCode,
+ });
+ });
+ req.on('error', reject);
+ req.end(request.body);
+ });
+ };
+}
+//# sourceMappingURL=new.js.map
+
+/***/ }),
+
+/***/ 27937:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var fs = __nccwpck_require__(57147);
+var path = __nccwpck_require__(71017);
+/**
+ * Recursively read the contents of a directory.
+ *
+ * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this
+ * directory.
+ * @returns Array holding all relative paths
+ */
+function deepReadDirSync(targetDir) {
+ var targetDirAbsPath = path.resolve(targetDir);
+ if (!fs.existsSync(targetDirAbsPath)) {
+ throw new Error("Cannot read contents of " + targetDirAbsPath + ". Directory does not exist.");
+ }
+ if (!fs.statSync(targetDirAbsPath).isDirectory()) {
+ throw new Error("Cannot read contents of " + targetDirAbsPath + ", because it is not a directory.");
+ }
+ // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it
+ // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve
+ // the difference between `targetDirAbsPath` and `currentDirAbsPath`.
+ var deepReadCurrentDir = function (currentDirAbsPath) {
+ return fs.readdirSync(currentDirAbsPath).reduce(function (absPaths, itemName) {
+ var itemAbsPath = path.join(currentDirAbsPath, itemName);
+ if (fs.statSync(itemAbsPath).isDirectory()) {
+ return tslib_1.__spread(absPaths, deepReadCurrentDir(itemAbsPath));
+ }
+ return tslib_1.__spread(absPaths, [itemAbsPath]);
+ }, []);
+ };
+ return deepReadCurrentDir(targetDirAbsPath).map(function (absPath) { return path.relative(targetDirAbsPath, absPath); });
+}
+exports.deepReadDirSync = deepReadDirSync;
+//# sourceMappingURL=utils.js.map
+
+/***/ }),
+
+/***/ 31271:
+/***/ ((__unused_webpack_module, exports) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata
+exports.SDK_NAME = 'sentry.javascript.node';
+//# sourceMappingURL=version.js.map
+
+/***/ }),
+
+/***/ 11668:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+/*!
+ * cookie
+ * Copyright(c) 2012-2014 Roman Shtylman
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+
+
+/**
+ * Module exports.
+ * @public
+ */
+
+exports.parse = parse;
+exports.serialize = serialize;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var decode = decodeURIComponent;
+var encode = encodeURIComponent;
+
+/**
+ * RegExp to match field-content in RFC 7230 sec 3.2
+ *
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+ * field-vchar = VCHAR / obs-text
+ * obs-text = %x80-FF
+ */
+
+var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
+
+/**
+ * Parse a cookie header.
+ *
+ * Parse the given cookie header string into an object
+ * The object has the various cookies as keys(names) => values
+ *
+ * @param {string} str
+ * @param {object} [options]
+ * @return {object}
+ * @public
+ */
+
+function parse(str, options) {
+ if (typeof str !== 'string') {
+ throw new TypeError('argument str must be a string');
+ }
+
+ var obj = {}
+ var opt = options || {};
+ var pairs = str.split(';')
+ var dec = opt.decode || decode;
+
+ for (var i = 0; i < pairs.length; i++) {
+ var pair = pairs[i];
+ var index = pair.indexOf('=')
+
+ // skip things that don't look like key=value
+ if (index < 0) {
+ continue;
+ }
+
+ var key = pair.substring(0, index).trim()
+
+ // only assign once
+ if (undefined == obj[key]) {
+ var val = pair.substring(index + 1, pair.length).trim()
+
+ // quoted values
+ if (val[0] === '"') {
+ val = val.slice(1, -1)
+ }
+
+ obj[key] = tryDecode(val, dec);
+ }
+ }
+
+ return obj;
+}
+
+/**
+ * Serialize data into a cookie header.
+ *
+ * Serialize the a name value pair into a cookie string suitable for
+ * http headers. An optional options object specified cookie parameters.
+ *
+ * serialize('foo', 'bar', { httpOnly: true })
+ * => "foo=bar; httpOnly"
+ *
+ * @param {string} name
+ * @param {string} val
+ * @param {object} [options]
+ * @return {string}
+ * @public
+ */
+
+function serialize(name, val, options) {
+ var opt = options || {};
+ var enc = opt.encode || encode;
+
+ if (typeof enc !== 'function') {
+ throw new TypeError('option encode is invalid');
+ }
+
+ if (!fieldContentRegExp.test(name)) {
+ throw new TypeError('argument name is invalid');
+ }
+
+ var value = enc(val);
+
+ if (value && !fieldContentRegExp.test(value)) {
+ throw new TypeError('argument val is invalid');
+ }
+
+ var str = name + '=' + value;
+
+ if (null != opt.maxAge) {
+ var maxAge = opt.maxAge - 0;
+
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
+ throw new TypeError('option maxAge is invalid')
+ }
+
+ str += '; Max-Age=' + Math.floor(maxAge);
+ }
+
+ if (opt.domain) {
+ if (!fieldContentRegExp.test(opt.domain)) {
+ throw new TypeError('option domain is invalid');
+ }
+
+ str += '; Domain=' + opt.domain;
+ }
+
+ if (opt.path) {
+ if (!fieldContentRegExp.test(opt.path)) {
+ throw new TypeError('option path is invalid');
+ }
+
+ str += '; Path=' + opt.path;
+ }
+
+ if (opt.expires) {
+ if (typeof opt.expires.toUTCString !== 'function') {
+ throw new TypeError('option expires is invalid');
+ }
+
+ str += '; Expires=' + opt.expires.toUTCString();
+ }
+
+ if (opt.httpOnly) {
+ str += '; HttpOnly';
+ }
+
+ if (opt.secure) {
+ str += '; Secure';
+ }
+
+ if (opt.sameSite) {
+ var sameSite = typeof opt.sameSite === 'string'
+ ? opt.sameSite.toLowerCase() : opt.sameSite;
+
+ switch (sameSite) {
+ case true:
+ str += '; SameSite=Strict';
+ break;
+ case 'lax':
+ str += '; SameSite=Lax';
+ break;
+ case 'strict':
+ str += '; SameSite=Strict';
+ break;
+ case 'none':
+ str += '; SameSite=None';
+ break;
+ default:
+ throw new TypeError('option sameSite is invalid');
+ }
+ }
+
+ return str;
+}
+
+/**
+ * Try decoding a string using a decoding function.
+ *
+ * @param {string} str
+ * @param {function} decode
+ * @private
+ */
+
+function tryDecode(str, decode) {
+ try {
+ return decode(str);
+ } catch (e) {
+ return str;
+ }
+}
+
+
+/***/ }),
+
+/***/ 83789:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var severity_1 = __nccwpck_require__(94124);
+exports.Severity = severity_1.Severity;
+var severity_2 = __nccwpck_require__(94124);
+exports.SeverityLevels = severity_2.SeverityLevels;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 94124:
+/***/ ((__unused_webpack_module, exports) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/**
+ * TODO(v7): Remove this enum and replace with SeverityLevel
+ */
+var Severity;
+(function (Severity) {
+ /** JSDoc */
+ Severity["Fatal"] = "fatal";
+ /** JSDoc */
+ Severity["Error"] = "error";
+ /** JSDoc */
+ Severity["Warning"] = "warning";
+ /** JSDoc */
+ Severity["Log"] = "log";
+ /** JSDoc */
+ Severity["Info"] = "info";
+ /** JSDoc */
+ Severity["Debug"] = "debug";
+ /** JSDoc */
+ Severity["Critical"] = "critical";
+})(Severity = exports.Severity || (exports.Severity = {}));
+// TODO: in v7, these can disappear, because they now also exist in `@sentry/utils`. (Having them there rather than here
+// is nice because then it enforces the idea that only types are exported from `@sentry/types`.)
+exports.SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'];
+//# sourceMappingURL=severity.js.map
+
+/***/ }),
+
+/***/ 58343:
+/***/ ((__unused_webpack_module, exports) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/**
+ * Consumes the promise and logs the error when it rejects.
+ * @param promise A promise to forget.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function forget(promise) {
+ void promise.then(null, function (e) {
+ // TODO: Use a better logging mechanism
+ // eslint-disable-next-line no-console
+ console.error(e);
+ });
+}
+exports.forget = forget;
+//# sourceMappingURL=async.js.map
+
+/***/ }),
+
+/***/ 30597:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var global_1 = __nccwpck_require__(68813);
+var is_1 = __nccwpck_require__(92757);
+/**
+ * Given a child DOM element, returns a query-selector statement describing that
+ * and its ancestors
+ * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
+ * @returns generated DOM path
+ */
+function htmlTreeAsString(elem, keyAttrs) {
+ // try/catch both:
+ // - accessing event.target (see getsentry/raven-js#838, #768)
+ // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
+ // - can throw an exception in some circumstances.
+ try {
+ var currentElem = elem;
+ var MAX_TRAVERSE_HEIGHT = 5;
+ var MAX_OUTPUT_LEN = 80;
+ var out = [];
+ var height = 0;
+ var len = 0;
+ var separator = ' > ';
+ var sepLength = separator.length;
+ var nextStr = void 0;
+ // eslint-disable-next-line no-plusplus
+ while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
+ nextStr = _htmlElementAsString(currentElem, keyAttrs);
+ // bail out if
+ // - nextStr is the 'html' element
+ // - the length of the string that would be created exceeds MAX_OUTPUT_LEN
+ // (ignore this limit if we are on the first iteration)
+ if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {
+ break;
+ }
+ out.push(nextStr);
+ len += nextStr.length;
+ currentElem = currentElem.parentNode;
+ }
+ return out.reverse().join(separator);
+ }
+ catch (_oO) {
+ return '';
+ }
+}
+exports.htmlTreeAsString = htmlTreeAsString;
+/**
+ * Returns a simple, query-selector representation of a DOM element
+ * e.g. [HTMLElement] => input#foo.btn[name=baz]
+ * @returns generated DOM path
+ */
+function _htmlElementAsString(el, keyAttrs) {
+ var elem = el;
+ var out = [];
+ var className;
+ var classes;
+ var key;
+ var attr;
+ var i;
+ if (!elem || !elem.tagName) {
+ return '';
+ }
+ out.push(elem.tagName.toLowerCase());
+ // Pairs of attribute keys defined in `serializeAttribute` and their values on element.
+ var keyAttrPairs = keyAttrs && keyAttrs.length
+ ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; })
+ : null;
+ if (keyAttrPairs && keyAttrPairs.length) {
+ keyAttrPairs.forEach(function (keyAttrPair) {
+ out.push("[" + keyAttrPair[0] + "=\"" + keyAttrPair[1] + "\"]");
+ });
+ }
+ else {
+ if (elem.id) {
+ out.push("#" + elem.id);
+ }
+ // eslint-disable-next-line prefer-const
+ className = elem.className;
+ if (className && is_1.isString(className)) {
+ classes = className.split(/\s+/);
+ for (i = 0; i < classes.length; i++) {
+ out.push("." + classes[i]);
+ }
+ }
+ }
+ var allowedAttrs = ['type', 'name', 'title', 'alt'];
+ for (i = 0; i < allowedAttrs.length; i++) {
+ key = allowedAttrs[i];
+ attr = elem.getAttribute(key);
+ if (attr) {
+ out.push("[" + key + "=\"" + attr + "\"]");
+ }
+ }
+ return out.join('');
+}
+/**
+ * A safe form of location.href
+ */
+function getLocationHref() {
+ var global = global_1.getGlobalObject();
+ try {
+ return global.document.location.href;
+ }
+ catch (oO) {
+ return '';
+ }
+}
+exports.getLocationHref = getLocationHref;
+//# sourceMappingURL=browser.js.map
+
+/***/ }),
+
+/***/ 38857:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var envelope_1 = __nccwpck_require__(6222);
+var time_1 = __nccwpck_require__(1735);
+/**
+ * Creates client report envelope
+ * @param discarded_events An array of discard events
+ * @param dsn A DSN that can be set on the header. Optional.
+ */
+function createClientReportEnvelope(discarded_events, dsn, timestamp) {
+ var clientReportItem = [
+ { type: 'client_report' },
+ {
+ timestamp: timestamp || time_1.dateTimestampInSeconds(),
+ discarded_events: discarded_events,
+ },
+ ];
+ return envelope_1.createEnvelope(dsn ? { dsn: dsn } : {}, [clientReportItem]);
+}
+exports.createClientReportEnvelope = createClientReportEnvelope;
+//# sourceMappingURL=clientreport.js.map
+
+/***/ }),
+
+/***/ 3275:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var error_1 = __nccwpck_require__(66238);
+var flags_1 = __nccwpck_require__(23710);
+/** Regular expression used to parse a Dsn. */
+var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;
+function isValidProtocol(protocol) {
+ return protocol === 'http' || protocol === 'https';
+}
+/**
+ * Renders the string representation of this Dsn.
+ *
+ * By default, this will render the public representation without the password
+ * component. To get the deprecated private representation, set `withPassword`
+ * to true.
+ *
+ * @param withPassword When set to true, the password will be included.
+ */
+function dsnToString(dsn, withPassword) {
+ if (withPassword === void 0) { withPassword = false; }
+ var host = dsn.host, path = dsn.path, pass = dsn.pass, port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
+ return (protocol + "://" + publicKey + (withPassword && pass ? ":" + pass : '') +
+ ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId));
+}
+exports.dsnToString = dsnToString;
+function dsnFromString(str) {
+ var match = DSN_REGEX.exec(str);
+ if (!match) {
+ throw new error_1.SentryError("Invalid Sentry Dsn: " + str);
+ }
+ var _a = tslib_1.__read(match.slice(1), 6), protocol = _a[0], publicKey = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5];
+ var path = '';
+ var projectId = lastPath;
+ var split = projectId.split('/');
+ if (split.length > 1) {
+ path = split.slice(0, -1).join('/');
+ projectId = split.pop();
+ }
+ if (projectId) {
+ var projectMatch = projectId.match(/^\d+/);
+ if (projectMatch) {
+ projectId = projectMatch[0];
+ }
+ }
+ return dsnFromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, publicKey: publicKey });
+}
+function dsnFromComponents(components) {
+ // TODO this is for backwards compatibility, and can be removed in a future version
+ if ('user' in components && !('publicKey' in components)) {
+ components.publicKey = components.user;
+ }
+ return {
+ user: components.publicKey || '',
+ protocol: components.protocol,
+ publicKey: components.publicKey || '',
+ pass: components.pass || '',
+ host: components.host,
+ port: components.port || '',
+ path: components.path || '',
+ projectId: components.projectId,
+ };
+}
+function validateDsn(dsn) {
+ if (!flags_1.IS_DEBUG_BUILD) {
+ return;
+ }
+ var port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol;
+ var requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];
+ requiredComponents.forEach(function (component) {
+ if (!dsn[component]) {
+ throw new error_1.SentryError("Invalid Sentry Dsn: " + component + " missing");
+ }
+ });
+ if (!projectId.match(/^\d+$/)) {
+ throw new error_1.SentryError("Invalid Sentry Dsn: Invalid projectId " + projectId);
+ }
+ if (!isValidProtocol(protocol)) {
+ throw new error_1.SentryError("Invalid Sentry Dsn: Invalid protocol " + protocol);
+ }
+ if (port && isNaN(parseInt(port, 10))) {
+ throw new error_1.SentryError("Invalid Sentry Dsn: Invalid port " + port);
+ }
+ return true;
+}
+/** The Sentry Dsn, identifying a Sentry instance and project. */
+function makeDsn(from) {
+ var components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);
+ validateDsn(components);
+ return components;
+}
+exports.makeDsn = makeDsn;
+//# sourceMappingURL=dsn.js.map
+
+/***/ }),
+
+/***/ 19489:
+/***/ ((__unused_webpack_module, exports) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical'];
+//# sourceMappingURL=enums.js.map
+
+/***/ }),
+
+/***/ 31913:
+/***/ ((__unused_webpack_module, exports) => {
+
+/*
+ * This module exists for optimizations in the build process through rollup and terser. We define some global
+ * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these
+ * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will
+ * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to
+ * `logger` and preventing node-related code from appearing in browser bundles.
+ *
+ * Attention:
+ * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by
+ * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack)
+ * having issues tree-shaking these constants across package boundaries.
+ * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want
+ * users to be able to shake away expressions that it guards.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/**
+ * Figures out if we're building a browser bundle.
+ *
+ * @returns true if this is a browser bundle build.
+ */
+function isBrowserBundle() {
+ return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;
+}
+exports.isBrowserBundle = isBrowserBundle;
+//# sourceMappingURL=env.js.map
+
+/***/ }),
+
+/***/ 6222:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var is_1 = __nccwpck_require__(92757);
+/**
+ * Creates an envelope.
+ * Make sure to always explicitly provide the generic to this function
+ * so that the envelope types resolve correctly.
+ */
+function createEnvelope(headers, items) {
+ if (items === void 0) { items = []; }
+ return [headers, items];
+}
+exports.createEnvelope = createEnvelope;
+/**
+ * Add an item to an envelope.
+ * Make sure to always explicitly provide the generic to this function
+ * so that the envelope types resolve correctly.
+ */
+function addItemToEnvelope(envelope, newItem) {
+ var _a = tslib_1.__read(envelope, 2), headers = _a[0], items = _a[1];
+ return [headers, tslib_1.__spread(items, [newItem])];
+}
+exports.addItemToEnvelope = addItemToEnvelope;
+/**
+ * Get the type of the envelope. Grabs the type from the first envelope item.
+ */
+function getEnvelopeType(envelope) {
+ var _a = tslib_1.__read(envelope, 2), _b = tslib_1.__read(_a[1], 1), _c = tslib_1.__read(_b[0], 1), firstItemHeader = _c[0];
+ return firstItemHeader.type;
+}
+exports.getEnvelopeType = getEnvelopeType;
+/**
+ * Serializes an envelope into a string.
+ */
+function serializeEnvelope(envelope) {
+ var _a = tslib_1.__read(envelope, 2), headers = _a[0], items = _a[1];
+ var serializedHeaders = JSON.stringify(headers);
+ // Have to cast items to any here since Envelope is a union type
+ // Fixed in Typescript 4.2
+ // TODO: Remove any[] cast when we upgrade to TS 4.2
+ // https://github.com/microsoft/TypeScript/issues/36390
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return items.reduce(function (acc, item) {
+ var _a = tslib_1.__read(item, 2), itemHeaders = _a[0], payload = _a[1];
+ // We do not serialize payloads that are primitives
+ var serializedPayload = is_1.isPrimitive(payload) ? String(payload) : JSON.stringify(payload);
+ return acc + "\n" + JSON.stringify(itemHeaders) + "\n" + serializedPayload;
+ }, serializedHeaders);
+}
+exports.serializeEnvelope = serializeEnvelope;
+//# sourceMappingURL=envelope.js.map
+
+/***/ }),
+
+/***/ 66238:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var polyfill_1 = __nccwpck_require__(1243);
+/** An error emitted by Sentry SDKs and related utilities. */
+var SentryError = /** @class */ (function (_super) {
+ tslib_1.__extends(SentryError, _super);
+ function SentryError(message) {
+ var _newTarget = this.constructor;
+ var _this = _super.call(this, message) || this;
+ _this.message = message;
+ _this.name = _newTarget.prototype.constructor.name;
+ polyfill_1.setPrototypeOf(_this, _newTarget.prototype);
+ return _this;
+ }
+ return SentryError;
+}(Error));
+exports.SentryError = SentryError;
+//# sourceMappingURL=error.js.map
+
+/***/ }),
+
+/***/ 23710:
+/***/ ((__unused_webpack_module, exports) => {
+
+/*
+ * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking
+ * for users.
+ *
+ * Debug flags need to be declared in each package individually and must not be imported across package boundaries,
+ * because some build tools have trouble tree-shaking imported guards.
+ *
+ * As a convention, we define debug flags in a `flags.ts` file in the root of a package's `src` folder.
+ *
+ * Debug flag files will contain "magic strings" like `__SENTRY_DEBUG__` that may get replaced with actual values during
+ * our, or the user's build process. Take care when introducing new flags - they must not throw if they are not
+ * replaced.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/** Flag that is true for debug builds, false otherwise. */
+exports.IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;
+//# sourceMappingURL=flags.js.map
+
+/***/ }),
+
+/***/ 68813:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+/**
+ * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,
+ * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var node_1 = __nccwpck_require__(16411);
+var fallbackGlobalObject = {};
+/**
+ * Safely get global scope object
+ *
+ * @returns Global scope object
+ */
+function getGlobalObject() {
+ return (node_1.isNodeEnv()
+ ? global
+ : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals
+ ? window // eslint-disable-line no-restricted-globals
+ : typeof self !== 'undefined'
+ ? self
+ : fallbackGlobalObject);
+}
+exports.getGlobalObject = getGlobalObject;
+/**
+ * Returns a global singleton contained in the global `__SENTRY__` object.
+ *
+ * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
+ * function and added to the `__SENTRY__` object.
+ *
+ * @param name name of the global singleton on __SENTRY__
+ * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
+ * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `getGlobalObject`'s return value
+ * @returns the singleton
+ */
+function getGlobalSingleton(name, creator, obj) {
+ var global = (obj || getGlobalObject());
+ var __SENTRY__ = (global.__SENTRY__ = global.__SENTRY__ || {});
+ var singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());
+ return singleton;
+}
+exports.getGlobalSingleton = getGlobalSingleton;
+//# sourceMappingURL=global.js.map
+
+/***/ }),
+
+/***/ 1620:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+tslib_1.__exportStar(__nccwpck_require__(58343), exports);
+tslib_1.__exportStar(__nccwpck_require__(30597), exports);
+tslib_1.__exportStar(__nccwpck_require__(3275), exports);
+tslib_1.__exportStar(__nccwpck_require__(19489), exports);
+tslib_1.__exportStar(__nccwpck_require__(66238), exports);
+tslib_1.__exportStar(__nccwpck_require__(68813), exports);
+tslib_1.__exportStar(__nccwpck_require__(65474), exports);
+tslib_1.__exportStar(__nccwpck_require__(92757), exports);
+tslib_1.__exportStar(__nccwpck_require__(15577), exports);
+tslib_1.__exportStar(__nccwpck_require__(49515), exports);
+tslib_1.__exportStar(__nccwpck_require__(32154), exports);
+tslib_1.__exportStar(__nccwpck_require__(16411), exports);
+tslib_1.__exportStar(__nccwpck_require__(28592), exports);
+tslib_1.__exportStar(__nccwpck_require__(69249), exports);
+tslib_1.__exportStar(__nccwpck_require__(39188), exports);
+tslib_1.__exportStar(__nccwpck_require__(31811), exports);
+tslib_1.__exportStar(__nccwpck_require__(68853), exports);
+tslib_1.__exportStar(__nccwpck_require__(5986), exports);
+tslib_1.__exportStar(__nccwpck_require__(70313), exports);
+tslib_1.__exportStar(__nccwpck_require__(66538), exports);
+tslib_1.__exportStar(__nccwpck_require__(88714), exports);
+tslib_1.__exportStar(__nccwpck_require__(87833), exports);
+tslib_1.__exportStar(__nccwpck_require__(1735), exports);
+tslib_1.__exportStar(__nccwpck_require__(66850), exports);
+tslib_1.__exportStar(__nccwpck_require__(31913), exports);
+tslib_1.__exportStar(__nccwpck_require__(6222), exports);
+tslib_1.__exportStar(__nccwpck_require__(38857), exports);
+tslib_1.__exportStar(__nccwpck_require__(69377), exports);
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 65474:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var flags_1 = __nccwpck_require__(23710);
+var global_1 = __nccwpck_require__(68813);
+var is_1 = __nccwpck_require__(92757);
+var logger_1 = __nccwpck_require__(15577);
+var object_1 = __nccwpck_require__(69249);
+var stacktrace_1 = __nccwpck_require__(5986);
+var supports_1 = __nccwpck_require__(88714);
+var global = global_1.getGlobalObject();
+/**
+ * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.
+ * - Console API
+ * - Fetch API
+ * - XHR API
+ * - History API
+ * - DOM API (click/typing)
+ * - Error API
+ * - UnhandledRejection API
+ */
+var handlers = {};
+var instrumented = {};
+/** Instruments given API */
+function instrument(type) {
+ if (instrumented[type]) {
+ return;
+ }
+ instrumented[type] = true;
+ switch (type) {
+ case 'console':
+ instrumentConsole();
+ break;
+ case 'dom':
+ instrumentDOM();
+ break;
+ case 'xhr':
+ instrumentXHR();
+ break;
+ case 'fetch':
+ instrumentFetch();
+ break;
+ case 'history':
+ instrumentHistory();
+ break;
+ case 'error':
+ instrumentError();
+ break;
+ case 'unhandledrejection':
+ instrumentUnhandledRejection();
+ break;
+ default:
+ flags_1.IS_DEBUG_BUILD && logger_1.logger.warn('unknown instrumentation type:', type);
+ return;
+ }
+}
+/**
+ * Add handler that will be called when given type of instrumentation triggers.
+ * Use at your own risk, this might break without changelog notice, only used internally.
+ * @hidden
+ */
+function addInstrumentationHandler(type, callback) {
+ handlers[type] = handlers[type] || [];
+ handlers[type].push(callback);
+ instrument(type);
+}
+exports.addInstrumentationHandler = addInstrumentationHandler;
+/** JSDoc */
+function triggerHandlers(type, data) {
+ var e_1, _a;
+ if (!type || !handlers[type]) {
+ return;
+ }
+ try {
+ for (var _b = tslib_1.__values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var handler = _c.value;
+ try {
+ handler(data);
+ }
+ catch (e) {
+ flags_1.IS_DEBUG_BUILD &&
+ logger_1.logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + stacktrace_1.getFunctionName(handler) + "\nError:", e);
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+}
+/** JSDoc */
+function instrumentConsole() {
+ if (!('console' in global)) {
+ return;
+ }
+ logger_1.CONSOLE_LEVELS.forEach(function (level) {
+ if (!(level in global.console)) {
+ return;
+ }
+ object_1.fill(global.console, level, function (originalConsoleMethod) {
+ return function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ triggerHandlers('console', { args: args, level: level });
+ // this fails for some browsers. :(
+ if (originalConsoleMethod) {
+ originalConsoleMethod.apply(global.console, args);
+ }
+ };
+ });
+ });
+}
+/** JSDoc */
+function instrumentFetch() {
+ if (!supports_1.supportsNativeFetch()) {
+ return;
+ }
+ object_1.fill(global, 'fetch', function (originalFetch) {
+ return function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var handlerData = {
+ args: args,
+ fetchData: {
+ method: getFetchMethod(args),
+ url: getFetchUrl(args),
+ },
+ startTimestamp: Date.now(),
+ };
+ triggerHandlers('fetch', tslib_1.__assign({}, handlerData));
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ return originalFetch.apply(global, args).then(function (response) {
+ triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), response: response }));
+ return response;
+ }, function (error) {
+ triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), error: error }));
+ // NOTE: If you are a Sentry user, and you are seeing this stack frame,
+ // it means the sentry.javascript SDK caught an error invoking your application code.
+ // This is expected behavior and NOT indicative of a bug with sentry.javascript.
+ throw error;
+ });
+ };
+ });
+}
+/* eslint-disable @typescript-eslint/no-unsafe-member-access */
+/** Extract `method` from fetch call arguments */
+function getFetchMethod(fetchArgs) {
+ if (fetchArgs === void 0) { fetchArgs = []; }
+ if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {
+ return String(fetchArgs[0].method).toUpperCase();
+ }
+ if (fetchArgs[1] && fetchArgs[1].method) {
+ return String(fetchArgs[1].method).toUpperCase();
+ }
+ return 'GET';
+}
+/** Extract `url` from fetch call arguments */
+function getFetchUrl(fetchArgs) {
+ if (fetchArgs === void 0) { fetchArgs = []; }
+ if (typeof fetchArgs[0] === 'string') {
+ return fetchArgs[0];
+ }
+ if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) {
+ return fetchArgs[0].url;
+ }
+ return String(fetchArgs[0]);
+}
+/* eslint-enable @typescript-eslint/no-unsafe-member-access */
+/** JSDoc */
+function instrumentXHR() {
+ if (!('XMLHttpRequest' in global)) {
+ return;
+ }
+ var xhrproto = XMLHttpRequest.prototype;
+ object_1.fill(xhrproto, 'open', function (originalOpen) {
+ return function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
+ var xhr = this;
+ var url = args[1];
+ var xhrInfo = (xhr.__sentry_xhr__ = {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ method: is_1.isString(args[0]) ? args[0].toUpperCase() : args[0],
+ url: args[1],
+ });
+ // if Sentry key appears in URL, don't capture it as a request
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ if (is_1.isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {
+ xhr.__sentry_own_request__ = true;
+ }
+ var onreadystatechangeHandler = function () {
+ if (xhr.readyState === 4) {
+ try {
+ // touching statusCode in some platforms throws
+ // an exception
+ xhrInfo.status_code = xhr.status;
+ }
+ catch (e) {
+ /* do nothing */
+ }
+ triggerHandlers('xhr', {
+ args: args,
+ endTimestamp: Date.now(),
+ startTimestamp: Date.now(),
+ xhr: xhr,
+ });
+ }
+ };
+ if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {
+ object_1.fill(xhr, 'onreadystatechange', function (original) {
+ return function () {
+ var readyStateArgs = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ readyStateArgs[_i] = arguments[_i];
+ }
+ onreadystatechangeHandler();
+ return original.apply(xhr, readyStateArgs);
+ };
+ });
+ }
+ else {
+ xhr.addEventListener('readystatechange', onreadystatechangeHandler);
+ }
+ return originalOpen.apply(xhr, args);
+ };
+ });
+ object_1.fill(xhrproto, 'send', function (originalSend) {
+ return function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ if (this.__sentry_xhr__ && args[0] !== undefined) {
+ this.__sentry_xhr__.body = args[0];
+ }
+ triggerHandlers('xhr', {
+ args: args,
+ startTimestamp: Date.now(),
+ xhr: this,
+ });
+ return originalSend.apply(this, args);
+ };
+ });
+}
+var lastHref;
+/** JSDoc */
+function instrumentHistory() {
+ if (!supports_1.supportsHistory()) {
+ return;
+ }
+ var oldOnPopState = global.onpopstate;
+ global.onpopstate = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var to = global.location.href;
+ // keep track of the current URL state, as we always receive only the updated state
+ var from = lastHref;
+ lastHref = to;
+ triggerHandlers('history', {
+ from: from,
+ to: to,
+ });
+ if (oldOnPopState) {
+ // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.
+ // https://github.com/getsentry/sentry-javascript/issues/3344
+ // https://github.com/bugsnag/bugsnag-js/issues/469
+ try {
+ return oldOnPopState.apply(this, args);
+ }
+ catch (_oO) {
+ // no-empty
+ }
+ }
+ };
+ /** @hidden */
+ function historyReplacementFunction(originalHistoryFunction) {
+ return function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var url = args.length > 2 ? args[2] : undefined;
+ if (url) {
+ // coerce to string (this is what pushState does)
+ var from = lastHref;
+ var to = String(url);
+ // keep track of the current URL state, as we always receive only the updated state
+ lastHref = to;
+ triggerHandlers('history', {
+ from: from,
+ to: to,
+ });
+ }
+ return originalHistoryFunction.apply(this, args);
+ };
+ }
+ object_1.fill(global.history, 'pushState', historyReplacementFunction);
+ object_1.fill(global.history, 'replaceState', historyReplacementFunction);
+}
+var debounceDuration = 1000;
+var debounceTimerID;
+var lastCapturedEvent;
+/**
+ * Decide whether the current event should finish the debounce of previously captured one.
+ * @param previous previously captured event
+ * @param current event to be captured
+ */
+function shouldShortcircuitPreviousDebounce(previous, current) {
+ // If there was no previous event, it should always be swapped for the new one.
+ if (!previous) {
+ return true;
+ }
+ // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.
+ if (previous.type !== current.type) {
+ return true;
+ }
+ try {
+ // If both events have the same type, it's still possible that actions were performed on different targets.
+ // e.g. 2 clicks on different buttons.
+ if (previous.target !== current.target) {
+ return true;
+ }
+ }
+ catch (e) {
+ // just accessing `target` property can throw an exception in some rare circumstances
+ // see: https://github.com/getsentry/sentry-javascript/issues/838
+ }
+ // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_
+ // to which an event listener was attached), we treat them as the same action, as we want to capture
+ // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.
+ return false;
+}
+/**
+ * Decide whether an event should be captured.
+ * @param event event to be captured
+ */
+function shouldSkipDOMEvent(event) {
+ // We are only interested in filtering `keypress` events for now.
+ if (event.type !== 'keypress') {
+ return false;
+ }
+ try {
+ var target = event.target;
+ if (!target || !target.tagName) {
+ return true;
+ }
+ // Only consider keypress events on actual input elements. This will disregard keypresses targeting body
+ // e.g.tabbing through elements, hotkeys, etc.
+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
+ return false;
+ }
+ }
+ catch (e) {
+ // just accessing `target` property can throw an exception in some rare circumstances
+ // see: https://github.com/getsentry/sentry-javascript/issues/838
+ }
+ return true;
+}
+/**
+ * Wraps addEventListener to capture UI breadcrumbs
+ * @param handler function that will be triggered
+ * @param globalListener indicates whether event was captured by the global event listener
+ * @returns wrapped breadcrumb events handler
+ * @hidden
+ */
+function makeDOMEventHandler(handler, globalListener) {
+ if (globalListener === void 0) { globalListener = false; }
+ return function (event) {
+ // It's possible this handler might trigger multiple times for the same
+ // event (e.g. event propagation through node ancestors).
+ // Ignore if we've already captured that event.
+ if (!event || lastCapturedEvent === event) {
+ return;
+ }
+ // We always want to skip _some_ events.
+ if (shouldSkipDOMEvent(event)) {
+ return;
+ }
+ var name = event.type === 'keypress' ? 'input' : event.type;
+ // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.
+ if (debounceTimerID === undefined) {
+ handler({
+ event: event,
+ name: name,
+ global: globalListener,
+ });
+ lastCapturedEvent = event;
+ }
+ // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.
+ // If that's the case, emit the previous event and store locally the newly-captured DOM event.
+ else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {
+ handler({
+ event: event,
+ name: name,
+ global: globalListener,
+ });
+ lastCapturedEvent = event;
+ }
+ // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.
+ clearTimeout(debounceTimerID);
+ debounceTimerID = global.setTimeout(function () {
+ debounceTimerID = undefined;
+ }, debounceDuration);
+ };
+}
+/** JSDoc */
+function instrumentDOM() {
+ if (!('document' in global)) {
+ return;
+ }
+ // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom
+ // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before
+ // we instrument `addEventListener` so that we don't end up attaching this handler twice.
+ var triggerDOMHandler = triggerHandlers.bind(null, 'dom');
+ var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);
+ global.document.addEventListener('click', globalDOMEventHandler, false);
+ global.document.addEventListener('keypress', globalDOMEventHandler, false);
+ // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled
+ // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That
+ // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler
+ // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still
+ // guaranteed to fire at least once.)
+ ['EventTarget', 'Node'].forEach(function (target) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ var proto = global[target] && global[target].prototype;
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins
+ if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
+ return;
+ }
+ object_1.fill(proto, 'addEventListener', function (originalAddEventListener) {
+ return function (type, listener, options) {
+ if (type === 'click' || type == 'keypress') {
+ try {
+ var el = this;
+ var handlers_1 = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});
+ var handlerForType = (handlers_1[type] = handlers_1[type] || { refCount: 0 });
+ if (!handlerForType.handler) {
+ var handler = makeDOMEventHandler(triggerDOMHandler);
+ handlerForType.handler = handler;
+ originalAddEventListener.call(this, type, handler, options);
+ }
+ handlerForType.refCount += 1;
+ }
+ catch (e) {
+ // Accessing dom properties is always fragile.
+ // Also allows us to skip `addEventListenrs` calls with no proper `this` context.
+ }
+ }
+ return originalAddEventListener.call(this, type, listener, options);
+ };
+ });
+ object_1.fill(proto, 'removeEventListener', function (originalRemoveEventListener) {
+ return function (type, listener, options) {
+ if (type === 'click' || type == 'keypress') {
+ try {
+ var el = this;
+ var handlers_2 = el.__sentry_instrumentation_handlers__ || {};
+ var handlerForType = handlers_2[type];
+ if (handlerForType) {
+ handlerForType.refCount -= 1;
+ // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.
+ if (handlerForType.refCount <= 0) {
+ originalRemoveEventListener.call(this, type, handlerForType.handler, options);
+ handlerForType.handler = undefined;
+ delete handlers_2[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete
+ }
+ // If there are no longer any custom handlers of any type on this element, cleanup everything.
+ if (Object.keys(handlers_2).length === 0) {
+ delete el.__sentry_instrumentation_handlers__;
+ }
+ }
+ }
+ catch (e) {
+ // Accessing dom properties is always fragile.
+ // Also allows us to skip `addEventListenrs` calls with no proper `this` context.
+ }
+ }
+ return originalRemoveEventListener.call(this, type, listener, options);
+ };
+ });
+ });
+}
+var _oldOnErrorHandler = null;
+/** JSDoc */
+function instrumentError() {
+ _oldOnErrorHandler = global.onerror;
+ global.onerror = function (msg, url, line, column, error) {
+ triggerHandlers('error', {
+ column: column,
+ error: error,
+ line: line,
+ msg: msg,
+ url: url,
+ });
+ if (_oldOnErrorHandler) {
+ // eslint-disable-next-line prefer-rest-params
+ return _oldOnErrorHandler.apply(this, arguments);
+ }
+ return false;
+ };
+}
+var _oldOnUnhandledRejectionHandler = null;
+/** JSDoc */
+function instrumentUnhandledRejection() {
+ _oldOnUnhandledRejectionHandler = global.onunhandledrejection;
+ global.onunhandledrejection = function (e) {
+ triggerHandlers('unhandledrejection', e);
+ if (_oldOnUnhandledRejectionHandler) {
+ // eslint-disable-next-line prefer-rest-params
+ return _oldOnUnhandledRejectionHandler.apply(this, arguments);
+ }
+ return true;
+ };
+}
+//# sourceMappingURL=instrument.js.map
+
+/***/ }),
+
+/***/ 92757:
+/***/ ((__unused_webpack_module, exports) => {
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+// eslint-disable-next-line @typescript-eslint/unbound-method
+var objectToString = Object.prototype.toString;
+/**
+ * Checks whether given value's type is one of a few Error or Error-like
+ * {@link isError}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isError(wat) {
+ switch (objectToString.call(wat)) {
+ case '[object Error]':
+ case '[object Exception]':
+ case '[object DOMException]':
+ return true;
+ default:
+ return isInstanceOf(wat, Error);
+ }
+}
+exports.isError = isError;
+function isBuiltin(wat, ty) {
+ return objectToString.call(wat) === "[object " + ty + "]";
+}
+/**
+ * Checks whether given value's type is ErrorEvent
+ * {@link isErrorEvent}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isErrorEvent(wat) {
+ return isBuiltin(wat, 'ErrorEvent');
+}
+exports.isErrorEvent = isErrorEvent;
+/**
+ * Checks whether given value's type is DOMError
+ * {@link isDOMError}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isDOMError(wat) {
+ return isBuiltin(wat, 'DOMError');
+}
+exports.isDOMError = isDOMError;
+/**
+ * Checks whether given value's type is DOMException
+ * {@link isDOMException}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isDOMException(wat) {
+ return isBuiltin(wat, 'DOMException');
+}
+exports.isDOMException = isDOMException;
+/**
+ * Checks whether given value's type is a string
+ * {@link isString}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isString(wat) {
+ return isBuiltin(wat, 'String');
+}
+exports.isString = isString;
+/**
+ * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
+ * {@link isPrimitive}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isPrimitive(wat) {
+ return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');
+}
+exports.isPrimitive = isPrimitive;
+/**
+ * Checks whether given value's type is an object literal
+ * {@link isPlainObject}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isPlainObject(wat) {
+ return isBuiltin(wat, 'Object');
+}
+exports.isPlainObject = isPlainObject;
+/**
+ * Checks whether given value's type is an Event instance
+ * {@link isEvent}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isEvent(wat) {
+ return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
+}
+exports.isEvent = isEvent;
+/**
+ * Checks whether given value's type is an Element instance
+ * {@link isElement}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isElement(wat) {
+ return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
+}
+exports.isElement = isElement;
+/**
+ * Checks whether given value's type is an regexp
+ * {@link isRegExp}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isRegExp(wat) {
+ return isBuiltin(wat, 'RegExp');
+}
+exports.isRegExp = isRegExp;
+/**
+ * Checks whether given value has a then function.
+ * @param wat A value to be checked.
+ */
+function isThenable(wat) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ return Boolean(wat && wat.then && typeof wat.then === 'function');
+}
+exports.isThenable = isThenable;
+/**
+ * Checks whether given value's type is a SyntheticEvent
+ * {@link isSyntheticEvent}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isSyntheticEvent(wat) {
+ return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
+}
+exports.isSyntheticEvent = isSyntheticEvent;
+/**
+ * Checks whether given value is NaN
+ * {@link isNaN}.
+ *
+ * @param wat A value to be checked.
+ * @returns A boolean representing the result.
+ */
+function isNaN(wat) {
+ return typeof wat === 'number' && wat !== wat;
+}
+exports.isNaN = isNaN;
+/**
+ * Checks whether given value's type is an instance of provided constructor.
+ * {@link isInstanceOf}.
+ *
+ * @param wat A value to be checked.
+ * @param base A constructor to be used in a check.
+ * @returns A boolean representing the result.
+ */
+function isInstanceOf(wat, base) {
+ try {
+ return wat instanceof base;
+ }
+ catch (_e) {
+ return false;
+ }
+}
+exports.isInstanceOf = isInstanceOf;
+//# sourceMappingURL=is.js.map
+
+/***/ }),
+
+/***/ 15577:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var flags_1 = __nccwpck_require__(23710);
+var global_1 = __nccwpck_require__(68813);
+// TODO: Implement different loggers for different environments
+var global = global_1.getGlobalObject();
+/** Prefix for logging strings */
+var PREFIX = 'Sentry Logger ';
+exports.CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert'];
+/**
+ * Temporarily disable sentry console instrumentations.
+ *
+ * @param callback The function to run against the original `console` messages
+ * @returns The results of the callback
+ */
+function consoleSandbox(callback) {
+ var global = global_1.getGlobalObject();
+ if (!('console' in global)) {
+ return callback();
+ }
+ var originalConsole = global.console;
+ var wrappedLevels = {};
+ // Restore all wrapped console methods
+ exports.CONSOLE_LEVELS.forEach(function (level) {
+ // TODO(v7): Remove this check as it's only needed for Node 6
+ var originalWrappedFunc = originalConsole[level] && originalConsole[level].__sentry_original__;
+ if (level in global.console && originalWrappedFunc) {
+ wrappedLevels[level] = originalConsole[level];
+ originalConsole[level] = originalWrappedFunc;
+ }
+ });
+ try {
+ return callback();
+ }
+ finally {
+ // Revert restoration to wrapped state
+ Object.keys(wrappedLevels).forEach(function (level) {
+ originalConsole[level] = wrappedLevels[level];
+ });
+ }
+}
+exports.consoleSandbox = consoleSandbox;
+function makeLogger() {
+ var enabled = false;
+ var logger = {
+ enable: function () {
+ enabled = true;
+ },
+ disable: function () {
+ enabled = false;
+ },
+ };
+ if (flags_1.IS_DEBUG_BUILD) {
+ exports.CONSOLE_LEVELS.forEach(function (name) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ logger[name] = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ if (enabled) {
+ consoleSandbox(function () {
+ var _a;
+ (_a = global.console)[name].apply(_a, tslib_1.__spread([PREFIX + "[" + name + "]:"], args));
+ });
+ }
+ };
+ });
+ }
+ else {
+ exports.CONSOLE_LEVELS.forEach(function (name) {
+ logger[name] = function () { return undefined; };
+ });
+ }
+ return logger;
+}
+// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used
+var logger;
+exports.logger = logger;
+if (flags_1.IS_DEBUG_BUILD) {
+ exports.logger = logger = global_1.getGlobalSingleton('logger', makeLogger);
+}
+else {
+ exports.logger = logger = makeLogger();
+}
+//# sourceMappingURL=logger.js.map
+
+/***/ }),
+
+/***/ 49515:
+/***/ ((__unused_webpack_module, exports) => {
+
+/* eslint-disable @typescript-eslint/no-unsafe-member-access */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/**
+ * Helper to decycle json objects
+ */
+function memoBuilder() {
+ var hasWeakSet = typeof WeakSet === 'function';
+ var inner = hasWeakSet ? new WeakSet() : [];
+ function memoize(obj) {
+ if (hasWeakSet) {
+ if (inner.has(obj)) {
+ return true;
+ }
+ inner.add(obj);
+ return false;
+ }
+ // eslint-disable-next-line @typescript-eslint/prefer-for-of
+ for (var i = 0; i < inner.length; i++) {
+ var value = inner[i];
+ if (value === obj) {
+ return true;
+ }
+ }
+ inner.push(obj);
+ return false;
+ }
+ function unmemoize(obj) {
+ if (hasWeakSet) {
+ inner.delete(obj);
+ }
+ else {
+ for (var i = 0; i < inner.length; i++) {
+ if (inner[i] === obj) {
+ inner.splice(i, 1);
+ break;
+ }
+ }
+ }
+ }
+ return [memoize, unmemoize];
+}
+exports.memoBuilder = memoBuilder;
+//# sourceMappingURL=memo.js.map
+
+/***/ }),
+
+/***/ 32154:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var global_1 = __nccwpck_require__(68813);
+var object_1 = __nccwpck_require__(69249);
+var string_1 = __nccwpck_require__(66538);
+/**
+ * UUID4 generator
+ *
+ * @returns string Generated UUID4.
+ */
+function uuid4() {
+ var global = global_1.getGlobalObject();
+ var crypto = global.crypto || global.msCrypto;
+ if (!(crypto === void 0) && crypto.getRandomValues) {
+ // Use window.crypto API if available
+ var arr = new Uint16Array(8);
+ crypto.getRandomValues(arr);
+ // set 4 in byte 7
+ // eslint-disable-next-line no-bitwise
+ arr[3] = (arr[3] & 0xfff) | 0x4000;
+ // set 2 most significant bits of byte 9 to '10'
+ // eslint-disable-next-line no-bitwise
+ arr[4] = (arr[4] & 0x3fff) | 0x8000;
+ var pad = function (num) {
+ var v = num.toString(16);
+ while (v.length < 4) {
+ v = "0" + v;
+ }
+ return v;
+ };
+ return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7]));
+ }
+ // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
+ return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
+ // eslint-disable-next-line no-bitwise
+ var r = (Math.random() * 16) | 0;
+ // eslint-disable-next-line no-bitwise
+ var v = c === 'x' ? r : (r & 0x3) | 0x8;
+ return v.toString(16);
+ });
+}
+exports.uuid4 = uuid4;
+/**
+ * Parses string form of URL into an object
+ * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
+ * // intentionally using regex and not href parsing trick because React Native and other
+ * // environments where DOM might not be available
+ * @returns parsed URL object
+ */
+function parseUrl(url) {
+ if (!url) {
+ return {};
+ }
+ var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
+ if (!match) {
+ return {};
+ }
+ // coerce to undefined values to empty string so we don't get 'undefined'
+ var query = match[6] || '';
+ var fragment = match[8] || '';
+ return {
+ host: match[4],
+ path: match[5],
+ protocol: match[2],
+ relative: match[5] + query + fragment,
+ };
+}
+exports.parseUrl = parseUrl;
+function getFirstException(event) {
+ return event.exception && event.exception.values ? event.exception.values[0] : undefined;
+}
+/**
+ * Extracts either message or type+value from an event that can be used for user-facing logs
+ * @returns event's description
+ */
+function getEventDescription(event) {
+ var message = event.message, eventId = event.event_id;
+ if (message) {
+ return message;
+ }
+ var firstException = getFirstException(event);
+ if (firstException) {
+ if (firstException.type && firstException.value) {
+ return firstException.type + ": " + firstException.value;
+ }
+ return firstException.type || firstException.value || eventId || '';
+ }
+ return eventId || '';
+}
+exports.getEventDescription = getEventDescription;
+/**
+ * Adds exception values, type and value to an synthetic Exception.
+ * @param event The event to modify.
+ * @param value Value of the exception.
+ * @param type Type of the exception.
+ * @hidden
+ */
+function addExceptionTypeValue(event, value, type) {
+ var exception = (event.exception = event.exception || {});
+ var values = (exception.values = exception.values || []);
+ var firstException = (values[0] = values[0] || {});
+ if (!firstException.value) {
+ firstException.value = value || '';
+ }
+ if (!firstException.type) {
+ firstException.type = type || 'Error';
+ }
+}
+exports.addExceptionTypeValue = addExceptionTypeValue;
+/**
+ * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
+ *
+ * @param event The event to modify.
+ * @param newMechanism Mechanism data to add to the event.
+ * @hidden
+ */
+function addExceptionMechanism(event, newMechanism) {
+ var firstException = getFirstException(event);
+ if (!firstException) {
+ return;
+ }
+ var defaultMechanism = { type: 'generic', handled: true };
+ var currentMechanism = firstException.mechanism;
+ firstException.mechanism = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, defaultMechanism), currentMechanism), newMechanism);
+ if (newMechanism && 'data' in newMechanism) {
+ var mergedData = tslib_1.__assign(tslib_1.__assign({}, (currentMechanism && currentMechanism.data)), newMechanism.data);
+ firstException.mechanism.data = mergedData;
+ }
+}
+exports.addExceptionMechanism = addExceptionMechanism;
+// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
+var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
+/**
+ * Parses input into a SemVer interface
+ * @param input string representation of a semver version
+ */
+function parseSemver(input) {
+ var match = input.match(SEMVER_REGEXP) || [];
+ var major = parseInt(match[1], 10);
+ var minor = parseInt(match[2], 10);
+ var patch = parseInt(match[3], 10);
+ return {
+ buildmetadata: match[5],
+ major: isNaN(major) ? undefined : major,
+ minor: isNaN(minor) ? undefined : minor,
+ patch: isNaN(patch) ? undefined : patch,
+ prerelease: match[4],
+ };
+}
+exports.parseSemver = parseSemver;
+/**
+ * This function adds context (pre/post/line) lines to the provided frame
+ *
+ * @param lines string[] containing all lines
+ * @param frame StackFrame that will be mutated
+ * @param linesOfContext number of context lines we want to add pre/post
+ */
+function addContextToFrame(lines, frame, linesOfContext) {
+ if (linesOfContext === void 0) { linesOfContext = 5; }
+ var lineno = frame.lineno || 0;
+ var maxLines = lines.length;
+ var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0);
+ frame.pre_context = lines
+ .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)
+ .map(function (line) { return string_1.snipLine(line, 0); });
+ frame.context_line = string_1.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);
+ frame.post_context = lines
+ .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)
+ .map(function (line) { return string_1.snipLine(line, 0); });
+}
+exports.addContextToFrame = addContextToFrame;
+/**
+ * Strip the query string and fragment off of a given URL or path (if present)
+ *
+ * @param urlPath Full URL or path, including possible query string and/or fragment
+ * @returns URL or path without query string or fragment
+ */
+function stripUrlQueryAndFragment(urlPath) {
+ // eslint-disable-next-line no-useless-escape
+ return urlPath.split(/[\?#]/, 1)[0];
+}
+exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment;
+/**
+ * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object
+ * in question), and marks it captured if not.
+ *
+ * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and
+ * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so
+ * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because
+ * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not
+ * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This
+ * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we
+ * see it.
+ *
+ * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on
+ * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent
+ * object wrapper forms so that this check will always work. However, because we need to flag the exact object which
+ * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification
+ * must be done before the exception captured.
+ *
+ * @param A thrown exception to check or flag as having been seen
+ * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
+ */
+function checkOrSetAlreadyCaught(exception) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ if (exception && exception.__sentry_captured__) {
+ return true;
+ }
+ try {
+ // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the
+ // `ExtraErrorData` integration
+ object_1.addNonEnumerableProperty(exception, '__sentry_captured__', true);
+ }
+ catch (err) {
+ // `exception` is a primitive, so we can't mark it seen
+ }
+ return false;
+}
+exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught;
+//# sourceMappingURL=misc.js.map
+
+/***/ }),
+
+/***/ 16411:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+/* module decorator */ module = __nccwpck_require__.nmd(module);
+/**
+ * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,
+ * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var env_1 = __nccwpck_require__(31913);
+/**
+ * Checks whether we're in the Node.js or Browser environment
+ *
+ * @returns Answer to given question
+ */
+function isNodeEnv() {
+ // explicitly check for browser bundles as those can be optimized statically
+ // by terser/rollup.
+ return (!env_1.isBrowserBundle() &&
+ Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]');
+}
+exports.isNodeEnv = isNodeEnv;
+/**
+ * Requires a module which is protected against bundler minification.
+ *
+ * @param request The module path to resolve
+ */
+// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
+function dynamicRequire(mod, request) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ return mod.require(request);
+}
+exports.dynamicRequire = dynamicRequire;
+/**
+ * Helper for dynamically loading module that should work with linked dependencies.
+ * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`
+ * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during
+ * build time. `require.resolve` is also not available in any other way, so we cannot create,
+ * a fake helper like we do with `dynamicRequire`.
+ *
+ * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.
+ * That is to mimic the behavior of `require.resolve` exactly.
+ *
+ * @param moduleName module name to require
+ * @returns possibly required module
+ */
+function loadModule(moduleName) {
+ var mod;
+ try {
+ mod = dynamicRequire(module, moduleName);
+ }
+ catch (e) {
+ // no-empty
+ }
+ try {
+ var cwd = dynamicRequire(module, 'process').cwd;
+ mod = dynamicRequire(module, cwd() + "/node_modules/" + moduleName);
+ }
+ catch (e) {
+ // no-empty
+ }
+ return mod;
+}
+exports.loadModule = loadModule;
+//# sourceMappingURL=node.js.map
+
+/***/ }),
+
+/***/ 28592:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var is_1 = __nccwpck_require__(92757);
+var memo_1 = __nccwpck_require__(49515);
+var object_1 = __nccwpck_require__(69249);
+var stacktrace_1 = __nccwpck_require__(5986);
+/**
+ * Recursively normalizes the given object.
+ *
+ * - Creates a copy to prevent original input mutation
+ * - Skips non-enumerable properties
+ * - When stringifying, calls `toJSON` if implemented
+ * - Removes circular references
+ * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format
+ * - Translates known global objects/classes to a string representations
+ * - Takes care of `Error` object serialization
+ * - Optionally limits depth of final output
+ * - Optionally limits number of properties/elements included in any single object/array
+ *
+ * @param input The object to be normalized.
+ * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)
+ * @param maxProperties The max number of elements or properties to be included in any single array or
+ * object in the normallized output..
+ * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization.
+ */
+function normalize(input, depth, maxProperties) {
+ if (depth === void 0) { depth = +Infinity; }
+ if (maxProperties === void 0) { maxProperties = +Infinity; }
+ try {
+ // since we're at the outermost level, there is no key
+ return visit('', input, depth, maxProperties);
+ }
+ catch (err) {
+ return { ERROR: "**non-serializable** (" + err + ")" };
+ }
+}
+exports.normalize = normalize;
+/** JSDoc */
+function normalizeToSize(object,
+// Default Node.js REPL depth
+depth,
+// 100kB, as 200kB is max payload size, so half sounds reasonable
+maxSize) {
+ if (depth === void 0) { depth = 3; }
+ if (maxSize === void 0) { maxSize = 100 * 1024; }
+ var normalized = normalize(object, depth);
+ if (jsonSize(normalized) > maxSize) {
+ return normalizeToSize(object, depth - 1, maxSize);
+ }
+ return normalized;
+}
+exports.normalizeToSize = normalizeToSize;
+/**
+ * Visits a node to perform normalization on it
+ *
+ * @param key The key corresponding to the given node
+ * @param value The node to be visited
+ * @param depth Optional number indicating the maximum recursion depth
+ * @param maxProperties Optional maximum number of properties/elements included in any single object/array
+ * @param memo Optional Memo class handling decycling
+ */
+function visit(key, value, depth, maxProperties, memo) {
+ if (depth === void 0) { depth = +Infinity; }
+ if (maxProperties === void 0) { maxProperties = +Infinity; }
+ if (memo === void 0) { memo = memo_1.memoBuilder(); }
+ var _a = tslib_1.__read(memo, 2), memoize = _a[0], unmemoize = _a[1];
+ // If the value has a `toJSON` method, see if we can bail and let it do the work
+ var valueWithToJSON = value;
+ if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {
+ try {
+ return valueWithToJSON.toJSON();
+ }
+ catch (err) {
+ // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)
+ }
+ }
+ // Get the simple cases out of the way first
+ if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !is_1.isNaN(value))) {
+ return value;
+ }
+ var stringified = stringifyValue(key, value);
+ // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`.
+ // Everything else will have already been serialized, so if we don't see that pattern, we're done.
+ if (!stringified.startsWith('[object ')) {
+ return stringified;
+ }
+ // We're also done if we've reached the max depth
+ if (depth === 0) {
+ // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`.
+ return stringified.replace('object ', '');
+ }
+ // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.
+ if (memoize(value)) {
+ return '[Circular ~]';
+ }
+ // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse
+ // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each
+ // property/entry, and keep track of the number of items we add to it.
+ var normalized = (Array.isArray(value) ? [] : {});
+ var numAdded = 0;
+ // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant
+ // properties are non-enumerable and otherwise would get missed.
+ var visitable = (is_1.isError(value) || is_1.isEvent(value) ? object_1.convertToPlainObject(value) : value);
+ for (var visitKey in visitable) {
+ // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.
+ if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
+ continue;
+ }
+ if (numAdded >= maxProperties) {
+ normalized[visitKey] = '[MaxProperties ~]';
+ break;
+ }
+ // Recursively visit all the child nodes
+ var visitValue = visitable[visitKey];
+ normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo);
+ numAdded += 1;
+ }
+ // Once we've visited all the branches, remove the parent from memo storage
+ unmemoize(value);
+ // Return accumulated values
+ return normalized;
+}
+exports.walk = visit;
+/**
+ * Stringify the given value. Handles various known special values and types.
+ *
+ * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn
+ * the number 1231 into "[Object Number]", nor on `null`, as it will throw.
+ *
+ * @param value The value to stringify
+ * @returns A stringified representation of the given value
+ */
+function stringifyValue(key,
+// this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for
+// our internal use, it'll do
+value) {
+ try {
+ if (key === 'domain' && value && typeof value === 'object' && value._events) {
+ return '[Domain]';
+ }
+ if (key === 'domainEmitter') {
+ return '[DomainEmitter]';
+ }
+ // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first
+ // which won't throw if they are not present.
+ if (typeof global !== 'undefined' && value === global) {
+ return '[Global]';
+ }
+ // eslint-disable-next-line no-restricted-globals
+ if (typeof window !== 'undefined' && value === window) {
+ return '[Window]';
+ }
+ // eslint-disable-next-line no-restricted-globals
+ if (typeof document !== 'undefined' && value === document) {
+ return '[Document]';
+ }
+ // React's SyntheticEvent thingy
+ if (is_1.isSyntheticEvent(value)) {
+ return '[SyntheticEvent]';
+ }
+ if (typeof value === 'number' && value !== value) {
+ return '[NaN]';
+ }
+ // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own)
+ if (value === void 0) {
+ return '[undefined]';
+ }
+ if (typeof value === 'function') {
+ return "[Function: " + stacktrace_1.getFunctionName(value) + "]";
+ }
+ if (typeof value === 'symbol') {
+ return "[" + String(value) + "]";
+ }
+ // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion
+ if (typeof value === 'bigint') {
+ return "[BigInt: " + String(value) + "]";
+ }
+ // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting
+ // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as
+ // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class),
+ // we can make sure that only plain objects come out that way.
+ return "[object " + Object.getPrototypeOf(value).constructor.name + "]";
+ }
+ catch (err) {
+ return "**non-serializable** (" + err + ")";
+ }
+}
+/** Calculates bytes size of input string */
+function utf8Length(value) {
+ // eslint-disable-next-line no-bitwise
+ return ~-encodeURI(value).split(/%..|./).length;
+}
+/** Calculates bytes size of input object */
+function jsonSize(value) {
+ return utf8Length(JSON.stringify(value));
+}
+//# sourceMappingURL=normalize.js.map
+
+/***/ }),
+
+/***/ 69249:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+var browser_1 = __nccwpck_require__(30597);
+var is_1 = __nccwpck_require__(92757);
+var string_1 = __nccwpck_require__(66538);
+/**
+ * Replace a method in an object with a wrapped version of itself.
+ *
+ * @param source An object that contains a method to be wrapped.
+ * @param name The name of the method to be wrapped.
+ * @param replacementFactory A higher-order function that takes the original version of the given method and returns a
+ * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to
+ * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.
+ * @returns void
+ */
+function fill(source, name, replacementFactory) {
+ if (!(name in source)) {
+ return;
+ }
+ var original = source[name];
+ var wrapped = replacementFactory(original);
+ // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work
+ // otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
+ if (typeof wrapped === 'function') {
+ try {
+ markFunctionWrapped(wrapped, original);
+ }
+ catch (_Oo) {
+ // This can throw if multiple fill happens on a global object like XMLHttpRequest
+ // Fixes https://github.com/getsentry/sentry-javascript/issues/2043
+ }
+ }
+ source[name] = wrapped;
+}
+exports.fill = fill;
+/**
+ * Defines a non-enumerable property on the given object.
+ *
+ * @param obj The object on which to set the property
+ * @param name The name of the property to be set
+ * @param value The value to which to set the property
+ */
+function addNonEnumerableProperty(obj, name, value) {
+ Object.defineProperty(obj, name, {
+ // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
+ value: value,
+ writable: true,
+ configurable: true,
+ });
+}
+exports.addNonEnumerableProperty = addNonEnumerableProperty;
+/**
+ * Remembers the original function on the wrapped function and
+ * patches up the prototype.
+ *
+ * @param wrapped the wrapper function
+ * @param original the original function that gets wrapped
+ */
+function markFunctionWrapped(wrapped, original) {
+ var proto = original.prototype || {};
+ wrapped.prototype = original.prototype = proto;
+ addNonEnumerableProperty(wrapped, '__sentry_original__', original);
+}
+exports.markFunctionWrapped = markFunctionWrapped;
+/**
+ * This extracts the original function if available. See
+ * `markFunctionWrapped` for more information.
+ *
+ * @param func the function to unwrap
+ * @returns the unwrapped version of the function if available.
+ */
+function getOriginalFunction(func) {
+ return func.__sentry_original__;
+}
+exports.getOriginalFunction = getOriginalFunction;
+/**
+ * Encodes given object into url-friendly format
+ *
+ * @param object An object that contains serializable values
+ * @returns string Encoded
+ */
+function urlEncode(object) {
+ return Object.keys(object)
+ .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); })
+ .join('&');
+}
+exports.urlEncode = urlEncode;
+/**
+ * Transforms any object into an object literal with all its attributes
+ * attached to it.
+ *
+ * @param value Initial source that we have to transform in order for it to be usable by the serializer
+ */
+function convertToPlainObject(value) {
+ var newObj = value;
+ if (is_1.isError(value)) {
+ newObj = tslib_1.__assign({ message: value.message, name: value.name, stack: value.stack }, getOwnProperties(value));
+ }
+ else if (is_1.isEvent(value)) {
+ var event_1 = value;
+ newObj = tslib_1.__assign({ type: event_1.type, target: serializeEventTarget(event_1.target), currentTarget: serializeEventTarget(event_1.currentTarget) }, getOwnProperties(event_1));
+ if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) {
+ newObj.detail = event_1.detail;
+ }
+ }
+ return newObj;
+}
+exports.convertToPlainObject = convertToPlainObject;
+/** Creates a string representation of the target of an `Event` object */
+function serializeEventTarget(target) {
+ try {
+ return is_1.isElement(target) ? browser_1.htmlTreeAsString(target) : Object.prototype.toString.call(target);
+ }
+ catch (_oO) {
+ return '';
+ }
+}
+/** Filters out all but an object's own properties */
+function getOwnProperties(obj) {
+ var extractedProps = {};
+ for (var property in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, property)) {
+ extractedProps[property] = obj[property];
+ }
+ }
+ return extractedProps;
+}
+/**
+ * Given any captured exception, extract its keys and create a sorted
+ * and truncated list that will be used inside the event message.
+ * eg. `Non-error exception captured with keys: foo, bar, baz`
+ */
+// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
+function extractExceptionKeysForMessage(exception, maxLength) {
+ if (maxLength === void 0) { maxLength = 40; }
+ var keys = Object.keys(convertToPlainObject(exception));
+ keys.sort();
+ if (!keys.length) {
+ return '[object has no keys]';
+ }
+ if (keys[0].length >= maxLength) {
+ return string_1.truncate(keys[0], maxLength);
+ }
+ for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) {
+ var serialized = keys.slice(0, includedKeys).join(', ');
+ if (serialized.length > maxLength) {
+ continue;
+ }
+ if (includedKeys === keys.length) {
+ return serialized;
+ }
+ return string_1.truncate(serialized, maxLength);
+ }
+ return '';
+}
+exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage;
+/**
+ * Given any object, return the new object with removed keys that value was `undefined`.
+ * Works recursively on objects and arrays.
+ */
+function dropUndefinedKeys(val) {
+ var e_1, _a;
+ if (is_1.isPlainObject(val)) {
+ var rv = {};
+ try {
+ for (var _b = tslib_1.__values(Object.keys(val)), _c = _b.next(); !_c.done; _c = _b.next()) {
+ var key = _c.value;
+ if (typeof val[key] !== 'undefined') {
+ rv[key] = dropUndefinedKeys(val[key]);
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ return rv;
+ }
+ if (Array.isArray(val)) {
+ return val.map(dropUndefinedKeys);
+ }
+ return val;
+}
+exports.dropUndefinedKeys = dropUndefinedKeys;
+/**
+ * Ensure that something is an object.
+ *
+ * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper
+ * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.
+ *
+ * @param wat The subject of the objectification
+ * @returns A version of `wat` which can safely be used with `Object` class methods
+ */
+function objectify(wat) {
+ var objectified;
+ switch (true) {
+ case wat === undefined || wat === null:
+ objectified = new String(wat);
+ break;
+ // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason
+ // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as
+ // an object in order to wrap it.
+ case typeof wat === 'symbol' || typeof wat === 'bigint':
+ objectified = Object(wat);
+ break;
+ // this will catch the remaining primitives: `String`, `Number`, and `Boolean`
+ case is_1.isPrimitive(wat):
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ objectified = new wat.constructor(wat);
+ break;
+ // by process of elimination, at this point we know that `wat` must already be an object
+ default:
+ objectified = wat;
+ break;
+ }
+ return objectified;
+}
+exports.objectify = objectify;
+//# sourceMappingURL=object.js.map
+
+/***/ }),
+
+/***/ 39188:
+/***/ ((__unused_webpack_module, exports) => {
+
+// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript
+// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/** JSDoc */
+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);
+ // eslint-disable-next-line no-plusplus
+ up++;
+ }
+ else if (up) {
+ parts.splice(i, 1);
+ // eslint-disable-next-line no-plusplus
+ up--;
+ }
+ }
+ // if the path is allowed to go above the root, restore leading ..s
+ if (allowAboveRoot) {
+ // eslint-disable-next-line no-plusplus
+ for (; up--; up) {
+ parts.unshift('..');
+ }
+ }
+ return parts;
+}
+// Split a filename into [root, dir, basename, ext], unix version
+// 'root' is just a slash, or nothing.
+var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/;
+/** JSDoc */
+function splitPath(filename) {
+ var parts = splitPathRe.exec(filename);
+ return parts ? parts.slice(1) : [];
+}
+// path.resolve([from ...], to)
+// posix version
+/** JSDoc */
+function resolve() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var resolvedPath = '';
+ var resolvedAbsolute = false;
+ for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
+ var path = i >= 0 ? args[i] : '/';
+ // Skip empty entries
+ 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(resolvedPath.split('/').filter(function (p) { return !!p; }), !resolvedAbsolute).join('/');
+ return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';
+}
+exports.resolve = resolve;
+/** JSDoc */
+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);
+}
+// path.relative(from, to)
+// posix version
+/** JSDoc */
+function relative(from, to) {
+ /* eslint-disable no-param-reassign */
+ from = resolve(from).substr(1);
+ to = resolve(to).substr(1);
+ /* eslint-enable no-param-reassign */
+ 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.relative = relative;
+// path.normalize(path)
+// posix version
+/** JSDoc */
+function normalizePath(path) {
+ var isPathAbsolute = isAbsolute(path);
+ var trailingSlash = path.substr(-1) === '/';
+ // Normalize the path
+ var normalizedPath = normalizeArray(path.split('/').filter(function (p) { return !!p; }), !isPathAbsolute).join('/');
+ if (!normalizedPath && !isPathAbsolute) {
+ normalizedPath = '.';
+ }
+ if (normalizedPath && trailingSlash) {
+ normalizedPath += '/';
+ }
+ return (isPathAbsolute ? '/' : '') + normalizedPath;
+}
+exports.normalizePath = normalizePath;
+// posix version
+/** JSDoc */
+function isAbsolute(path) {
+ return path.charAt(0) === '/';
+}
+exports.isAbsolute = isAbsolute;
+// posix version
+/** JSDoc */
+function join() {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return normalizePath(args.join('/'));
+}
+exports.join = join;
+/** JSDoc */
+function dirname(path) {
+ var result = splitPath(path);
+ var root = result[0];
+ var dir = result[1];
+ if (!root && !dir) {
+ // No dirname whatsoever
+ return '.';
+ }
+ if (dir) {
+ // It has a dirname, strip trailing slash
+ dir = dir.substr(0, dir.length - 1);
+ }
+ return root + dir;
+}
+exports.dirname = dirname;
+/** JSDoc */
+function basename(path, ext) {
+ var f = splitPath(path)[2];
+ if (ext && f.substr(ext.length * -1) === ext) {
+ f = f.substr(0, f.length - ext.length);
+ }
+ return f;
+}
+exports.basename = basename;
+//# sourceMappingURL=path.js.map
+
+/***/ }),
+
+/***/ 1243:
+/***/ ((__unused_webpack_module, exports) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);
+/**
+ * setPrototypeOf polyfill using __proto__
+ */
+// eslint-disable-next-line @typescript-eslint/ban-types
+function setProtoOf(obj, proto) {
+ // @ts-ignore __proto__ does not exist on obj
+ obj.__proto__ = proto;
+ return obj;
+}
+/**
+ * setPrototypeOf polyfill using mixin
+ */
+// eslint-disable-next-line @typescript-eslint/ban-types
+function mixinProperties(obj, proto) {
+ for (var prop in proto) {
+ if (!Object.prototype.hasOwnProperty.call(obj, prop)) {
+ // @ts-ignore typescript complains about indexing so we remove
+ obj[prop] = proto[prop];
+ }
+ }
+ return obj;
+}
+//# sourceMappingURL=polyfill.js.map
+
+/***/ }),
+
+/***/ 31811:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var error_1 = __nccwpck_require__(66238);
+var syncpromise_1 = __nccwpck_require__(87833);
+/**
+ * Creates an new PromiseBuffer object with the specified limit
+ * @param limit max number of promises that can be stored in the buffer
+ */
+function makePromiseBuffer(limit) {
+ var buffer = [];
+ function isReady() {
+ return limit === undefined || buffer.length < limit;
+ }
+ /**
+ * Remove a promise from the queue.
+ *
+ * @param task Can be any PromiseLike
+ * @returns Removed promise.
+ */
+ function remove(task) {
+ return buffer.splice(buffer.indexOf(task), 1)[0];
+ }
+ /**
+ * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.
+ *
+ * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:
+ * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor
+ * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By
+ * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer
+ * limit check.
+ * @returns The original promise.
+ */
+ function add(taskProducer) {
+ if (!isReady()) {
+ return syncpromise_1.rejectedSyncPromise(new error_1.SentryError('Not adding Promise due to buffer limit reached.'));
+ }
+ // start the task and add its promise to the queue
+ var task = taskProducer();
+ if (buffer.indexOf(task) === -1) {
+ buffer.push(task);
+ }
+ void task
+ .then(function () { return remove(task); })
+ // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`
+ // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't
+ // have promises, so TS has to polyfill when down-compiling.)
+ .then(null, function () {
+ return remove(task).then(null, function () {
+ // We have to add another catch here because `remove()` starts a new promise chain.
+ });
+ });
+ return task;
+ }
+ /**
+ * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.
+ *
+ * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or
+ * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to
+ * `true`.
+ * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and
+ * `false` otherwise
+ */
+ function drain(timeout) {
+ return new syncpromise_1.SyncPromise(function (resolve, reject) {
+ var counter = buffer.length;
+ if (!counter) {
+ return resolve(true);
+ }
+ // wait for `timeout` ms and then resolve to `false` (if not cancelled first)
+ var capturedSetTimeout = setTimeout(function () {
+ if (timeout && timeout > 0) {
+ resolve(false);
+ }
+ }, timeout);
+ // if all promises resolve in time, cancel the timer and resolve to `true`
+ buffer.forEach(function (item) {
+ void syncpromise_1.resolvedSyncPromise(item).then(function () {
+ // eslint-disable-next-line no-plusplus
+ if (!--counter) {
+ clearTimeout(capturedSetTimeout);
+ resolve(true);
+ }
+ }, reject);
+ });
+ });
+ }
+ return {
+ $: buffer,
+ add: add,
+ drain: drain,
+ };
+}
+exports.makePromiseBuffer = makePromiseBuffer;
+//# sourceMappingURL=promisebuffer.js.map
+
+/***/ }),
+
+/***/ 69377:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+var tslib_1 = __nccwpck_require__(4351);
+exports.DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds
+/**
+ * Extracts Retry-After value from the request header or returns default value
+ * @param header string representation of 'Retry-After' header
+ * @param now current unix timestamp
+ *
+ */
+function parseRetryAfterHeader(header, now) {
+ if (now === void 0) { now = Date.now(); }
+ var headerDelay = parseInt("" + header, 10);
+ if (!isNaN(headerDelay)) {
+ return headerDelay * 1000;
+ }
+ var headerDate = Date.parse("" + header);
+ if (!isNaN(headerDate)) {
+ return headerDate - now;
+ }
+ return exports.DEFAULT_RETRY_AFTER;
+}
+exports.parseRetryAfterHeader = parseRetryAfterHeader;
+/**
+ * Gets the time that given category is disabled until for rate limiting
+ */
+function disabledUntil(limits, category) {
+ return limits[category] || limits.all || 0;
+}
+exports.disabledUntil = disabledUntil;
+/**
+ * Checks if a category is rate limited
+ */
+function isRateLimited(limits, category, now) {
+ if (now === void 0) { now = Date.now(); }
+ return disabledUntil(limits, category) > now;
+}
+exports.isRateLimited = isRateLimited;
+/**
+ * Update ratelimits from incoming headers.
+ * Returns true if headers contains a non-empty rate limiting header.
+ */
+function updateRateLimits(limits, headers, now) {
+ var e_1, _a, e_2, _b;
+ if (now === void 0) { now = Date.now(); }
+ var updatedRateLimits = tslib_1.__assign({}, limits);
+ // "The name is case-insensitive."
+ // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get
+ var rateLimitHeader = headers['x-sentry-rate-limits'];
+ var retryAfterHeader = headers['retry-after'];
+ if (rateLimitHeader) {
+ try {
+ /**
+ * rate limit headers are of the form
+ * ,,..
+ * where each is of the form
+ * : : :
+ * where
+ * is a delay in seconds
+ * is the event type(s) (error, transaction, etc) being rate limited and is of the form
+ *